MDL-14741: better default layout for buttons and added new moodlenolink plugin
[moodle.git] / mod / lesson / essay.php
CommitLineData
f15eb92c 1<?php // $Id$
2/**
3 * Provides the interface for grading essay questions
4 *
5 * @version $Id$
6 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7 * @package lesson
8 **/
9
10 require_once('../../config.php');
11 require_once('locallib.php');
12 require_once('lib.php');
13
fb992d71 14 $id = required_param('id', PARAM_INT); // Course Module ID
15 $mode = optional_param('mode', 'display', PARAM_ALPHA);
f15eb92c 16
17 list($cm, $course, $lesson) = lesson_get_basics($id);
18
19 require_login($course->id, false, $cm);
20
21 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
22
d927bb55 23 require_capability('mod/lesson:edit', $context);
f15eb92c 24
25/// Handle any preprocessing before header is printed - based on $mode
26 switch ($mode) {
27 case 'display': // Default view - get the necessary data
28 // Get lesson pages that are essay
646fc290 29 $params = array ("lessonid" => $lesson->id, "qtype" => LESSON_ESSAY);
30 if ($pages = $DB->get_records_select('lesson_pages', "lessonid = :lessonid AND qtype = :qtype", $params)) {
f15eb92c 31 // Get only the attempts that are in response to essay questions
646fc290 32 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
33 if ($essayattempts = $DB->get_records_select('lesson_attempts', 'pageid $usql', $parameters)) {
f15eb92c 34 // Get all the users who have taken this lesson, order by their last name
0ffa2c95 35 if (!empty($CFG->enablegroupings) && !empty($cm->groupingid)) {
e57bc529 36 $params["groupinid"] = $cm->groupingid;
0ffa2c95 37 $sql = "SELECT DISTINCT u.*
646fc290 38 FROM {lesson_attempts} a
39 INNER JOIN {user} u ON u.id = a.userid
40 INNER JOIN {groups_members} gm ON gm.userid = u.id
41 INNER JOIN {groupings_groups} gg ON gm.groupid = :groupinid
42 WHERE a.lessonid = :lessonid
0ffa2c95 43 ORDER BY u.lastname";
44 } else {
45 $sql = "SELECT u.*
646fc290 46 FROM {user} u,
47 {lesson_attempts} a
48 WHERE a.lessonid = :lessonid and
0ffa2c95 49 u.id = a.userid
50 ORDER BY u.lastname";
51 }
e57bc529 52 if (!$users = $DB->get_records_sql($sql, $params)) {
0ffa2c95 53 $mode = 'none'; // not displaying anything
54 lesson_set_message(get_string('noonehasanswered', 'lesson'));
f15eb92c 55 }
56 } else {
57 $mode = 'none'; // not displaying anything
58 lesson_set_message(get_string('noonehasanswered', 'lesson'));
59 }
60 } else {
61 $mode = 'none'; // not displaying anything
62 lesson_set_message(get_string('noessayquestionsfound', 'lesson'));
63 }
64 break;
65 case 'grade': // Grading form - get the necessary data
66 confirm_sesskey();
67
68 $attemptid = required_param('attemptid', PARAM_INT);
69
646fc290 70 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid))) {
86f93345 71 print_error('cannotfindattempt', 'lesson');
f15eb92c 72 }
646fc290 73 if (!$page = $DB->get_record('lesson_pages', array('id' => $attempt->pageid))) {
86f93345 74 print_error('cannotfindpages', 'lesson');
f15eb92c 75 }
646fc290 76 if (!$user = $DB->get_record('user', array('id' => $attempt->userid))) {
86f93345 77 print_error('cannotfinduser', 'lesson');
f15eb92c 78 }
646fc290 79 if (!$answer = $DB->get_record('lesson_answers', array('lessonid' => $lesson->id, 'pageid' => $page->id))) {
86f93345 80 print_error('cannotfindanswer', 'lesson');
f15eb92c 81 }
82 break;
83 case 'update':
294ce987 84 if (confirm_sesskey() and $form = data_submitted()) {
f15eb92c 85 if (optional_param('cancel', 0)) {
86 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
87 }
88
89 $attemptid = required_param('attemptid', PARAM_INT);
90
646fc290 91 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid))) {
86f93345 92 print_error('cannotfindattempt', 'lesson');
f15eb92c 93 }
646fc290 94 $params = array ("lessonid" => $lesson->id, "userid" => $attempt->userid);
95 if (!$grades = $DB->get_records_select('lesson_grades', "lessonid = :lessonid and userid = :userid", $params, 'completed', '*', $attempt->retry, 1)) {
86f93345 96 print_error('cannotfindgrade', 'lesson');
f15eb92c 97 }
98
99 $essayinfo = new stdClass;
100 $essayinfo = unserialize($attempt->useranswer);
101
102 $essayinfo->graded = 1;
103 $essayinfo->score = clean_param($form->score, PARAM_INT);
294ce987 104 $essayinfo->response = clean_param($form->response, PARAM_RAW);
f15eb92c 105 $essayinfo->sent = 0;
106 if (!$lesson->custom && $essayinfo->score == 1) {
107 $attempt->correct = 1;
108 } else {
109 $attempt->correct = 0;
110 }
111
294ce987 112 $attempt->useranswer = serialize($essayinfo);
f15eb92c 113
646fc290 114 if (!$DB->update_record('lesson_attempts', $attempt)) {
86f93345 115 print_error('cannotupdateessayscore', 'lesson');
f15eb92c 116 }
117
118 // Get grade information
119 $grade = current($grades);
120 $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
121
122 // Set and update
123 $updategrade->id = $grade->id;
124 $updategrade->grade = $gradeinfo->grade;
646fc290 125 if($DB->update_record('lesson_grades', $updategrade)) {
f15eb92c 126 // Log it
127 add_to_log($course->id, 'lesson', 'update grade', "essay.php?id=$cm->id", $lesson->name, $cm->id);
128
260a56b1 129 lesson_set_message(get_string('changessaved'), 'notifysuccess');
f15eb92c 130 } else {
260a56b1 131 lesson_set_message(get_string('updatefailed', 'lesson'));
f15eb92c 132 }
92bcca38 133
134 // update central gradebook
135 lesson_update_grades($lesson, $grade->userid);
136
260a56b1 137 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
f15eb92c 138 } else {
86f93345 139 print_error('invalidformdata');
f15eb92c 140 }
141 break;
142 case 'email': // Sending an email(s) to a single user or all
143 confirm_sesskey();
144
145 // Get our users (could be singular)
146 if ($userid = optional_param('userid', 0, PARAM_INT)) {
646fc290 147 $queryadd = " AND userid = :userid";
148 if (! $users = $DB->get_records('user', array('id' => $userid))) {
86f93345 149 print_error('cannotfinduser', 'lesson');
f15eb92c 150 }
151 } else {
152 $queryadd = '';
646fc290 153 $params = array ("lessonid" => $lesson->id);
154 if (!$users = $DB->get_records_sql("SELECT u.*
155 FROM {user} u,
156 {lesson_attempts} a
157 WHERE a.lessonid = :lessonid and
f15eb92c 158 u.id = a.userid
646fc290 159 ORDER BY u.lastname", $params)) {
86f93345 160 print_error('cannotfinduser', 'lesson');
f15eb92c 161 }
162 }
163
164 // Get lesson pages that are essay
646fc290 165 $params = array ("lessonid" => $lesson->id, "qtype" => LESSON_ESSAY);
166 if (!$pages = $DB->get_records_select('lesson_pages', "lessonid = :lessonid AND qtype = :qtype", $params)) {
86f93345 167 print_error('cannotfindpages', 'lesson');
f15eb92c 168 }
169
170 // Get only the attempts that are in response to essay questions
646fc290 171 list($usql, $params) = $DB->get_in_or_equal(array_keys($pages));
172 if (isset($queryadd) && $queryadd!='') {
173 $params["userid"] = $userid;
174 }
175 if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
f15eb92c 176 error ('No one has answered essay questions yet...');
177 }
178 // Get the answers
646fc290 179 list($answerUsql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
180 $parameters["lessonid"] = $lesson->id;
181 if (!$answers = $DB->get_records_select('lesson_answers', "lessonid = :lessonid AND pageid $answerUsql", $parameters, '', 'pageid, score')) {
f15eb92c 182 error ('Could not find answer records.');
183 }
184 $options = new stdClass;
185 $options->noclean = true;
186
187 foreach ($attempts as $attempt) {
188 $essayinfo = unserialize($attempt->useranswer);
260a56b1 189 if ($essayinfo->graded and !$essayinfo->sent) {
190 // Holds values for the essayemailsubject string for the email message
191 $a = new stdClass;
192
193 // Set the grade
646fc290 194 $params = array ("lessonid" => $lesson->id, "userid" => $attempt->userid);
195 $grades = $DB->get_records_select('lesson_grades', "lessonid = :lessonid and userid = :userid", $params, 'completed', '*', $attempt->retry, 1);
260a56b1 196 $grade = current($grades);
197 $a->newgrade = $grade->grade;
198
199 // Set the points
f15eb92c 200 if ($lesson->custom) {
260a56b1 201 $a->earned = $essayinfo->score;
202 $a->outof = $answers[$attempt->pageid]->score;
f15eb92c 203 } else {
260a56b1 204 $a->earned = $essayinfo->score;
205 $a->outof = 1;
f15eb92c 206 }
260a56b1 207
208 // Set rest of the message values
209 $a->question = format_text($pages[$attempt->pageid]->contents, FORMAT_MOODLE, $options);
294ce987 210 $a->response = s($essayinfo->answer);
260a56b1 211 $a->teacher = $course->teacher;
107470cb 212 $a->comment = s($essayinfo->response);
260a56b1 213
214
215 // Fetch message HTML and plain text formats
216 $message = get_string('essayemailmessage', 'lesson', $a);
f15eb92c 217 $plaintxt = format_text_email($message, FORMAT_HTML);
218
260a56b1 219 // Subject
220 $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));
221
f15eb92c 222 if(email_to_user($users[$attempt->userid], $USER, $subject, $plaintxt, $message)) {
223 $essayinfo->sent = 1;
294ce987 224 $attempt->useranswer = serialize($essayinfo);
646fc290 225 $DB->update_record('lesson_attempts', $attempt);
f15eb92c 226 // Log it
227 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);
228 } else {
86f93345 229 print_error('emailfail');
f15eb92c 230 }
231 }
232 }
260a56b1 233 lesson_set_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
234 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
f15eb92c 235 break;
236 }
237
238 // Log it
239 add_to_log($course->id, 'lesson', 'view grade', "essay.php?id=$cm->id", get_string('manualgrading', 'lesson'), $cm->id);
240
241 lesson_print_header($cm, $course, $lesson, 'essay');
242
243 switch ($mode) {
244 case 'display':
245 // Expects $user, $essayattempts and $pages to be set already
246
247 // Group all the essays by userid
248 $studentessays = array();
249 foreach ($essayattempts as $essay) {
250 // Not very nice :) but basically
251 // this organizes the essays so we know how many
252 // times a student answered an essay per try and per page
253 $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
254 }
255
256 // Setup table
257 $table = new stdClass;
258 $table->head = array($course->students, get_string('essays', 'lesson'), get_string('email', 'lesson'));
259 $table->align = array('left', 'left', 'left');
260 $table->wrap = array('nowrap', 'nowrap', 'nowrap');
261
262 // Get the student ids of the users who have answered the essay question
263 $userids = array_keys($studentessays);
264
265 // Cycle through all the students
266 foreach ($userids as $userid) {
267 $studentname = fullname($users[$userid], true);
268 $essaylinks = array();
269
270 // Number of attempts on the lesson
318e3745 271 $attempts = $DB->count_records('lesson_grades', array('userid'=>$userid, 'lessonid'=>$lesson->id));
f15eb92c 272
273 // Go through each essay page
274 foreach ($studentessays[$userid] as $page => $tries) {
275 $count = 0;
276
277 // Go through each attempt per page
278 foreach($tries as $try) {
279 if ($count == $attempts) {
280 break; // Stop displaying essays (attempt not completed)
281 }
282 $count++;
283
284 // Make sure they didn't answer it more than the max number of attmepts
285 if (count($try) > $lesson->maxattempts) {
286 $essay = $try[$lesson->maxattempts-1];
287 } else {
288 $essay = end($try);
289 }
290
291 // Start processing the attempt
292 $essayinfo = unserialize($essay->useranswer);
293
294 // Different colors for all the states of an essay (graded, if sent, not graded)
295 if (!$essayinfo->graded) {
296 $class = ' class="graded"';
297 } elseif (!$essayinfo->sent) {
298 $class = ' class="sent"';
299 } else {
300 $class = ' class="ungraded"';
301 }
302 // link for each essay
303 $essaylinks[] = "<a$class href=\"$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id&amp;mode=grade&amp;attemptid=$essay->id&amp;sesskey=".sesskey().'">'.userdate($essay->timeseen, get_string('strftimedatetime')).' '.format_string($pages[$essay->pageid]->title,true).'</a>';
304 }
305 }
306 // email link for this user
307 $emaillink = "<a href=\"$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id&amp;mode=email&amp;userid=$userid&amp;sesskey=".sesskey().'">'.get_string('emailgradedessays', 'lesson').'</a>';
308
309 $table->data[] = array(print_user_picture($userid, $course->id, $users[$userid]->picture, 0, true).$studentname, implode("<br />\n", $essaylinks), $emaillink);
310 }
311 // email link for all users
312 $emailalllink = "<a href=\"$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id&amp;mode=email&amp;sesskey=".sesskey().'">'.get_string('emailallgradedessays', 'lesson').'</a>';
313
314 $table->data[] = array(' ', ' ', $emailalllink);
315
316 print_table($table);
317 break;
318 case 'grade':
319 // Grading form
320 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
321
322 echo '<div class="grade">
b7dc2256 323 <form id="essaygrade" method="post" action="'.$CFG->wwwroot.'/mod/lesson/essay.php">
f15eb92c 324 <input type="hidden" name="id" value="'.$cm->id.'" />
325 <input type="hidden" name="mode" value="update" />
326 <input type="hidden" name="attemptid" value="'.$attemptid.'" />
327 <input type="hidden" name="sesskey" value="'.sesskey().'" />';
328
329 // All tables will have these settings
330 $table = new stdClass;
331 $table->align = array('left');
332 $table->wrap = array();
333 $table->width = '50%';
334 $table->size = array('100%');
335 $table->class = 'generaltable gradetable';
336
337 // Print the question
338 $table->head = array(get_string('question', 'lesson'));
339 $options = new stdClass;
340 $options->noclean = true;
341 $table->data[] = array(format_text($page->contents, FORMAT_MOODLE, $options));
342
343 print_table($table);
344
345 unset($table->data);
346
347 // Now the user's answer
348 $essayinfo = unserialize($attempt->useranswer);
349
350 $table->head = array(get_string('studentresponse', 'lesson', fullname($user, true)));
294ce987 351 $table->data[] = array(s($essayinfo->answer));
f15eb92c 352
353 print_table($table);
354
355 unset($table->data);
356
357 // Now a response box and grade drop-down for grader
358 $table->head = array(get_string('comments', 'lesson'));
107470cb 359 $table->data[] = array(print_textarea(false, 15, 60, 0, 0, 'response', $essayinfo->response, $course->id, true));
f15eb92c 360 $options = array();
361 if ($lesson->custom) {
362 for ($i=$answer->score; $i>=0; $i--) {
363 $options[$i] = $i;
364 }
365 } else {
366 $options[0] = get_string('nocredit', 'lesson');
367 $options[1] = get_string('credit', 'lesson');
368 }
369 $table->data[] = array(get_string('essayscore', 'lesson').': '.choose_from_menu($options, 'score', $essayinfo->score, '', '', '', true));
370
371 print_table($table);
372 echo '<div class="buttons">
373 <input type="submit" name="cancel" value="'.get_string('cancel').'" />
374 <input type="submit" value="'.get_string('savechanges').'" />
375 </div>
376 </form>
377 </div>';
378 break;
379 }
380
381 print_footer($course);
86f93345 382?>