Merge branch 'MDL-35530_m23' of git://github.com/rwijaya/moodle into MOODLE_23_STABLE
[moodle.git] / mod / lesson / essay.php
blob74e3a1b3d8c6038d93707739c8f6624d644a6057
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
22 * @subpackage lesson
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 **/
27 require_once('../../config.php');
28 require_once($CFG->dirroot.'/mod/lesson/locallib.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 $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST));
39 require_login($course, false, $cm);
40 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
41 require_capability('mod/lesson:edit', $context);
43 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$id));
44 if ($mode !== 'display') {
45 $url->param('mode', $mode);
47 $PAGE->set_url($url);
49 $attempt = new stdClass();
50 $user = new stdClass();
51 $attemptid = optional_param('attemptid', 0, PARAM_INT);
53 if ($attemptid > 0) {
54 $attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid));
55 $answer = $DB->get_record('lesson_answers', array('lessonid' => $lesson->id, 'pageid' => $attempt->pageid));
56 $user = $DB->get_record('user', array('id' => $attempt->userid));
57 $scoreoptions = array();
58 if ($lesson->custom) {
59 $i = $answer->score;
60 while ($i >= 0) {
61 $scoreoptions[$i] = (string)$i;
62 $i--;
64 } else {
65 $scoreoptions[0] = get_string('nocredit', 'lesson');
66 $scoreoptions[1] = get_string('credit', 'lesson');
70 /// Handle any preprocessing before header is printed - based on $mode
71 switch ($mode) {
72 case 'grade':
73 // Grading form - get the necessary data
74 require_sesskey();
76 if (empty($attempt)) {
77 print_error('cannotfindattempt', 'lesson');
79 if (empty($user)) {
80 print_error('cannotfinduser', 'lesson');
82 if (empty($answer)) {
83 print_error('cannotfindanswer', 'lesson');
85 break;
87 case 'update':
88 require_sesskey();
90 if (empty($attempt)) {
91 print_error('cannotfindattempt', 'lesson');
93 if (empty($user)) {
94 print_error('cannotfinduser', 'lesson');
97 $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
98 if ($mform->is_cancelled()) {
99 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
101 if ($form = $mform->get_data()) {
102 if (!$grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1)) {
103 print_error('cannotfindgrade', 'lesson');
106 $essayinfo = new stdClass;
107 $essayinfo = unserialize($attempt->useranswer);
109 $essayinfo->graded = 1;
110 $essayinfo->score = $form->score;
111 $essayinfo->response = clean_param($form->response, PARAM_RAW);
112 $essayinfo->sent = 0;
113 if (!$lesson->custom && $essayinfo->score == 1) {
114 $attempt->correct = 1;
115 } else {
116 $attempt->correct = 0;
119 $attempt->useranswer = serialize($essayinfo);
121 $DB->update_record('lesson_attempts', $attempt);
123 // Get grade information
124 $grade = current($grades);
125 $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
127 // Set and update
128 $updategrade = new stdClass();
129 $updategrade->id = $grade->id;
130 $updategrade->grade = $gradeinfo->grade;
131 $DB->update_record('lesson_grades', $updategrade);
132 // Log it
133 add_to_log($course->id, 'lesson', 'update grade', "essay.php?id=$cm->id", $lesson->name, $cm->id);
135 $lesson->add_message(get_string('changessaved'), 'notifysuccess');
137 // update central gradebook
138 lesson_update_grades($lesson, $grade->userid);
140 redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
141 } else {
142 print_error('invalidformdata');
144 break;
145 case 'email':
146 // Sending an email(s) to a single user or all
147 require_sesskey();
149 // Get our users (could be singular)
150 if ($userid = optional_param('userid', 0, PARAM_INT)) {
151 $queryadd = " AND userid = ?";
152 if (! $users = $DB->get_records('user', array('id' => $userid))) {
153 print_error('cannotfinduser', 'lesson');
155 } else {
156 $queryadd = '';
157 $params = array ("lessonid" => $lesson->id);
158 // Need to use inner view to avoid distinct + text
159 if (!$users = $DB->get_records_sql("
160 SELECT u.*
161 FROM {user} u
162 JOIN (
163 SELECT DISTINCT u.id
164 FROM {user} u,
165 {lesson_attempts} a
166 WHERE a.lessonid = :lessonid and
167 u.id = a.userid) ui ON (u.id = ui.id)
168 ORDER BY u.lastname", $params)) {
169 print_error('cannotfinduser', 'lesson');
173 $pages = $lesson->load_all_pages();
174 foreach ($pages as $key=>$page) {
175 if ($page->qtype !== LESSON_PAGE_ESSAY) {
176 unset($pages[$key]);
180 // Get only the attempts that are in response to essay questions
181 list($usql, $params) = $DB->get_in_or_equal(array_keys($pages));
182 if (!empty($queryadd)) {
183 $params[] = $userid;
185 if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
186 print_error('nooneansweredthisquestion', 'lesson');
188 // Get the answers
189 list($answerUsql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
190 array_unshift($parameters, $lesson->id);
191 if (!$answers = $DB->get_records_select('lesson_answers', "lessonid = ? AND pageid $answerUsql", $parameters, '', 'pageid, score')) {
192 print_error('cannotfindanswer', 'lesson');
194 $options = new stdClass;
195 $options->noclean = true;
197 foreach ($attempts as $attempt) {
198 $essayinfo = unserialize($attempt->useranswer);
199 if ($essayinfo->graded && !$essayinfo->sent) {
200 // Holds values for the essayemailsubject string for the email message
201 $a = new stdClass;
203 // Set the grade
204 $grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1);
205 $grade = current($grades);
206 $a->newgrade = $grade->grade;
208 // Set the points
209 if ($lesson->custom) {
210 $a->earned = $essayinfo->score;
211 $a->outof = $answers[$attempt->pageid]->score;
212 } else {
213 $a->earned = $essayinfo->score;
214 $a->outof = 1;
217 // Set rest of the message values
218 $currentpage = $lesson->load_page($attempt->pageid);
219 $a->question = format_text($currentpage->contents, $currentpage->contentsformat, $options);
220 $a->response = s($essayinfo->answer);
221 $a->comment = s($essayinfo->response);
223 // Fetch message HTML and plain text formats
224 $message = get_string('essayemailmessage2', 'lesson', $a);
225 $plaintext = format_text_email($message, FORMAT_HTML);
227 // Subject
228 $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));
230 $eventdata = new stdClass();
231 $eventdata->modulename = 'lesson';
232 $eventdata->userfrom = $USER;
233 $eventdata->userto = $users[$attempt->userid];
234 $eventdata->subject = $subject;
235 $eventdata->fullmessage = $plaintext;
236 $eventdata->fullmessageformat = FORMAT_PLAIN;
237 $eventdata->fullmessagehtml = $message;
238 $eventdata->smallmessage = '';
240 // Required for messaging framework
241 $eventdata->component = 'mod_lesson';
242 $eventdata->name = 'graded_essay';
244 message_send($eventdata);
245 $essayinfo->sent = 1;
246 $attempt->useranswer = serialize($essayinfo);
247 $DB->update_record('lesson_attempts', $attempt);
248 // Log it
249 add_to_log($course->id, 'lesson', 'update email essay grade', "essay.php?id=$cm->id", format_string($pages[$attempt->pageid]->title,true).': '.fullname($users[$attempt->userid]), $cm->id);
252 $lesson->add_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
253 redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
254 break;
255 case 'display': // Default view - get the necessary data
256 default:
257 // Get lesson pages that are essay
258 $pages = $lesson->load_all_pages();
259 foreach ($pages as $key=>$page) {
260 if ($page->qtype !== LESSON_PAGE_ESSAY) {
261 unset($pages[$key]);
264 if (count($pages) > 0) {
265 $params = array ("lessonid" => $lesson->id, "qtype" => LESSON_PAGE_ESSAY);
266 // Get only the attempts that are in response to essay questions
267 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
268 if ($essayattempts = $DB->get_records_select('lesson_attempts', 'pageid '.$usql, $parameters)) {
269 // Get all the users who have taken this lesson, order by their last name
270 $ufields = user_picture::fields('u');
271 if (!empty($cm->groupingid)) {
272 $params["groupingid"] = $cm->groupingid;
273 $sql = "SELECT DISTINCT $ufields
274 FROM {lesson_attempts} a
275 INNER JOIN {user} u ON u.id = a.userid
276 INNER JOIN {groups_members} gm ON gm.userid = u.id
277 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid
278 WHERE a.lessonid = :lessonid
279 ORDER BY u.lastname";
280 } else {
281 $sql = "SELECT DISTINCT $ufields
282 FROM {user} u,
283 {lesson_attempts} a
284 WHERE a.lessonid = :lessonid and
285 u.id = a.userid
286 ORDER BY u.lastname";
288 if (!$users = $DB->get_records_sql($sql, $params)) {
289 $mode = 'none'; // not displaying anything
290 $lesson->add_message(get_string('noonehasanswered', 'lesson'));
292 } else {
293 $mode = 'none'; // not displaying anything
294 $lesson->add_message(get_string('noonehasanswered', 'lesson'));
296 } else {
297 $mode = 'none'; // not displaying anything
298 $lesson->add_message(get_string('noessayquestionsfound', 'lesson'));
300 break;
302 // Log it
303 add_to_log($course->id, 'lesson', 'view grade', "essay.php?id=$cm->id", get_string('manualgrading', 'lesson'), $cm->id);
305 $lessonoutput = $PAGE->get_renderer('mod_lesson');
306 echo $lessonoutput->header($lesson, $cm, 'essay');
308 switch ($mode) {
309 case 'display':
310 // Expects $user, $essayattempts and $pages to be set already
312 // Group all the essays by userid
313 $studentessays = array();
314 foreach ($essayattempts as $essay) {
315 // Not very nice :) but basically
316 // this organizes the essays so we know how many
317 // times a student answered an essay per try and per page
318 $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
321 // Setup table
322 $table = new html_table();
323 $table->head = array(get_string('name'), get_string('essays', 'lesson'), get_string('email', 'lesson'));
324 $table->attributes['class'] = 'standardtable generaltable';
325 $table->align = array('left', 'left', 'left');
326 $table->wrap = array('nowrap', 'nowrap', '');
328 // Cycle through all the students
329 foreach (array_keys($studentessays) as $userid) {
330 $studentname = fullname($users[$userid], true);
331 $essaylinks = array();
333 // Number of attempts on the lesson
334 $attempts = $DB->count_records('lesson_grades', array('userid'=>$userid, 'lessonid'=>$lesson->id));
336 // Go through each essay page
337 foreach ($studentessays[$userid] as $page => $tries) {
338 $count = 0;
340 // Go through each attempt per page
341 foreach($tries as $try) {
342 if ($count == $attempts) {
343 break; // Stop displaying essays (attempt not completed)
345 $count++;
347 // Make sure they didn't answer it more than the max number of attmepts
348 if (count($try) > $lesson->maxattempts) {
349 $essay = $try[$lesson->maxattempts-1];
350 } else {
351 $essay = end($try);
354 // Start processing the attempt
355 $essayinfo = unserialize($essay->useranswer);
357 // link for each essay
358 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'grade','attemptid'=>$essay->id,'sesskey'=>sesskey()));
359 $attributes = array();
360 // Different colors for all the states of an essay (graded, if sent, not graded)
361 if (!$essayinfo->graded) {
362 $attributes['class'] = "graded";
363 } elseif (!$essayinfo->sent) {
364 $attributes['class'] = "sent";
365 } else {
366 $attributes['class'] = "ungraded";
368 $essaylinks[] = html_writer::link($url, userdate($essay->timeseen, get_string('strftimedatetime')).' '.format_string($pages[$essay->pageid]->title,true), $attributes);
371 // email link for this user
372 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','userid'=>$userid,'sesskey'=>sesskey()));
373 $emaillink = html_writer::link($url, get_string('emailgradedessays', 'lesson'));
375 $table->data[] = array($OUTPUT->user_picture($users[$userid], array('courseid'=>$course->id)).$studentname, implode("<br />", $essaylinks), $emaillink);
378 // email link for all users
379 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','sesskey'=>sesskey()));
380 $emailalllink = html_writer::link($url, get_string('emailallgradedessays', 'lesson'));
382 $table->data[] = array(' ', ' ', $emailalllink);
384 echo html_writer::table($table);
385 break;
386 case 'grade':
387 // Grading form
388 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
389 $essayinfo = unserialize($attempt->useranswer);
390 $currentpage = $lesson->load_page($attempt->pageid);
392 $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
393 $data = new stdClass;
394 $data->id = $cm->id;
395 $data->attemptid = $attemptid;
396 $data->score = $essayinfo->score;
397 $data->question = format_string($currentpage->contents, $currentpage->contentsformat);
398 $data->studentanswer = format_string($essayinfo->answer, $essayinfo->answerformat);
399 $data->response = $essayinfo->response;
400 $mform->set_data($data);
402 $mform->display();
403 break;
406 echo $OUTPUT->footer();