MDL-19810 upgraded calls to print_table, print_single_button, print_user_picture...
[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');
3b120e46 13 require_once($CFG->libdir.'/eventslib.php');
f15eb92c 14
fb992d71 15 $id = required_param('id', PARAM_INT); // Course Module ID
16 $mode = optional_param('mode', 'display', PARAM_ALPHA);
f15eb92c 17
18 list($cm, $course, $lesson) = lesson_get_basics($id);
19
20 require_login($course->id, false, $cm);
21
22 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
23
d927bb55 24 require_capability('mod/lesson:edit', $context);
f15eb92c 25
26/// Handle any preprocessing before header is printed - based on $mode
27 switch ($mode) {
28 case 'display': // Default view - get the necessary data
29 // Get lesson pages that are essay
646fc290 30 $params = array ("lessonid" => $lesson->id, "qtype" => LESSON_ESSAY);
31 if ($pages = $DB->get_records_select('lesson_pages', "lessonid = :lessonid AND qtype = :qtype", $params)) {
f15eb92c 32 // Get only the attempts that are in response to essay questions
646fc290 33 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
34 if ($essayattempts = $DB->get_records_select('lesson_attempts', 'pageid $usql', $parameters)) {
f15eb92c 35 // Get all the users who have taken this lesson, order by their last name
0ffa2c95 36 if (!empty($CFG->enablegroupings) && !empty($cm->groupingid)) {
e57bc529 37 $params["groupinid"] = $cm->groupingid;
0ffa2c95 38 $sql = "SELECT DISTINCT u.*
646fc290 39 FROM {lesson_attempts} a
40 INNER JOIN {user} u ON u.id = a.userid
41 INNER JOIN {groups_members} gm ON gm.userid = u.id
42 INNER JOIN {groupings_groups} gg ON gm.groupid = :groupinid
43 WHERE a.lessonid = :lessonid
0ffa2c95 44 ORDER BY u.lastname";
45 } else {
46 $sql = "SELECT u.*
646fc290 47 FROM {user} u,
48 {lesson_attempts} a
49 WHERE a.lessonid = :lessonid and
0ffa2c95 50 u.id = a.userid
51 ORDER BY u.lastname";
52 }
e57bc529 53 if (!$users = $DB->get_records_sql($sql, $params)) {
0ffa2c95 54 $mode = 'none'; // not displaying anything
55 lesson_set_message(get_string('noonehasanswered', 'lesson'));
f15eb92c 56 }
57 } else {
58 $mode = 'none'; // not displaying anything
59 lesson_set_message(get_string('noonehasanswered', 'lesson'));
60 }
61 } else {
62 $mode = 'none'; // not displaying anything
63 lesson_set_message(get_string('noessayquestionsfound', 'lesson'));
64 }
65 break;
66 case 'grade': // Grading form - get the necessary data
67 confirm_sesskey();
68
69 $attemptid = required_param('attemptid', PARAM_INT);
70
646fc290 71 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid))) {
86f93345 72 print_error('cannotfindattempt', 'lesson');
f15eb92c 73 }
646fc290 74 if (!$page = $DB->get_record('lesson_pages', array('id' => $attempt->pageid))) {
86f93345 75 print_error('cannotfindpages', 'lesson');
f15eb92c 76 }
646fc290 77 if (!$user = $DB->get_record('user', array('id' => $attempt->userid))) {
86f93345 78 print_error('cannotfinduser', 'lesson');
f15eb92c 79 }
646fc290 80 if (!$answer = $DB->get_record('lesson_answers', array('lessonid' => $lesson->id, 'pageid' => $page->id))) {
86f93345 81 print_error('cannotfindanswer', 'lesson');
f15eb92c 82 }
83 break;
84 case 'update':
294ce987 85 if (confirm_sesskey() and $form = data_submitted()) {
f15eb92c 86 if (optional_param('cancel', 0)) {
87 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
88 }
89
90 $attemptid = required_param('attemptid', PARAM_INT);
91
646fc290 92 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid))) {
86f93345 93 print_error('cannotfindattempt', 'lesson');
f15eb92c 94 }
646fc290 95 $params = array ("lessonid" => $lesson->id, "userid" => $attempt->userid);
96 if (!$grades = $DB->get_records_select('lesson_grades', "lessonid = :lessonid and userid = :userid", $params, 'completed', '*', $attempt->retry, 1)) {
86f93345 97 print_error('cannotfindgrade', 'lesson');
f15eb92c 98 }
99
100 $essayinfo = new stdClass;
101 $essayinfo = unserialize($attempt->useranswer);
102
103 $essayinfo->graded = 1;
104 $essayinfo->score = clean_param($form->score, PARAM_INT);
294ce987 105 $essayinfo->response = clean_param($form->response, PARAM_RAW);
f15eb92c 106 $essayinfo->sent = 0;
107 if (!$lesson->custom && $essayinfo->score == 1) {
108 $attempt->correct = 1;
109 } else {
110 $attempt->correct = 0;
111 }
112
294ce987 113 $attempt->useranswer = serialize($essayinfo);
f15eb92c 114
a8c31db2 115 $DB->update_record('lesson_attempts', $attempt);
f15eb92c 116
117 // Get grade information
118 $grade = current($grades);
119 $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
120
121 // Set and update
122 $updategrade->id = $grade->id;
123 $updategrade->grade = $gradeinfo->grade;
a8c31db2 124 $DB->update_record('lesson_grades', $updategrade);
125 // Log it
126 add_to_log($course->id, 'lesson', 'update grade', "essay.php?id=$cm->id", $lesson->name, $cm->id);
127
128 lesson_set_message(get_string('changessaved'), 'notifysuccess');
92bcca38 129
130 // update central gradebook
131 lesson_update_grades($lesson, $grade->userid);
132
260a56b1 133 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
f15eb92c 134 } else {
86f93345 135 print_error('invalidformdata');
f15eb92c 136 }
137 break;
138 case 'email': // Sending an email(s) to a single user or all
139 confirm_sesskey();
140
141 // Get our users (could be singular)
142 if ($userid = optional_param('userid', 0, PARAM_INT)) {
646fc290 143 $queryadd = " AND userid = :userid";
144 if (! $users = $DB->get_records('user', array('id' => $userid))) {
86f93345 145 print_error('cannotfinduser', 'lesson');
f15eb92c 146 }
147 } else {
148 $queryadd = '';
646fc290 149 $params = array ("lessonid" => $lesson->id);
150 if (!$users = $DB->get_records_sql("SELECT u.*
151 FROM {user} u,
152 {lesson_attempts} a
153 WHERE a.lessonid = :lessonid and
f15eb92c 154 u.id = a.userid
646fc290 155 ORDER BY u.lastname", $params)) {
86f93345 156 print_error('cannotfinduser', 'lesson');
f15eb92c 157 }
158 }
159
160 // Get lesson pages that are essay
646fc290 161 $params = array ("lessonid" => $lesson->id, "qtype" => LESSON_ESSAY);
162 if (!$pages = $DB->get_records_select('lesson_pages', "lessonid = :lessonid AND qtype = :qtype", $params)) {
86f93345 163 print_error('cannotfindpages', 'lesson');
f15eb92c 164 }
165
166 // Get only the attempts that are in response to essay questions
646fc290 167 list($usql, $params) = $DB->get_in_or_equal(array_keys($pages));
168 if (isset($queryadd) && $queryadd!='') {
169 $params["userid"] = $userid;
170 }
171 if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
771dc7b2 172 print_error('nooneansweredthisquestion', 'lesson');
f15eb92c 173 }
174 // Get the answers
646fc290 175 list($answerUsql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
176 $parameters["lessonid"] = $lesson->id;
177 if (!$answers = $DB->get_records_select('lesson_answers', "lessonid = :lessonid AND pageid $answerUsql", $parameters, '', 'pageid, score')) {
771dc7b2 178 print_error('cannotfindanswer', 'lesson');
f15eb92c 179 }
180 $options = new stdClass;
181 $options->noclean = true;
182
183 foreach ($attempts as $attempt) {
184 $essayinfo = unserialize($attempt->useranswer);
260a56b1 185 if ($essayinfo->graded and !$essayinfo->sent) {
186 // Holds values for the essayemailsubject string for the email message
187 $a = new stdClass;
188
189 // Set the grade
646fc290 190 $params = array ("lessonid" => $lesson->id, "userid" => $attempt->userid);
191 $grades = $DB->get_records_select('lesson_grades', "lessonid = :lessonid and userid = :userid", $params, 'completed', '*', $attempt->retry, 1);
260a56b1 192 $grade = current($grades);
193 $a->newgrade = $grade->grade;
194
195 // Set the points
f15eb92c 196 if ($lesson->custom) {
260a56b1 197 $a->earned = $essayinfo->score;
198 $a->outof = $answers[$attempt->pageid]->score;
f15eb92c 199 } else {
260a56b1 200 $a->earned = $essayinfo->score;
201 $a->outof = 1;
f15eb92c 202 }
9101efd3 203
260a56b1 204 // Set rest of the message values
205 $a->question = format_text($pages[$attempt->pageid]->contents, FORMAT_MOODLE, $options);
294ce987 206 $a->response = s($essayinfo->answer);
107470cb 207 $a->comment = s($essayinfo->response);
9101efd3 208
260a56b1 209 // Fetch message HTML and plain text formats
9101efd3 210 $message = get_string('essayemailmessage2', 'lesson', $a);
f15eb92c 211 $plaintxt = format_text_email($message, FORMAT_HTML);
212
260a56b1 213 // Subject
214 $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));
2044a2b2 215
3b120e46 216 $eventdata = new object();
217 $eventdata->modulename = 'lesson';
218 $eventdata->userfrom = $USER;
219 $eventdata->userto = $users[$attempt->userid];
220 $eventdata->subject = $subject;
221 $eventdata->fullmessage = $plaintext;
222 $eventdata->fullmessageformat = FORMAT_PLAIN;
223 $eventdata->fullmessagehtml = $message;
224 $eventdata->smallmessage = '';
225 if ( events_trigger('message_send', $eventdata) == 0){
f15eb92c 226 $essayinfo->sent = 1;
294ce987 227 $attempt->useranswer = serialize($essayinfo);
646fc290 228 $DB->update_record('lesson_attempts', $attempt);
f15eb92c 229 // Log it
230 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);
231 } else {
86f93345 232 print_error('emailfail');
f15eb92c 233 }
234 }
235 }
260a56b1 236 lesson_set_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
237 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
f15eb92c 238 break;
239 }
240
241 // Log it
242 add_to_log($course->id, 'lesson', 'view grade', "essay.php?id=$cm->id", get_string('manualgrading', 'lesson'), $cm->id);
243
244 lesson_print_header($cm, $course, $lesson, 'essay');
245
246 switch ($mode) {
247 case 'display':
248 // Expects $user, $essayattempts and $pages to be set already
249
250 // Group all the essays by userid
251 $studentessays = array();
252 foreach ($essayattempts as $essay) {
253 // Not very nice :) but basically
254 // this organizes the essays so we know how many
255 // times a student answered an essay per try and per page
256 $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
257 }
258
259 // Setup table
260 $table = new stdClass;
9101efd3 261 $table->head = array(get_string('name'), get_string('essays', 'lesson'), get_string('email', 'lesson'));
f15eb92c 262 $table->align = array('left', 'left', 'left');
263 $table->wrap = array('nowrap', 'nowrap', 'nowrap');
264
265 // Get the student ids of the users who have answered the essay question
266 $userids = array_keys($studentessays);
267
268 // Cycle through all the students
269 foreach ($userids as $userid) {
270 $studentname = fullname($users[$userid], true);
271 $essaylinks = array();
272
273 // Number of attempts on the lesson
318e3745 274 $attempts = $DB->count_records('lesson_grades', array('userid'=>$userid, 'lessonid'=>$lesson->id));
f15eb92c 275
276 // Go through each essay page
277 foreach ($studentessays[$userid] as $page => $tries) {
278 $count = 0;
279
280 // Go through each attempt per page
281 foreach($tries as $try) {
282 if ($count == $attempts) {
283 break; // Stop displaying essays (attempt not completed)
284 }
285 $count++;
286
287 // Make sure they didn't answer it more than the max number of attmepts
288 if (count($try) > $lesson->maxattempts) {
289 $essay = $try[$lesson->maxattempts-1];
290 } else {
291 $essay = end($try);
292 }
293
294 // Start processing the attempt
295 $essayinfo = unserialize($essay->useranswer);
296
297 // Different colors for all the states of an essay (graded, if sent, not graded)
298 if (!$essayinfo->graded) {
299 $class = ' class="graded"';
300 } elseif (!$essayinfo->sent) {
301 $class = ' class="sent"';
302 } else {
303 $class = ' class="ungraded"';
304 }
305 // link for each essay
306 $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>';
307 }
308 }
309 // email link for this user
310 $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>';
311
312 $table->data[] = array(print_user_picture($userid, $course->id, $users[$userid]->picture, 0, true).$studentname, implode("<br />\n", $essaylinks), $emaillink);
313 }
314 // email link for all users
315 $emailalllink = "<a href=\"$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id&amp;mode=email&amp;sesskey=".sesskey().'">'.get_string('emailallgradedessays', 'lesson').'</a>';
316
317 $table->data[] = array(' ', ' ', $emailalllink);
318
319 print_table($table);
320 break;
321 case 'grade':
322 // Grading form
323 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
324
325 echo '<div class="grade">
b7dc2256 326 <form id="essaygrade" method="post" action="'.$CFG->wwwroot.'/mod/lesson/essay.php">
f15eb92c 327 <input type="hidden" name="id" value="'.$cm->id.'" />
328 <input type="hidden" name="mode" value="update" />
329 <input type="hidden" name="attemptid" value="'.$attemptid.'" />
330 <input type="hidden" name="sesskey" value="'.sesskey().'" />';
331
332 // All tables will have these settings
333 $table = new stdClass;
334 $table->align = array('left');
335 $table->wrap = array();
336 $table->width = '50%';
337 $table->size = array('100%');
338 $table->class = 'generaltable gradetable';
339
340 // Print the question
341 $table->head = array(get_string('question', 'lesson'));
342 $options = new stdClass;
343 $options->noclean = true;
344 $table->data[] = array(format_text($page->contents, FORMAT_MOODLE, $options));
345
346 print_table($table);
347
348 unset($table->data);
349
350 // Now the user's answer
351 $essayinfo = unserialize($attempt->useranswer);
352
353 $table->head = array(get_string('studentresponse', 'lesson', fullname($user, true)));
294ce987 354 $table->data[] = array(s($essayinfo->answer));
f15eb92c 355
356 print_table($table);
357
358 unset($table->data);
359
360 // Now a response box and grade drop-down for grader
361 $table->head = array(get_string('comments', 'lesson'));
107470cb 362 $table->data[] = array(print_textarea(false, 15, 60, 0, 0, 'response', $essayinfo->response, $course->id, true));
f15eb92c 363 $options = array();
364 if ($lesson->custom) {
365 for ($i=$answer->score; $i>=0; $i--) {
366 $options[$i] = $i;
367 }
368 } else {
369 $options[0] = get_string('nocredit', 'lesson');
370 $options[1] = get_string('credit', 'lesson');
371 }
955ee33d 372 $select = html_select::make($options, 'score', $essayinfo->score, false);
373 $select->nothingvalue = '';
374 $table->data[] = array(get_string('essayscore', 'lesson').': '.$OUTPUT->select($select));
f15eb92c 375
376 print_table($table);
377 echo '<div class="buttons">
378 <input type="submit" name="cancel" value="'.get_string('cancel').'" />
379 <input type="submit" value="'.get_string('savechanges').'" />
380 </div>
381 </form>
382 </div>';
383 break;
384 }
385
f7e6b862 386 echo $OUTPUT->footer();
86f93345 387?>