3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * Provides the interface for grading essay questions
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once('../../config.php');
27 require_once($CFG->dirroot.'/mod/lesson/locallib.php');
28 require_once($CFG->dirroot.'/mod/lesson/pagetypes/essay.php');
29 require_once($CFG->dirroot.'/mod/lesson/essay_form.php');
31 $id = required_param('id', PARAM_INT); // Course Module ID
32 $mode = optional_param('mode', 'display', PARAM_ALPHA);
34 $cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST);
35 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
36 $dblesson = $DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST);
37 $lesson = new lesson($dblesson);
39 require_login($course, false, $cm);
40 $context = context_module::instance($cm->id);
41 require_capability('mod/lesson:grade', $context);
43 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$id));
44 if ($mode !== 'display') {
45 $url->param('mode', $mode);
49 $currentgroup = groups_get_activity_group($cm, true);
51 $attempt = new stdClass();
52 $user = new stdClass();
53 $attemptid = optional_param('attemptid', 0, PARAM_INT);
55 $formattextdefoptions = new stdClass();
56 $formattextdefoptions->noclean = true;
57 $formattextdefoptions->para = false;
58 $formattextdefoptions->context = $context;
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));
65 $lesson->update_effective_access($user->id);
66 $scoreoptions = array();
67 if ($lesson->custom) {
70 $scoreoptions[$i] = (string)$i;
74 $scoreoptions[0] = get_string('nocredit', 'lesson');
75 $scoreoptions[1] = get_string('credit', 'lesson');
79 /// Handle any preprocessing before header is printed - based on $mode
82 // Grading form - get the necessary data
85 if (empty($attempt)) {
86 print_error('cannotfindattempt', 'lesson');
89 print_error('cannotfinduser', 'lesson');
92 print_error('cannotfindanswer', 'lesson');
99 if (empty($attempt)) {
100 print_error('cannotfindattempt', 'lesson');
103 print_error('cannotfinduser', 'lesson');
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);
113 if ($mform->is_cancelled()) {
114 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
116 if ($form = $mform->get_data()) {
117 if (!$grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1)) {
118 print_error('cannotfindgrade', 'lesson');
121 $essayinfo->graded = 1;
122 $essayinfo->score = $form->score;
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;
127 $essayinfo->sent = 0;
128 if (!$lesson->custom && $essayinfo->score == 1) {
129 $attempt->correct = 1;
131 $attempt->correct = 0;
134 $attempt->useranswer = serialize($essayinfo);
136 $DB->update_record('lesson_attempts', $attempt);
138 // Get grade information
139 $grade = current($grades);
140 $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
143 $updategrade = new stdClass();
144 $updategrade->id = $grade->id;
145 $updategrade->grade = $gradeinfo->grade;
146 $DB->update_record('lesson_grades', $updategrade);
149 'context' => $context,
150 'objectid' => $grade->id,
151 'courseid' => $course->id,
152 'relateduserid' => $attempt->userid,
154 'lessonid' => $lesson->id,
155 'attemptid' => $attemptid
158 $event = \mod_lesson\event\essay_assessed::create($params);
159 $event->add_record_snapshot('lesson', $dblesson);
162 $lesson->add_message(get_string('changessaved'), 'notifysuccess');
164 // update central gradebook
165 lesson_update_grades($lesson, $grade->userid);
167 redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
169 print_error('invalidformdata');
173 // Sending an email(s) to a single user or all
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');
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;
190 // Need to use inner view to avoid distinct + text
191 if (!$users = $DB->get_records_sql("
195 SELECT DISTINCT userid
196 FROM {lesson_attempts}
197 WHERE lessonid = :lessonid
198 ) ui ON u.id = ui.userid
199 JOIN ($esql) ue ON ue.id = u.id
200 ORDER BY $sort", $params)) {
201 print_error('cannotfinduser', 'lesson');
205 $pages = $lesson->load_all_pages();
206 foreach ($pages as $key=>$page) {
207 if ($page->qtype != LESSON_PAGE_ESSAY) {
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)) {
217 if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
218 print_error('nooneansweredthisquestion', 'lesson');
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');
227 foreach ($attempts as $attempt) {
228 $essayinfo = lesson_page_type_essay::extract_useranswer($attempt->useranswer);
229 if ($essayinfo->graded && !$essayinfo->sent) {
230 // Holds values for the essayemailsubject string for the email message
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;
239 if ($lesson->custom) {
240 $a->earned = $essayinfo->score;
241 $a->outof = $answers[$attempt->pageid]->score;
243 $a->earned = $essayinfo->score;
247 // Set rest of the message values
248 $currentpage = $lesson->load_page($attempt->pageid);
249 $a->question = format_text($currentpage->contents, $currentpage->contentsformat, $formattextdefoptions);
250 $a->response = format_text($essayinfo->answer, $essayinfo->answerformat,
251 array('context' => $context, 'para' => true));
252 $a->comment = $essayinfo->response;
253 $a->comment = file_rewrite_pluginfile_urls($a->comment, 'pluginfile.php', $context->id,
254 'mod_lesson', 'essay_responses', $attempt->id);
255 $a->comment = format_text($a->comment, $essayinfo->responseformat, $formattextdefoptions);
256 $a->lesson = format_string($lesson->name, true);
258 // Fetch message HTML and plain text formats
259 $message = get_string('essayemailmessage2', 'lesson', $a);
260 $plaintext = format_text_email($message, FORMAT_HTML);
263 $subject = get_string('essayemailsubject', 'lesson');
266 $contexturl = new moodle_url('/grade/report/user/index.php', array('id' => $course->id));
268 $eventdata = new \core\message\message();
269 $eventdata->courseid = $course->id;
270 $eventdata->modulename = 'lesson';
271 $eventdata->userfrom = $USER;
272 $eventdata->userto = $users[$attempt->userid];
273 $eventdata->subject = $subject;
274 $eventdata->fullmessage = $plaintext;
275 $eventdata->fullmessageformat = FORMAT_PLAIN;
276 $eventdata->fullmessagehtml = $message;
277 $eventdata->smallmessage = '';
278 $eventdata->contexturl = $contexturl;
280 // Required for messaging framework
281 $eventdata->component = 'mod_lesson';
282 $eventdata->name = 'graded_essay';
284 message_send($eventdata);
285 $essayinfo->sent = 1;
286 $attempt->useranswer = serialize($essayinfo);
287 $DB->update_record('lesson_attempts', $attempt);
290 $lesson->add_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
291 redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
293 case 'display': // Default view - get the necessary data
295 // Get lesson pages that are essay
296 $pages = $lesson->load_all_pages();
297 foreach ($pages as $key=>$page) {
298 if ($page->qtype != LESSON_PAGE_ESSAY) {
302 if (count($pages) > 0) {
303 // Get only the attempts that are in response to essay questions
304 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($pages), SQL_PARAMS_NAMED);
305 // If group selected, only get group members attempts.
306 list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
307 $parameters = array_merge($params, $parameters);
310 FROM {lesson_attempts} a
311 JOIN ($esql) ue ON a.userid = ue.id
313 if ($essayattempts = $DB->get_records_sql($sql, $parameters)) {
314 $ufields = user_picture::fields('u');
315 // Get all the users who have taken this lesson.
316 list($sort, $sortparams) = users_order_by_sql('u');
318 $params['lessonid'] = $lesson->id;
319 $sql = "SELECT DISTINCT $ufields
321 JOIN {lesson_attempts} a ON u.id = a.userid
322 JOIN ($esql) ue ON ue.id = a.userid
323 WHERE a.lessonid = :lessonid
325 if (!$users = $DB->get_records_sql($sql, $params)) {
326 $mode = 'none'; // not displaying anything
327 if (!empty($currentgroup)) {
328 $groupname = groups_get_group_name($currentgroup);
329 $lesson->add_message(get_string('noonehasansweredgroup', 'lesson', $groupname));
331 $lesson->add_message(get_string('noonehasanswered', 'lesson'));
335 $mode = 'none'; // not displaying anything
336 if (!empty($currentgroup)) {
337 $groupname = groups_get_group_name($currentgroup);
338 $lesson->add_message(get_string('noonehasansweredgroup', 'lesson', $groupname));
340 $lesson->add_message(get_string('noonehasanswered', 'lesson'));
344 $mode = 'none'; // not displaying anything
345 $lesson->add_message(get_string('noessayquestionsfound', 'lesson'));
350 $lessonoutput = $PAGE->get_renderer('mod_lesson');
351 echo $lessonoutput->header($lesson, $cm, 'essay', false, null, get_string('manualgrading', 'lesson'));
355 groups_print_activity_menu($cm, $url);
356 // Expects $user, $essayattempts and $pages to be set already
358 // Group all the essays by userid
359 $studentessays = array();
360 foreach ($essayattempts as $essay) {
361 // Not very nice :) but basically
362 // this organizes the essays so we know how many
363 // times a student answered an essay per try and per page
364 $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
368 $table = new html_table();
369 $table->head = array(get_string('name'), get_string('essays', 'lesson'), get_string('status'),
370 get_string('email', 'lesson'));
371 $table->attributes['class'] = 'standardtable generaltable';
372 $table->align = array('left', 'left', 'left');
373 $table->wrap = array('nowrap', 'nowrap', '');
375 // Cycle through all the students
376 foreach (array_keys($studentessays) as $userid) {
377 $studentname = fullname($users[$userid], true);
378 $essaylinks = array();
379 $essaystatuses = array();
381 // Number of attempts on the lesson
382 $attempts = $lesson->count_user_retries($userid);
384 // Go through each essay page
385 foreach ($studentessays[$userid] as $page => $tries) {
388 // Go through each attempt per page
389 foreach($tries as $try) {
390 if ($count == $attempts) {
391 break; // Stop displaying essays (attempt not completed)
395 // Make sure they didn't answer it more than the max number of attmepts
396 if (count($try) > $lesson->maxattempts) {
397 $essay = $try[$lesson->maxattempts-1];
402 // Start processing the attempt
403 $essayinfo = lesson_page_type_essay::extract_useranswer($essay->useranswer);
405 // link for each essay
406 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'grade','attemptid'=>$essay->id,'sesskey'=>sesskey()));
407 $linktitle = userdate($essay->timeseen, get_string('strftimedatetime')).' '.
408 format_string($pages[$essay->pageid]->title, true);
410 // Different colors for all the states of an essay (graded, if sent, not graded)
411 if (!$essayinfo->graded) {
412 $class = "badge badge-warning";
413 $status = get_string('notgraded', 'lesson');
414 } elseif (!$essayinfo->sent) {
415 $class = "badge badge-success";
416 $status = get_string('graded', 'lesson');
418 $class = "badge badge-success";
419 $status = get_string('sent', 'lesson');
421 $attributes = array('tabindex' => 0);
423 $essaylinks[] = html_writer::link($url, $linktitle);
424 $essaystatuses[] = html_writer::span($status, $class, $attributes);
427 // email link for this user
428 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','userid'=>$userid,'sesskey'=>sesskey()));
429 $emaillink = html_writer::link($url, get_string('emailgradedessays', 'lesson'));
431 $table->data[] = array($OUTPUT->user_picture($users[$userid], array('courseid' => $course->id)) . $studentname,
432 implode("<br />", $essaylinks), implode("<br />", $essaystatuses), $emaillink);
435 // email link for all users
436 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','sesskey'=>sesskey()));
437 $emailalllink = html_writer::link($url, get_string('emailallgradedessays', 'lesson'));
439 $table->data[] = array(' ', ' ', ' ', $emailalllink);
441 echo html_writer::table($table);
444 // Trigger the essay grade viewed event.
445 $event = \mod_lesson\event\essay_attempt_viewed::create(array(
446 'objectid' => $attempt->id,
447 'relateduserid' => $attempt->userid,
448 'context' => $context,
449 'courseid' => $course->id,
451 $event->add_record_snapshot('lesson_attempts', $attempt);
455 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
456 $essayinfo = lesson_page_type_essay::extract_useranswer($attempt->useranswer);
457 $currentpage = $lesson->load_page($attempt->pageid);
459 $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
460 $data = new stdClass;
462 $data->attemptid = $attemptid;
463 $data->score = $essayinfo->score;
464 $data->question = format_text($currentpage->contents, $currentpage->contentsformat, $formattextdefoptions);
465 $data->studentanswer = format_text($essayinfo->answer, $essayinfo->answerformat,
466 array('context' => $context, 'para' => true));
467 $data->response = $essayinfo->response;
468 $data->responseformat = $essayinfo->responseformat;
469 $editoroptions = array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES,
470 'maxbytes' => $CFG->maxbytes, 'context' => $context);
471 $data = file_prepare_standard_editor($data, 'response', $editoroptions, $context,
472 'mod_lesson', 'essay_responses', $attempt->id);
473 $mform->set_data($data);
478 groups_print_activity_menu($cm, $url);
482 echo $OUTPUT->footer();