MDL-10234
[moodle-linuxchix.git] / mod / lesson / essay.php
blob2d0dbbc56b543bc634f9529ae4e84796e8b3869b
1 <?php // $Id$
2 /**
3 * Provides the interface for grading essay questions
5 * @version $Id$
6 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7 * @package lesson
8 **/
10 require_once('../../config.php');
11 require_once('locallib.php');
12 require_once('lib.php');
14 $id = required_param('id', PARAM_INT); // Course Module ID
15 $mode = optional_param('mode', 'display', PARAM_ALPHA);
17 list($cm, $course, $lesson) = lesson_get_basics($id);
19 require_login($course->id, false, $cm);
21 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
23 require_capability('mod/lesson:edit', $context);
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
33 if (!$users = get_records_sql("SELECT u.*
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');
41 } else {
42 $mode = 'none'; // not displaying anything
43 lesson_set_message(get_string('noonehasanswered', 'lesson'));
45 } else {
46 $mode = 'none'; // not displaying anything
47 lesson_set_message(get_string('noessayquestionsfound', 'lesson'));
49 break;
50 case 'grade': // Grading form - get the necessary data
51 confirm_sesskey();
53 $attemptid = required_param('attemptid', PARAM_INT);
55 if (!$attempt = get_record('lesson_attempts', 'id', $attemptid)) {
56 error('Error: could not find attempt');
58 if (!$page = get_record('lesson_pages', 'id', $attempt->pageid)) {
59 error('Error: could not find lesson page');
61 if (!$user = get_record('user', 'id', $attempt->userid)) {
62 error('Error: could not find users');
64 if (!$answer = get_record('lesson_answers', 'lessonid', $lesson->id, 'pageid', $page->id)) {
65 error('Error: could not find answer');
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");
74 $attemptid = required_param('attemptid', PARAM_INT);
76 if (!$attempt = get_record('lesson_attempts', 'id', $attemptid)) {
77 error('Error: could not find essay');
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');
83 $essayinfo = new stdClass;
84 $essayinfo = unserialize($attempt->useranswer);
86 $essayinfo->graded = 1;
87 $essayinfo->score = clean_param($form->score, PARAM_INT);
88 $essayinfo->response = stripslashes_safe(clean_param($form->response, PARAM_RAW));
89 $essayinfo->sent = 0;
90 if (!$lesson->custom && $essayinfo->score == 1) {
91 $attempt->correct = 1;
92 } else {
93 $attempt->correct = 0;
96 $attempt->useranswer = addslashes(serialize($essayinfo));
98 if (!update_record('lesson_attempts', $attempt)) {
99 error('Could not update essay score');
102 // Get grade information
103 $grade = current($grades);
104 $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
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);
113 lesson_set_message(get_string('changessaved'), 'notifysuccess');
114 } else {
115 lesson_set_message(get_string('updatefailed', 'lesson'));
118 // update central gradebook
119 lesson_update_grades($lesson, $grade->userid);
121 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
122 } else {
123 error('Something is wrong with the form data');
125 break;
126 case 'email': // Sending an email(s) to a single user or all
127 confirm_sesskey();
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');
135 } else {
136 $queryadd = '';
137 if (!$users = get_records_sql("SELECT u.*
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');
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');
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...');
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.');
161 $options = new stdClass;
162 $options->noclean = true;
164 foreach ($attempts as $attempt) {
165 $essayinfo = unserialize($attempt->useranswer);
166 if ($essayinfo->graded and !$essayinfo->sent) {
167 // Holds values for the essayemailsubject string for the email message
168 $a = new stdClass;
170 // Set the grade
171 $grades = get_records_select('lesson_grades', "lessonid = $lesson->id and userid = $attempt->userid", 'completed', '*', $attempt->retry, 1);
172 $grade = current($grades);
173 $a->newgrade = $grade->grade;
175 // Set the points
176 if ($lesson->custom) {
177 $a->earned = $essayinfo->score;
178 $a->outof = $answers[$attempt->pageid]->score;
179 } else {
180 $a->earned = $essayinfo->score;
181 $a->outof = 1;
184 // Set rest of the message values
185 $a->question = format_text($pages[$attempt->pageid]->contents, FORMAT_MOODLE, $options);
186 $a->response = s(stripslashes_safe($essayinfo->answer));
187 $a->teacher = $course->teacher;
188 $a->comment = s($essayinfo->response);
191 // Fetch message HTML and plain text formats
192 $message = get_string('essayemailmessage', 'lesson', $a);
193 $plaintxt = format_text_email($message, FORMAT_HTML);
195 // Subject
196 $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));
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');
209 lesson_set_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
210 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
211 break;
214 // Log it
215 add_to_log($course->id, 'lesson', 'view grade', "essay.php?id=$cm->id", get_string('manualgrading', 'lesson'), $cm->id);
217 lesson_print_header($cm, $course, $lesson, 'essay');
219 switch ($mode) {
220 case 'display':
221 // Expects $user, $essayattempts and $pages to be set already
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;
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');
238 // Get the student ids of the users who have answered the essay question
239 $userids = array_keys($studentessays);
241 // Cycle through all the students
242 foreach ($userids as $userid) {
243 $studentname = fullname($users[$userid], true);
244 $essaylinks = array();
246 // Number of attempts on the lesson
247 $attempts = count_records('lesson_grades', 'userid', $userid, 'lessonid', $lesson->id);
249 // Go through each essay page
250 foreach ($studentessays[$userid] as $page => $tries) {
251 $count = 0;
253 // Go through each attempt per page
254 foreach($tries as $try) {
255 if ($count == $attempts) {
256 break; // Stop displaying essays (attempt not completed)
258 $count++;
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);
267 // Start processing the attempt
268 $essayinfo = unserialize($essay->useranswer);
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"';
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>';
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>';
285 $table->data[] = array(print_user_picture($userid, $course->id, $users[$userid]->picture, 0, true).$studentname, implode("<br />\n", $essaylinks), $emaillink);
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>';
290 $table->data[] = array(' ', ' ', $emailalllink);
292 print_table($table);
293 break;
294 case 'grade':
295 // Grading form
296 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
298 echo '<div class="grade">
299 <form id="essaygrade" method="post" action="'.$CFG->wwwroot.'/mod/lesson/essay.php">
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().'" />';
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';
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));
319 print_table($table);
321 unset($table->data);
323 // Now the user's answer
324 $essayinfo = unserialize($attempt->useranswer);
326 $table->head = array(get_string('studentresponse', 'lesson', fullname($user, true)));
327 $table->data[] = array(s(stripslashes_safe($essayinfo->answer)));
329 print_table($table);
331 unset($table->data);
333 // Now a response box and grade drop-down for grader
334 $table->head = array(get_string('comments', 'lesson'));
335 $table->data[] = array(print_textarea(false, 15, 60, 0, 0, 'response', $essayinfo->response, $course->id, true));
336 $options = array();
337 if ($lesson->custom) {
338 for ($i=$answer->score; $i>=0; $i--) {
339 $options[$i] = $i;
341 } else {
342 $options[0] = get_string('nocredit', 'lesson');
343 $options[1] = get_string('credit', 'lesson');
345 $table->data[] = array(get_string('essayscore', 'lesson').': '.choose_from_menu($options, 'score', $essayinfo->score, '', '', '', true));
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;
357 print_footer($course);