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