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