Merge branch 'MDL-56959-master-fixup' of https://github.com/FMCorz/moodle
[moodle.git] / mod / lesson / essay.php
blobe7413438445d98409d6374bdff7dbd8cd757335a
1 <?php
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.
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/>.
18 /**
19 * Provides the interface for grading essay questions
21 * @package mod_lesson
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 **/
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');
30 require_once($CFG->libdir.'/eventslib.php');
32 $id = required_param('id', PARAM_INT); // Course Module ID
33 $mode = optional_param('mode', 'display', PARAM_ALPHA);
35 $cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST);
36 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
37 $dblesson = $DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST);
38 $lesson = new lesson($dblesson);
40 require_login($course, false, $cm);
41 $context = context_module::instance($cm->id);
42 require_capability('mod/lesson:grade', $context);
44 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$id));
45 if ($mode !== 'display') {
46 $url->param('mode', $mode);
48 $PAGE->set_url($url);
50 $currentgroup = groups_get_activity_group($cm, true);
52 $attempt = new stdClass();
53 $user = new stdClass();
54 $attemptid = optional_param('attemptid', 0, PARAM_INT);
56 $formattextdefoptions = new stdClass();
57 $formattextdefoptions->noclean = true;
58 $formattextdefoptions->para = false;
59 $formattextdefoptions->context = $context;
61 if ($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));
65 // Apply overrides.
66 $lesson->update_effective_access($user->id);
67 $scoreoptions = array();
68 if ($lesson->custom) {
69 $i = $answer->score;
70 while ($i >= 0) {
71 $scoreoptions[$i] = (string)$i;
72 $i--;
74 } else {
75 $scoreoptions[0] = get_string('nocredit', 'lesson');
76 $scoreoptions[1] = get_string('credit', 'lesson');
80 /// Handle any preprocessing before header is printed - based on $mode
81 switch ($mode) {
82 case 'grade':
83 // Grading form - get the necessary data
84 require_sesskey();
86 if (empty($attempt)) {
87 print_error('cannotfindattempt', 'lesson');
89 if (empty($user)) {
90 print_error('cannotfinduser', 'lesson');
92 if (empty($answer)) {
93 print_error('cannotfindanswer', 'lesson');
95 break;
97 case 'update':
98 require_sesskey();
100 if (empty($attempt)) {
101 print_error('cannotfindattempt', 'lesson');
103 if (empty($user)) {
104 print_error('cannotfinduser', 'lesson');
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);
114 if ($mform->is_cancelled()) {
115 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
117 if ($form = $mform->get_data()) {
118 if (!$grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1)) {
119 print_error('cannotfindgrade', 'lesson');
122 $essayinfo->graded = 1;
123 $essayinfo->score = $form->score;
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;
128 $essayinfo->sent = 0;
129 if (!$lesson->custom && $essayinfo->score == 1) {
130 $attempt->correct = 1;
131 } else {
132 $attempt->correct = 0;
135 $attempt->useranswer = serialize($essayinfo);
137 $DB->update_record('lesson_attempts', $attempt);
139 // Get grade information
140 $grade = current($grades);
141 $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
143 // Set and update
144 $updategrade = new stdClass();
145 $updategrade->id = $grade->id;
146 $updategrade->grade = $gradeinfo->grade;
147 $DB->update_record('lesson_grades', $updategrade);
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
159 $event = \mod_lesson\event\essay_assessed::create($params);
160 $event->add_record_snapshot('lesson', $dblesson);
161 $event->trigger();
163 $lesson->add_message(get_string('changessaved'), 'notifysuccess');
165 // update central gradebook
166 lesson_update_grades($lesson, $grade->userid);
168 redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
169 } else {
170 print_error('invalidformdata');
172 break;
173 case 'email':
174 // Sending an email(s) to a single user or all
175 require_sesskey();
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');
183 } else {
184 $queryadd = '';
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;
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 (
196 SELECT DISTINCT userid
197 FROM {lesson_attempts}
198 WHERE lessonid = :lessonid
199 ) ui ON u.id = ui.userid
200 JOIN ($esql) ue ON ue.id = u.id
201 ORDER BY $sort", $params)) {
202 print_error('cannotfinduser', 'lesson');
206 $pages = $lesson->load_all_pages();
207 foreach ($pages as $key=>$page) {
208 if ($page->qtype != LESSON_PAGE_ESSAY) {
209 unset($pages[$key]);
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;
218 if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
219 print_error('nooneansweredthisquestion', 'lesson');
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');
228 foreach ($attempts as $attempt) {
229 $essayinfo = lesson_page_type_essay::extract_useranswer($attempt->useranswer);
230 if ($essayinfo->graded && !$essayinfo->sent) {
231 // Holds values for the essayemailsubject string for the email message
232 $a = new stdClass;
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;
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;
248 // Set rest of the message values
249 $currentpage = $lesson->load_page($attempt->pageid);
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));
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);
257 $a->lesson = format_string($lesson->name, true);
259 // Fetch message HTML and plain text formats
260 $message = get_string('essayemailmessage2', 'lesson', $a);
261 $plaintext = format_text_email($message, FORMAT_HTML);
263 // Subject
264 $subject = get_string('essayemailsubject', 'lesson');
266 // Context url.
267 $contexturl = new moodle_url('/grade/report/user/index.php', array('id' => $course->id));
269 $eventdata = new \core\message\message();
270 $eventdata->courseid = $course->id;
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;
278 $eventdata->smallmessage = '';
279 $eventdata->contexturl = $contexturl;
281 // Required for messaging framework
282 $eventdata->component = 'mod_lesson';
283 $eventdata->name = 'graded_essay';
285 message_send($eventdata);
286 $essayinfo->sent = 1;
287 $attempt->useranswer = serialize($essayinfo);
288 $DB->update_record('lesson_attempts', $attempt);
291 $lesson->add_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
292 redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
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) {
299 if ($page->qtype != LESSON_PAGE_ESSAY) {
300 unset($pages[$key]);
303 if (count($pages) > 0) {
304 // Get only the attempts that are in response to essay questions
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);
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)) {
315 $ufields = user_picture::fields('u');
316 // Get all the users who have taken this lesson.
317 list($sort, $sortparams) = users_order_by_sql('u');
319 $params['lessonid'] = $lesson->id;
320 $sql = "SELECT DISTINCT $ufields
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
325 ORDER BY $sort";
326 if (!$users = $DB->get_records_sql($sql, $params)) {
327 $mode = 'none'; // not displaying anything
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'));
335 } else {
336 $mode = 'none'; // not displaying anything
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'));
344 } else {
345 $mode = 'none'; // not displaying anything
346 $lesson->add_message(get_string('noessayquestionsfound', 'lesson'));
348 break;
351 $lessonoutput = $PAGE->get_renderer('mod_lesson');
352 echo $lessonoutput->header($lesson, $cm, 'essay', false, null, get_string('manualgrading', 'lesson'));
354 switch ($mode) {
355 case 'display':
356 groups_print_activity_menu($cm, $url);
357 // Expects $user, $essayattempts and $pages to be set already
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;
368 // Setup table
369 $table = new html_table();
370 $table->head = array(get_string('name'), get_string('essays', 'lesson'), 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();
380 // Number of attempts on the lesson
381 $attempts = $DB->count_records('lesson_grades', array('userid'=>$userid, 'lessonid'=>$lesson->id));
383 // Go through each essay page
384 foreach ($studentessays[$userid] as $page => $tries) {
385 $count = 0;
387 // Go through each attempt per page
388 foreach($tries as $try) {
389 if ($count == $attempts) {
390 break; // Stop displaying essays (attempt not completed)
392 $count++;
394 // Make sure they didn't answer it more than the max number of attmepts
395 if (count($try) > $lesson->maxattempts) {
396 $essay = $try[$lesson->maxattempts-1];
397 } else {
398 $essay = end($try);
401 // Start processing the attempt
402 $essayinfo = lesson_page_type_essay::extract_useranswer($essay->useranswer);
404 // link for each essay
405 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'grade','attemptid'=>$essay->id,'sesskey'=>sesskey()));
406 $attributes = array();
407 // Different colors for all the states of an essay (graded, if sent, not graded)
408 if (!$essayinfo->graded) {
409 $attributes['class'] = "essayungraded";
410 } elseif (!$essayinfo->sent) {
411 $attributes['class'] = "essaygraded";
412 } else {
413 $attributes['class'] = "essaysent";
415 $essaylinks[] = html_writer::link($url, userdate($essay->timeseen, get_string('strftimedatetime')).' '.format_string($pages[$essay->pageid]->title,true), $attributes);
418 // email link for this user
419 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','userid'=>$userid,'sesskey'=>sesskey()));
420 $emaillink = html_writer::link($url, get_string('emailgradedessays', 'lesson'));
422 $table->data[] = array($OUTPUT->user_picture($users[$userid], array('courseid'=>$course->id)).$studentname, implode("<br />", $essaylinks), $emaillink);
425 // email link for all users
426 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','sesskey'=>sesskey()));
427 $emailalllink = html_writer::link($url, get_string('emailallgradedessays', 'lesson'));
429 $table->data[] = array(' ', ' ', $emailalllink);
431 echo html_writer::table($table);
432 break;
433 case 'grade':
434 // Trigger the essay grade viewed event.
435 $event = \mod_lesson\event\essay_attempt_viewed::create(array(
436 'objectid' => $attempt->id,
437 'relateduserid' => $attempt->userid,
438 'context' => $context,
439 'courseid' => $course->id,
441 $event->add_record_snapshot('lesson_attempts', $attempt);
442 $event->trigger();
444 // Grading form
445 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
446 $essayinfo = lesson_page_type_essay::extract_useranswer($attempt->useranswer);
447 $currentpage = $lesson->load_page($attempt->pageid);
449 $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
450 $data = new stdClass;
451 $data->id = $cm->id;
452 $data->attemptid = $attemptid;
453 $data->score = $essayinfo->score;
454 $data->question = format_text($currentpage->contents, $currentpage->contentsformat, $formattextdefoptions);
455 $data->studentanswer = format_text($essayinfo->answer, $essayinfo->answerformat,
456 array('context' => $context, 'para' => true));
457 $data->response = $essayinfo->response;
458 $data->responseformat = $essayinfo->responseformat;
459 $editoroptions = array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES,
460 'maxbytes' => $CFG->maxbytes, 'context' => $context);
461 $data = file_prepare_standard_editor($data, 'response', $editoroptions, $context,
462 'mod_lesson', 'essay_responses', $attempt->id);
463 $mform->set_data($data);
465 $mform->display();
466 break;
467 default:
468 groups_print_activity_menu($cm, $url);
469 break;
472 echo $OUTPUT->footer();