grade_update now supports more grade_item properties
[moodle.git] / mod / lesson / essay.php
CommitLineData
f15eb92c 1<?php // $Id$
2/**
3 * Provides the interface for grading essay questions
4 *
5 * @version $Id$
6 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7 * @package lesson
8 **/
9
10 require_once('../../config.php');
11 require_once('locallib.php');
12 require_once('lib.php');
13
fb992d71 14 $id = required_param('id', PARAM_INT); // Course Module ID
15 $mode = optional_param('mode', 'display', PARAM_ALPHA);
f15eb92c 16
17 list($cm, $course, $lesson) = lesson_get_basics($id);
18
19 require_login($course->id, false, $cm);
20
21 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
22
d927bb55 23 require_capability('mod/lesson:edit', $context);
f15eb92c 24
25/// Handle any preprocessing before header is printed - based on $mode
26 switch ($mode) {
27 case 'display': // Default view - get the necessary data
28 // Get lesson pages that are essay
29 if ($pages = get_records_select('lesson_pages', "lessonid = $lesson->id AND qtype = ".LESSON_ESSAY)) {
30 // Get only the attempts that are in response to essay questions
31 if ($essayattempts = get_records_select('lesson_attempts', 'pageid IN('.implode(',', array_keys($pages)).')')) {
32 // Get all the users who have taken this lesson, order by their last name
51693108 33 if (!$users = get_records_sql("SELECT u.*
f15eb92c 34 FROM {$CFG->prefix}user u,
35 {$CFG->prefix}lesson_attempts a
36 WHERE a.lessonid = '$lesson->id' and
37 u.id = a.userid
38 ORDER BY u.lastname")) {
39 error('Error: could not find users');
40 }
41 } else {
42 $mode = 'none'; // not displaying anything
43 lesson_set_message(get_string('noonehasanswered', 'lesson'));
44 }
45 } else {
46 $mode = 'none'; // not displaying anything
47 lesson_set_message(get_string('noessayquestionsfound', 'lesson'));
48 }
49 break;
50 case 'grade': // Grading form - get the necessary data
51 confirm_sesskey();
52
53 $attemptid = required_param('attemptid', PARAM_INT);
54
55 if (!$attempt = get_record('lesson_attempts', 'id', $attemptid)) {
56 error('Error: could not find attempt');
57 }
58 if (!$page = get_record('lesson_pages', 'id', $attempt->pageid)) {
59 error('Error: could not find lesson page');
60 }
61 if (!$user = get_record('user', 'id', $attempt->userid)) {
62 error('Error: could not find users');
63 }
64 if (!$answer = get_record('lesson_answers', 'lessonid', $lesson->id, 'pageid', $page->id)) {
65 error('Error: could not find answer');
66 }
67 break;
68 case 'update':
69 if (confirm_sesskey() and $form = data_submitted($CFG->wwwroot.'/mod/lesson/essay.php')) {
70 if (optional_param('cancel', 0)) {
71 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
72 }
73
74 $attemptid = required_param('attemptid', PARAM_INT);
75
76 if (!$attempt = get_record('lesson_attempts', 'id', $attemptid)) {
77 error('Error: could not find essay');
78 }
79 if (!$grades = get_records_select('lesson_grades', "lessonid = $lesson->id and userid = $attempt->userid", 'completed', '*', $attempt->retry, 1)) {
80 error('Error: could not find grades');
81 }
82
83 $essayinfo = new stdClass;
84 $essayinfo = unserialize($attempt->useranswer);
85
86 $essayinfo->graded = 1;
87 $essayinfo->score = clean_param($form->score, PARAM_INT);
107470cb 88 $essayinfo->response = stripslashes_safe(clean_param($form->response, PARAM_RAW));
f15eb92c 89 $essayinfo->sent = 0;
90 if (!$lesson->custom && $essayinfo->score == 1) {
91 $attempt->correct = 1;
92 } else {
93 $attempt->correct = 0;
94 }
95
96 $attempt->useranswer = addslashes(serialize($essayinfo));
97
98 if (!update_record('lesson_attempts', $attempt)) {
99 error('Could not update essay score');
100 }
101
102 // Get grade information
103 $grade = current($grades);
104 $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
105
106 // Set and update
107 $updategrade->id = $grade->id;
108 $updategrade->grade = $gradeinfo->grade;
109 if(update_record('lesson_grades', $updategrade)) {
110 // Log it
111 add_to_log($course->id, 'lesson', 'update grade', "essay.php?id=$cm->id", $lesson->name, $cm->id);
112
260a56b1 113 lesson_set_message(get_string('changessaved'), 'notifysuccess');
f15eb92c 114 } else {
260a56b1 115 lesson_set_message(get_string('updatefailed', 'lesson'));
f15eb92c 116 }
260a56b1 117 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
f15eb92c 118 } else {
119 error('Something is wrong with the form data');
120 }
121 break;
122 case 'email': // Sending an email(s) to a single user or all
123 confirm_sesskey();
124
125 // Get our users (could be singular)
126 if ($userid = optional_param('userid', 0, PARAM_INT)) {
127 $queryadd = " AND userid = $userid";
128 if (! $users = get_records('user', 'id', $userid)) {
129 error('Error: could not find users');
130 }
131 } else {
132 $queryadd = '';
51693108 133 if (!$users = get_records_sql("SELECT u.*
f15eb92c 134 FROM {$CFG->prefix}user u,
135 {$CFG->prefix}lesson_attempts a
136 WHERE a.lessonid = '$lesson->id' and
137 u.id = a.userid
138 ORDER BY u.lastname")) {
139 error('Error: could not find users');
140 }
141 }
142
143 // Get lesson pages that are essay
144 if (!$pages = get_records_select('lesson_pages', "lessonid = $lesson->id AND qtype = ".LESSON_ESSAY)) {
145 error('Error: could not find lesson pages');
146 }
147
148 // Get only the attempts that are in response to essay questions
149 $pageids = implode(',', array_keys($pages)); // all the pageids in comma seperated list
150 if (!$attempts = get_records_select('lesson_attempts', "pageid IN($pageids)".$queryadd)) {
151 error ('No one has answered essay questions yet...');
152 }
153 // Get the answers
154 if (!$answers = get_records_select('lesson_answers', "lessonid = $lesson->id AND pageid IN($pageids)", '', 'pageid, score')) {
155 error ('Could not find answer records.');
156 }
157 $options = new stdClass;
158 $options->noclean = true;
159
160 foreach ($attempts as $attempt) {
161 $essayinfo = unserialize($attempt->useranswer);
260a56b1 162 if ($essayinfo->graded and !$essayinfo->sent) {
163 // Holds values for the essayemailsubject string for the email message
164 $a = new stdClass;
165
166 // Set the grade
f15eb92c 167 $grades = get_records_select('lesson_grades', "lessonid = $lesson->id and userid = $attempt->userid", 'completed', '*', $attempt->retry, 1);
260a56b1 168 $grade = current($grades);
169 $a->newgrade = $grade->grade;
170
171 // Set the points
f15eb92c 172 if ($lesson->custom) {
260a56b1 173 $a->earned = $essayinfo->score;
174 $a->outof = $answers[$attempt->pageid]->score;
f15eb92c 175 } else {
260a56b1 176 $a->earned = $essayinfo->score;
177 $a->outof = 1;
f15eb92c 178 }
260a56b1 179
180 // Set rest of the message values
181 $a->question = format_text($pages[$attempt->pageid]->contents, FORMAT_MOODLE, $options);
107470cb 182 $a->response = s(stripslashes_safe($essayinfo->answer));
260a56b1 183 $a->teacher = $course->teacher;
107470cb 184 $a->comment = s($essayinfo->response);
260a56b1 185
186
187 // Fetch message HTML and plain text formats
188 $message = get_string('essayemailmessage', 'lesson', $a);
f15eb92c 189 $plaintxt = format_text_email($message, FORMAT_HTML);
190
260a56b1 191 // Subject
192 $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));
193
f15eb92c 194 if(email_to_user($users[$attempt->userid], $USER, $subject, $plaintxt, $message)) {
195 $essayinfo->sent = 1;
196 $attempt->useranswer = addslashes(serialize($essayinfo));
197 update_record('lesson_attempts', $attempt);
198 // Log it
199 add_to_log($course->id, 'lesson', 'update email essay grade', "essay.php?id=$cm->id", format_string($pages[$attempt->pageid]->title,true).': '.fullname($users[$attempt->userid]), $cm->id);
200 } else {
201 error('Emailing Failed');
202 }
203 }
204 }
260a56b1 205 lesson_set_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
206 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
f15eb92c 207 break;
208 }
209
210 // Log it
211 add_to_log($course->id, 'lesson', 'view grade', "essay.php?id=$cm->id", get_string('manualgrading', 'lesson'), $cm->id);
212
213 lesson_print_header($cm, $course, $lesson, 'essay');
214
215 switch ($mode) {
216 case 'display':
217 // Expects $user, $essayattempts and $pages to be set already
218
219 // Group all the essays by userid
220 $studentessays = array();
221 foreach ($essayattempts as $essay) {
222 // Not very nice :) but basically
223 // this organizes the essays so we know how many
224 // times a student answered an essay per try and per page
225 $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
226 }
227
228 // Setup table
229 $table = new stdClass;
230 $table->head = array($course->students, get_string('essays', 'lesson'), get_string('email', 'lesson'));
231 $table->align = array('left', 'left', 'left');
232 $table->wrap = array('nowrap', 'nowrap', 'nowrap');
233
234 // Get the student ids of the users who have answered the essay question
235 $userids = array_keys($studentessays);
236
237 // Cycle through all the students
238 foreach ($userids as $userid) {
239 $studentname = fullname($users[$userid], true);
240 $essaylinks = array();
241
242 // Number of attempts on the lesson
243 $attempts = count_records('lesson_grades', 'userid', $userid, 'lessonid', $lesson->id);
244
245 // Go through each essay page
246 foreach ($studentessays[$userid] as $page => $tries) {
247 $count = 0;
248
249 // Go through each attempt per page
250 foreach($tries as $try) {
251 if ($count == $attempts) {
252 break; // Stop displaying essays (attempt not completed)
253 }
254 $count++;
255
256 // Make sure they didn't answer it more than the max number of attmepts
257 if (count($try) > $lesson->maxattempts) {
258 $essay = $try[$lesson->maxattempts-1];
259 } else {
260 $essay = end($try);
261 }
262
263 // Start processing the attempt
264 $essayinfo = unserialize($essay->useranswer);
265
266 // Different colors for all the states of an essay (graded, if sent, not graded)
267 if (!$essayinfo->graded) {
268 $class = ' class="graded"';
269 } elseif (!$essayinfo->sent) {
270 $class = ' class="sent"';
271 } else {
272 $class = ' class="ungraded"';
273 }
274 // link for each essay
275 $essaylinks[] = "<a$class href=\"$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id&amp;mode=grade&amp;attemptid=$essay->id&amp;sesskey=".sesskey().'">'.userdate($essay->timeseen, get_string('strftimedatetime')).' '.format_string($pages[$essay->pageid]->title,true).'</a>';
276 }
277 }
278 // email link for this user
279 $emaillink = "<a href=\"$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id&amp;mode=email&amp;userid=$userid&amp;sesskey=".sesskey().'">'.get_string('emailgradedessays', 'lesson').'</a>';
280
281 $table->data[] = array(print_user_picture($userid, $course->id, $users[$userid]->picture, 0, true).$studentname, implode("<br />\n", $essaylinks), $emaillink);
282 }
283 // email link for all users
284 $emailalllink = "<a href=\"$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id&amp;mode=email&amp;sesskey=".sesskey().'">'.get_string('emailallgradedessays', 'lesson').'</a>';
285
286 $table->data[] = array(' ', ' ', $emailalllink);
287
288 print_table($table);
289 break;
290 case 'grade':
291 // Grading form
292 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
293
294 echo '<div class="grade">
b7dc2256 295 <form id="essaygrade" method="post" action="'.$CFG->wwwroot.'/mod/lesson/essay.php">
f15eb92c 296 <input type="hidden" name="id" value="'.$cm->id.'" />
297 <input type="hidden" name="mode" value="update" />
298 <input type="hidden" name="attemptid" value="'.$attemptid.'" />
299 <input type="hidden" name="sesskey" value="'.sesskey().'" />';
300
301 // All tables will have these settings
302 $table = new stdClass;
303 $table->align = array('left');
304 $table->wrap = array();
305 $table->width = '50%';
306 $table->size = array('100%');
307 $table->class = 'generaltable gradetable';
308
309 // Print the question
310 $table->head = array(get_string('question', 'lesson'));
311 $options = new stdClass;
312 $options->noclean = true;
313 $table->data[] = array(format_text($page->contents, FORMAT_MOODLE, $options));
314
315 print_table($table);
316
317 unset($table->data);
318
319 // Now the user's answer
320 $essayinfo = unserialize($attempt->useranswer);
321
322 $table->head = array(get_string('studentresponse', 'lesson', fullname($user, true)));
107470cb 323 $table->data[] = array(s(stripslashes_safe($essayinfo->answer)));
f15eb92c 324
325 print_table($table);
326
327 unset($table->data);
328
329 // Now a response box and grade drop-down for grader
330 $table->head = array(get_string('comments', 'lesson'));
107470cb 331 $table->data[] = array(print_textarea(false, 15, 60, 0, 0, 'response', $essayinfo->response, $course->id, true));
f15eb92c 332 $options = array();
333 if ($lesson->custom) {
334 for ($i=$answer->score; $i>=0; $i--) {
335 $options[$i] = $i;
336 }
337 } else {
338 $options[0] = get_string('nocredit', 'lesson');
339 $options[1] = get_string('credit', 'lesson');
340 }
341 $table->data[] = array(get_string('essayscore', 'lesson').': '.choose_from_menu($options, 'score', $essayinfo->score, '', '', '', true));
342
343 print_table($table);
344 echo '<div class="buttons">
345 <input type="submit" name="cancel" value="'.get_string('cancel').'" />
346 <input type="submit" value="'.get_string('savechanges').'" />
347 </div>
348 </form>
349 </div>';
350 break;
351 }
352
353 print_footer($course);
354?>