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