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