MDL-39261 mod_lesson: Rewrite the answer URL for grading
[moodle.git] / mod / lesson / essay.php
CommitLineData
86342d63 1<?php
0a4abb73
SH
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
f15eb92c 18/**
19 * Provides the interface for grading essay questions
20 *
9b24f68b 21 * @package mod_lesson
cc3dbaaa
PS
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
f15eb92c 24 **/
25
0a4abb73
SH
26require_once('../../config.php');
27require_once($CFG->dirroot.'/mod/lesson/locallib.php');
ebf5ad4f 28require_once($CFG->dirroot.'/mod/lesson/pagetypes/essay.php');
0a4abb73 29require_once($CFG->dirroot.'/mod/lesson/essay_form.php');
0a4abb73
SH
30
31$id = required_param('id', PARAM_INT); // Course Module ID
32$mode = optional_param('mode', 'display', PARAM_ALPHA);
b3daa926 33
0e35ba6f 34$cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST);
74df2951 35$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
f5771482
AG
36$dblesson = $DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST);
37$lesson = new lesson($dblesson);
b3daa926 38
0a4abb73 39require_login($course, false, $cm);
5918e371 40$context = context_module::instance($cm->id);
5fc6a9e7 41require_capability('mod/lesson:grade', $context);
0a4abb73 42
a6855934 43$url = new moodle_url('/mod/lesson/essay.php', array('id'=>$id));
0a4abb73
SH
44if ($mode !== 'display') {
45 $url->param('mode', $mode);
46}
47$PAGE->set_url($url);
86342d63 48
fdc790fc
GF
49$currentgroup = groups_get_activity_group($cm, true);
50
4bb7783e
RW
51$attempt = new stdClass();
52$user = new stdClass();
53$attemptid = optional_param('attemptid', 0, PARAM_INT);
54
59f1c9f5
JMV
55$formattextdefoptions = new stdClass();
56$formattextdefoptions->noclean = true;
57$formattextdefoptions->para = false;
58$formattextdefoptions->context = $context;
59
4bb7783e
RW
60if ($attemptid > 0) {
61 $attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid));
62 $answer = $DB->get_record('lesson_answers', array('lessonid' => $lesson->id, 'pageid' => $attempt->pageid));
63 $user = $DB->get_record('user', array('id' => $attempt->userid));
e0e1a83e
JMV
64 // Apply overrides.
65 $lesson->update_effective_access($user->id);
4bb7783e
RW
66 $scoreoptions = array();
67 if ($lesson->custom) {
68 $i = $answer->score;
69 while ($i >= 0) {
70 $scoreoptions[$i] = (string)$i;
71 $i--;
72 }
73 } else {
74 $scoreoptions[0] = get_string('nocredit', 'lesson');
75 $scoreoptions[1] = get_string('credit', 'lesson');
b38f0baa 76 }
b38f0baa 77}
4bb7783e 78
f15eb92c 79/// Handle any preprocessing before header is printed - based on $mode
0a4abb73
SH
80switch ($mode) {
81 case 'grade':
82 // Grading form - get the necessary data
83 require_sesskey();
84
4bb7783e 85 if (empty($attempt)) {
0a4abb73
SH
86 print_error('cannotfindattempt', 'lesson');
87 }
4bb7783e 88 if (empty($user)) {
0a4abb73
SH
89 print_error('cannotfinduser', 'lesson');
90 }
4bb7783e 91 if (empty($answer)) {
0a4abb73
SH
92 print_error('cannotfindanswer', 'lesson');
93 }
94 break;
95
96 case 'update':
97 require_sesskey();
4bb7783e
RW
98
99 if (empty($attempt)) {
100 print_error('cannotfindattempt', 'lesson');
101 }
102 if (empty($user)) {
103 print_error('cannotfinduser', 'lesson');
104 }
105
ebf5ad4f
JMV
106 $editoroptions = array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES,
107 'maxbytes' => $CFG->maxbytes, 'context' => $context);
108 $essayinfo = lesson_page_type_essay::extract_useranswer($attempt->useranswer);
109 $essayinfo = file_prepare_standard_editor($essayinfo, 'response', $editoroptions, $context,
110 'mod_lesson', 'essay_responses', $attempt->id);
111 $mform = new essay_grading_form(null, array('scoreoptions' => $scoreoptions, 'user' => $user));
112 $mform->set_data($essayinfo);
b38f0baa
AB
113 if ($mform->is_cancelled()) {
114 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
115 }
0a4abb73 116 if ($form = $mform->get_data()) {
0a4abb73
SH
117 if (!$grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1)) {
118 print_error('cannotfindgrade', 'lesson');
f15eb92c 119 }
86342d63 120
0a4abb73 121 $essayinfo->graded = 1;
4bb7783e 122 $essayinfo->score = $form->score;
ebf5ad4f
JMV
123 $form = file_postupdate_standard_editor($form, 'response', $editoroptions, $context,
124 'mod_lesson', 'essay_responses', $attempt->id);
125 $essayinfo->response = $form->response;
126 $essayinfo->responseformat = $form->responseformat;
0a4abb73
SH
127 $essayinfo->sent = 0;
128 if (!$lesson->custom && $essayinfo->score == 1) {
129 $attempt->correct = 1;
130 } else {
131 $attempt->correct = 0;
132 }
f15eb92c 133
0a4abb73 134 $attempt->useranswer = serialize($essayinfo);
f15eb92c 135
0a4abb73 136 $DB->update_record('lesson_attempts', $attempt);
f15eb92c 137
0a4abb73
SH
138 // Get grade information
139 $grade = current($grades);
140 $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
86342d63 141
0a4abb73 142 // Set and update
39790bd8 143 $updategrade = new stdClass();
0a4abb73
SH
144 $updategrade->id = $grade->id;
145 $updategrade->grade = $gradeinfo->grade;
146 $DB->update_record('lesson_grades', $updategrade);
f5771482
AG
147
148 $params = array(
149 'context' => $context,
150 'objectid' => $grade->id,
151 'courseid' => $course->id,
152 'relateduserid' => $attempt->userid,
153 'other' => array(
154 'lessonid' => $lesson->id,
155 'attemptid' => $attemptid
156 )
157 );
158 $event = \mod_lesson\event\essay_assessed::create($params);
159 $event->add_record_snapshot('lesson', $dblesson);
160 $event->trigger();
86342d63 161
0a4abb73 162 $lesson->add_message(get_string('changessaved'), 'notifysuccess');
86342d63 163
0a4abb73
SH
164 // update central gradebook
165 lesson_update_grades($lesson, $grade->userid);
92bcca38 166
a6855934 167 redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
0a4abb73
SH
168 } else {
169 print_error('invalidformdata');
170 }
171 break;
172 case 'email':
173 // Sending an email(s) to a single user or all
174 require_sesskey();
92bcca38 175
0a4abb73
SH
176 // Get our users (could be singular)
177 if ($userid = optional_param('userid', 0, PARAM_INT)) {
178 $queryadd = " AND userid = ?";
179 if (! $users = $DB->get_records('user', array('id' => $userid))) {
180 print_error('cannotfinduser', 'lesson');
f15eb92c 181 }
0a4abb73
SH
182 } else {
183 $queryadd = '';
fdc790fc
GF
184
185 // If group selected, only send to group members.
186 list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
187 list($sort, $sortparams) = users_order_by_sql('u');
188 $params['lessonid'] = $lesson->id;
189
e07c51c4
EL
190 // Need to use inner view to avoid distinct + text
191 if (!$users = $DB->get_records_sql("
192 SELECT u.*
193 FROM {user} u
194 JOIN (
9695ff81
TH
195 SELECT DISTINCT userid
196 FROM {lesson_attempts}
197 WHERE lessonid = :lessonid
fdc790fc
GF
198 ) ui ON u.id = ui.userid
199 JOIN ($esql) ue ON ue.id = u.id
200 ORDER BY $sort", $params)) {
0a4abb73 201 print_error('cannotfinduser', 'lesson');
f15eb92c 202 }
0a4abb73 203 }
f15eb92c 204
0a4abb73
SH
205 $pages = $lesson->load_all_pages();
206 foreach ($pages as $key=>$page) {
814e381a 207 if ($page->qtype != LESSON_PAGE_ESSAY) {
0a4abb73 208 unset($pages[$key]);
f15eb92c 209 }
0a4abb73
SH
210 }
211
212 // Get only the attempts that are in response to essay questions
213 list($usql, $params) = $DB->get_in_or_equal(array_keys($pages));
214 if (!empty($queryadd)) {
215 $params[] = $userid;
216 }
217 if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
218 print_error('nooneansweredthisquestion', 'lesson');
219 }
220 // Get the answers
221 list($answerUsql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
222 array_unshift($parameters, $lesson->id);
223 if (!$answers = $DB->get_records_select('lesson_answers', "lessonid = ? AND pageid $answerUsql", $parameters, '', 'pageid, score')) {
224 print_error('cannotfindanswer', 'lesson');
225 }
0a4abb73
SH
226
227 foreach ($attempts as $attempt) {
ebf5ad4f 228 $essayinfo = lesson_page_type_essay::extract_useranswer($attempt->useranswer);
0a4abb73
SH
229 if ($essayinfo->graded && !$essayinfo->sent) {
230 // Holds values for the essayemailsubject string for the email message
231 $a = new stdClass;
232
233 // Set the grade
234 $grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1);
235 $grade = current($grades);
236 $a->newgrade = $grade->grade;
237
238 // Set the points
239 if ($lesson->custom) {
240 $a->earned = $essayinfo->score;
241 $a->outof = $answers[$attempt->pageid]->score;
242 } else {
243 $a->earned = $essayinfo->score;
244 $a->outof = 1;
245 }
f15eb92c 246
0a4abb73
SH
247 // Set rest of the message values
248 $currentpage = $lesson->load_page($attempt->pageid);
59f1c9f5 249 $a->question = format_text($currentpage->contents, $currentpage->contentsformat, $formattextdefoptions);
676eca7b
P
250 $answer = file_rewrite_pluginfile_urls($essayinfo->answer, 'pluginfile.php', $context->id,
251 'mod_lesson', 'essay_responses', $attempt->id);
252 $a->response = format_text($answer, $essayinfo->answerformat,
59f1c9f5 253 array('context' => $context, 'para' => true));
ebf5ad4f
JMV
254 $a->comment = $essayinfo->response;
255 $a->comment = file_rewrite_pluginfile_urls($a->comment, 'pluginfile.php', $context->id,
256 'mod_lesson', 'essay_responses', $attempt->id);
257 $a->comment = format_text($a->comment, $essayinfo->responseformat, $formattextdefoptions);
5df7f123 258 $a->lesson = format_string($lesson->name, true);
0a4abb73
SH
259
260 // Fetch message HTML and plain text formats
261 $message = get_string('essayemailmessage2', 'lesson', $a);
262 $plaintext = format_text_email($message, FORMAT_HTML);
263
264 // Subject
5df7f123 265 $subject = get_string('essayemailsubject', 'lesson');
0a4abb73 266
cc350fd9
AD
267 // Context url.
268 $contexturl = new moodle_url('/grade/report/user/index.php', array('id' => $course->id));
269
270 $eventdata = new \core\message\message();
271 $eventdata->courseid = $course->id;
0a4abb73
SH
272 $eventdata->modulename = 'lesson';
273 $eventdata->userfrom = $USER;
274 $eventdata->userto = $users[$attempt->userid];
275 $eventdata->subject = $subject;
276 $eventdata->fullmessage = $plaintext;
277 $eventdata->fullmessageformat = FORMAT_PLAIN;
278 $eventdata->fullmessagehtml = $message;
0e8b5160 279 $eventdata->smallmessage = '';
cc350fd9 280 $eventdata->contexturl = $contexturl;
0a4abb73
SH
281
282 // Required for messaging framework
283 $eventdata->component = 'mod_lesson';
284 $eventdata->name = 'graded_essay';
2f67a9b3 285
0a4abb73
SH
286 message_send($eventdata);
287 $essayinfo->sent = 1;
288 $attempt->useranswer = serialize($essayinfo);
289 $DB->update_record('lesson_attempts', $attempt);
646fc290 290 }
0a4abb73
SH
291 }
292 $lesson->add_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
a6855934 293 redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
0a4abb73
SH
294 break;
295 case 'display': // Default view - get the necessary data
296 default:
297 // Get lesson pages that are essay
298 $pages = $lesson->load_all_pages();
299 foreach ($pages as $key=>$page) {
814e381a 300 if ($page->qtype != LESSON_PAGE_ESSAY) {
0a4abb73 301 unset($pages[$key]);
f15eb92c 302 }
0a4abb73
SH
303 }
304 if (count($pages) > 0) {
0a4abb73 305 // Get only the attempts that are in response to essay questions
fdc790fc
GF
306 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($pages), SQL_PARAMS_NAMED);
307 // If group selected, only get group members attempts.
308 list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
309 $parameters = array_merge($params, $parameters);
310
311 $sql = "SELECT a.*
312 FROM {lesson_attempts} a
313 JOIN ($esql) ue ON a.userid = ue.id
314 WHERE pageid $usql";
315 if ($essayattempts = $DB->get_records_sql($sql, $parameters)) {
eae1948c 316 $ufields = user_picture::fields('u');
fdc790fc 317 // Get all the users who have taken this lesson.
9695ff81 318 list($sort, $sortparams) = users_order_by_sql('u');
fdc790fc
GF
319
320 $params['lessonid'] = $lesson->id;
157771a3 321 $sql = "SELECT DISTINCT $ufields
fdc790fc
GF
322 FROM {user} u
323 JOIN {lesson_attempts} a ON u.id = a.userid
324 JOIN ($esql) ue ON ue.id = a.userid
325 WHERE a.lessonid = :lessonid
157771a3 326 ORDER BY $sort";
0a4abb73
SH
327 if (!$users = $DB->get_records_sql($sql, $params)) {
328 $mode = 'none'; // not displaying anything
fdc790fc
GF
329 if (!empty($currentgroup)) {
330 $groupname = groups_get_group_name($currentgroup);
331 $lesson->add_message(get_string('noonehasansweredgroup', 'lesson', $groupname));
332 } else {
333 $lesson->add_message(get_string('noonehasanswered', 'lesson'));
334 }
0a4abb73
SH
335 }
336 } else {
337 $mode = 'none'; // not displaying anything
fdc790fc
GF
338 if (!empty($currentgroup)) {
339 $groupname = groups_get_group_name($currentgroup);
340 $lesson->add_message(get_string('noonehasansweredgroup', 'lesson', $groupname));
341 } else {
342 $lesson->add_message(get_string('noonehasanswered', 'lesson'));
343 }
f15eb92c 344 }
0a4abb73
SH
345 } else {
346 $mode = 'none'; // not displaying anything
347 $lesson->add_message(get_string('noessayquestionsfound', 'lesson'));
348 }
349 break;
350}
0a4abb73 351
649cf95d 352$lessonoutput = $PAGE->get_renderer('mod_lesson');
d42bc7dc 353echo $lessonoutput->header($lesson, $cm, 'essay', false, null, get_string('manualgrading', 'lesson'));
0a4abb73
SH
354
355switch ($mode) {
356 case 'display':
fdc790fc 357 groups_print_activity_menu($cm, $url);
0a4abb73
SH
358 // Expects $user, $essayattempts and $pages to be set already
359
360 // Group all the essays by userid
361 $studentessays = array();
362 foreach ($essayattempts as $essay) {
363 // Not very nice :) but basically
364 // this organizes the essays so we know how many
365 // times a student answered an essay per try and per page
366 $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
367 }
368
369 // Setup table
370 $table = new html_table();
a86b7560
MG
371 $table->head = array(get_string('name'), get_string('essays', 'lesson'), get_string('status'),
372 get_string('email', 'lesson'));
16be8974 373 $table->attributes['class'] = 'standardtable generaltable';
0a4abb73
SH
374 $table->align = array('left', 'left', 'left');
375 $table->wrap = array('nowrap', 'nowrap', '');
376
377 // Cycle through all the students
378 foreach (array_keys($studentessays) as $userid) {
379 $studentname = fullname($users[$userid], true);
380 $essaylinks = array();
a86b7560 381 $essaystatuses = array();
0a4abb73
SH
382
383 // Number of attempts on the lesson
37029e46 384 $attempts = $lesson->count_user_retries($userid);
0a4abb73
SH
385
386 // Go through each essay page
387 foreach ($studentessays[$userid] as $page => $tries) {
388 $count = 0;
389
390 // Go through each attempt per page
391 foreach($tries as $try) {
392 if ($count == $attempts) {
393 break; // Stop displaying essays (attempt not completed)
394 }
395 $count++;
396
397 // Make sure they didn't answer it more than the max number of attmepts
398 if (count($try) > $lesson->maxattempts) {
399 $essay = $try[$lesson->maxattempts-1];
f15eb92c 400 } else {
0a4abb73 401 $essay = end($try);
f15eb92c 402 }
9101efd3 403
0a4abb73 404 // Start processing the attempt
ebf5ad4f 405 $essayinfo = lesson_page_type_essay::extract_useranswer($essay->useranswer);
0a4abb73
SH
406
407 // link for each essay
a6855934 408 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'grade','attemptid'=>$essay->id,'sesskey'=>sesskey()));
a86b7560
MG
409 $linktitle = userdate($essay->timeseen, get_string('strftimedatetime')).' '.
410 format_string($pages[$essay->pageid]->title, true);
411
0a4abb73
SH
412 // Different colors for all the states of an essay (graded, if sent, not graded)
413 if (!$essayinfo->graded) {
a86b7560
MG
414 $class = "label label-warning";
415 $status = get_string('notgraded', 'lesson');
0a4abb73 416 } elseif (!$essayinfo->sent) {
a86b7560
MG
417 $class = "label label-success";
418 $status = get_string('graded', 'lesson');
0a4abb73 419 } else {
a86b7560
MG
420 $class = "label label-success";
421 $status = get_string('sent', 'lesson');
0a4abb73 422 }
a86b7560
MG
423 $attributes = array('tabindex' => 0);
424
425 $essaylinks[] = html_writer::link($url, $linktitle);
426 $essaystatuses[] = html_writer::span($status, $class, $attributes);
f15eb92c 427 }
428 }
0a4abb73 429 // email link for this user
a6855934 430 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','userid'=>$userid,'sesskey'=>sesskey()));
57cd3739 431 $emaillink = html_writer::link($url, get_string('emailgradedessays', 'lesson'));
86342d63 432
a86b7560
MG
433 $table->data[] = array($OUTPUT->user_picture($users[$userid], array('courseid' => $course->id)) . $studentname,
434 implode("<br />", $essaylinks), implode("<br />", $essaystatuses), $emaillink);
0a4abb73 435 }
f15eb92c 436
0a4abb73 437 // email link for all users
a6855934 438 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','sesskey'=>sesskey()));
57cd3739 439 $emailalllink = html_writer::link($url, get_string('emailallgradedessays', 'lesson'));
86342d63 440
a86b7560 441 $table->data[] = array(' ', ' ', ' ', $emailalllink);
0a4abb73 442
16be8974 443 echo html_writer::table($table);
0a4abb73
SH
444 break;
445 case 'grade':
b6374c24
MN
446 // Trigger the essay grade viewed event.
447 $event = \mod_lesson\event\essay_attempt_viewed::create(array(
448 'objectid' => $attempt->id,
449 'relateduserid' => $attempt->userid,
450 'context' => $context,
451 'courseid' => $course->id,
452 ));
453 $event->add_record_snapshot('lesson_attempts', $attempt);
454 $event->trigger();
455
0a4abb73
SH
456 // Grading form
457 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
ebf5ad4f 458 $essayinfo = lesson_page_type_essay::extract_useranswer($attempt->useranswer);
676eca7b
P
459 $answer = file_rewrite_pluginfile_urls($essayinfo->answer, 'pluginfile.php', $context->id,
460 'mod_lesson', 'essay_responses', $attempt->id);
3195bc84 461 $currentpage = $lesson->load_page($attempt->pageid);
b38f0baa
AB
462
463 $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
0a4abb73
SH
464 $data = new stdClass;
465 $data->id = $cm->id;
466 $data->attemptid = $attemptid;
467 $data->score = $essayinfo->score;
59f1c9f5 468 $data->question = format_text($currentpage->contents, $currentpage->contentsformat, $formattextdefoptions);
676eca7b 469 $data->studentanswer = format_text($answer, $essayinfo->answerformat,
59f1c9f5 470 array('context' => $context, 'para' => true));
0a4abb73 471 $data->response = $essayinfo->response;
ebf5ad4f
JMV
472 $data->responseformat = $essayinfo->responseformat;
473 $editoroptions = array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES,
474 'maxbytes' => $CFG->maxbytes, 'context' => $context);
475 $data = file_prepare_standard_editor($data, 'response', $editoroptions, $context,
476 'mod_lesson', 'essay_responses', $attempt->id);
0a4abb73
SH
477 $mform->set_data($data);
478
479 $mform->display();
480 break;
fdc790fc
GF
481 default:
482 groups_print_activity_menu($cm, $url);
483 break;
0a4abb73
SH
484}
485
486echo $OUTPUT->footer();