merged from STABLE18
[moodle-linuxchix.git] / mod / lesson / essay.php
blob72535e885f9ba8d1ebffbe5ae239b37cada02793
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'));
117 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
118 } else {
119 error('Something is wrong with the form data');
121 break;
122 case 'email': // Sending an email(s) to a single user or all
123 confirm_sesskey();
125 // Get our users (could be singular)
126 if ($userid = optional_param('userid', 0, PARAM_INT)) {
127 $queryadd = " AND userid = $userid";
128 if (! $users = get_records('user', 'id', $userid)) {
129 error('Error: could not find users');
131 } else {
132 $queryadd = '';
133 if (!$users = get_records_sql("SELECT u.*
134 FROM {$CFG->prefix}user u,
135 {$CFG->prefix}lesson_attempts a
136 WHERE a.lessonid = '$lesson->id' and
137 u.id = a.userid
138 ORDER BY u.lastname")) {
139 error('Error: could not find users');
143 // Get lesson pages that are essay
144 if (!$pages = get_records_select('lesson_pages', "lessonid = $lesson->id AND qtype = ".LESSON_ESSAY)) {
145 error('Error: could not find lesson pages');
148 // Get only the attempts that are in response to essay questions
149 $pageids = implode(',', array_keys($pages)); // all the pageids in comma seperated list
150 if (!$attempts = get_records_select('lesson_attempts', "pageid IN($pageids)".$queryadd)) {
151 error ('No one has answered essay questions yet...');
153 // Get the answers
154 if (!$answers = get_records_select('lesson_answers', "lessonid = $lesson->id AND pageid IN($pageids)", '', 'pageid, score')) {
155 error ('Could not find answer records.');
157 $options = new stdClass;
158 $options->noclean = true;
160 foreach ($attempts as $attempt) {
161 $essayinfo = unserialize($attempt->useranswer);
162 if ($essayinfo->graded and !$essayinfo->sent) {
163 // Holds values for the essayemailsubject string for the email message
164 $a = new stdClass;
166 // Set the grade
167 $grades = get_records_select('lesson_grades', "lessonid = $lesson->id and userid = $attempt->userid", 'completed', '*', $attempt->retry, 1);
168 $grade = current($grades);
169 $a->newgrade = $grade->grade;
171 // Set the points
172 if ($lesson->custom) {
173 $a->earned = $essayinfo->score;
174 $a->outof = $answers[$attempt->pageid]->score;
175 } else {
176 $a->earned = $essayinfo->score;
177 $a->outof = 1;
180 // Set rest of the message values
181 $a->question = format_text($pages[$attempt->pageid]->contents, FORMAT_MOODLE, $options);
182 $a->response = s(stripslashes_safe($essayinfo->answer));
183 $a->teacher = $course->teacher;
184 $a->comment = s($essayinfo->response);
187 // Fetch message HTML and plain text formats
188 $message = get_string('essayemailmessage', 'lesson', $a);
189 $plaintxt = format_text_email($message, FORMAT_HTML);
191 // Subject
192 $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));
194 if(email_to_user($users[$attempt->userid], $USER, $subject, $plaintxt, $message)) {
195 $essayinfo->sent = 1;
196 $attempt->useranswer = addslashes(serialize($essayinfo));
197 update_record('lesson_attempts', $attempt);
198 // Log it
199 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);
200 } else {
201 error('Emailing Failed');
205 lesson_set_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
206 redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
207 break;
210 // Log it
211 add_to_log($course->id, 'lesson', 'view grade', "essay.php?id=$cm->id", get_string('manualgrading', 'lesson'), $cm->id);
213 lesson_print_header($cm, $course, $lesson, 'essay');
215 switch ($mode) {
216 case 'display':
217 // Expects $user, $essayattempts and $pages to be set already
219 // Group all the essays by userid
220 $studentessays = array();
221 foreach ($essayattempts as $essay) {
222 // Not very nice :) but basically
223 // this organizes the essays so we know how many
224 // times a student answered an essay per try and per page
225 $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
228 // Setup table
229 $table = new stdClass;
230 $table->head = array($course->students, get_string('essays', 'lesson'), get_string('email', 'lesson'));
231 $table->align = array('left', 'left', 'left');
232 $table->wrap = array('nowrap', 'nowrap', 'nowrap');
234 // Get the student ids of the users who have answered the essay question
235 $userids = array_keys($studentessays);
237 // Cycle through all the students
238 foreach ($userids as $userid) {
239 $studentname = fullname($users[$userid], true);
240 $essaylinks = array();
242 // Number of attempts on the lesson
243 $attempts = count_records('lesson_grades', 'userid', $userid, 'lessonid', $lesson->id);
245 // Go through each essay page
246 foreach ($studentessays[$userid] as $page => $tries) {
247 $count = 0;
249 // Go through each attempt per page
250 foreach($tries as $try) {
251 if ($count == $attempts) {
252 break; // Stop displaying essays (attempt not completed)
254 $count++;
256 // Make sure they didn't answer it more than the max number of attmepts
257 if (count($try) > $lesson->maxattempts) {
258 $essay = $try[$lesson->maxattempts-1];
259 } else {
260 $essay = end($try);
263 // Start processing the attempt
264 $essayinfo = unserialize($essay->useranswer);
266 // Different colors for all the states of an essay (graded, if sent, not graded)
267 if (!$essayinfo->graded) {
268 $class = ' class="graded"';
269 } elseif (!$essayinfo->sent) {
270 $class = ' class="sent"';
271 } else {
272 $class = ' class="ungraded"';
274 // link for each essay
275 $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>';
278 // email link for this user
279 $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>';
281 $table->data[] = array(print_user_picture($userid, $course->id, $users[$userid]->picture, 0, true).$studentname, implode("<br />\n", $essaylinks), $emaillink);
283 // email link for all users
284 $emailalllink = "<a href=\"$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id&amp;mode=email&amp;sesskey=".sesskey().'">'.get_string('emailallgradedessays', 'lesson').'</a>';
286 $table->data[] = array(' ', ' ', $emailalllink);
288 print_table($table);
289 break;
290 case 'grade':
291 // Grading form
292 // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
294 echo '<div class="grade">
295 <form id="essaygrade" method="post" action="'.$CFG->wwwroot.'/mod/lesson/essay.php">
296 <input type="hidden" name="id" value="'.$cm->id.'" />
297 <input type="hidden" name="mode" value="update" />
298 <input type="hidden" name="attemptid" value="'.$attemptid.'" />
299 <input type="hidden" name="sesskey" value="'.sesskey().'" />';
301 // All tables will have these settings
302 $table = new stdClass;
303 $table->align = array('left');
304 $table->wrap = array();
305 $table->width = '50%';
306 $table->size = array('100%');
307 $table->class = 'generaltable gradetable';
309 // Print the question
310 $table->head = array(get_string('question', 'lesson'));
311 $options = new stdClass;
312 $options->noclean = true;
313 $table->data[] = array(format_text($page->contents, FORMAT_MOODLE, $options));
315 print_table($table);
317 unset($table->data);
319 // Now the user's answer
320 $essayinfo = unserialize($attempt->useranswer);
322 $table->head = array(get_string('studentresponse', 'lesson', fullname($user, true)));
323 $table->data[] = array(s(stripslashes_safe($essayinfo->answer)));
325 print_table($table);
327 unset($table->data);
329 // Now a response box and grade drop-down for grader
330 $table->head = array(get_string('comments', 'lesson'));
331 $table->data[] = array(print_textarea(false, 15, 60, 0, 0, 'response', $essayinfo->response, $course->id, true));
332 $options = array();
333 if ($lesson->custom) {
334 for ($i=$answer->score; $i>=0; $i--) {
335 $options[$i] = $i;
337 } else {
338 $options[0] = get_string('nocredit', 'lesson');
339 $options[1] = get_string('credit', 'lesson');
341 $table->data[] = array(get_string('essayscore', 'lesson').': '.choose_from_menu($options, 'score', $essayinfo->score, '', '', '', true));
343 print_table($table);
344 echo '<div class="buttons">
345 <input type="submit" name="cancel" value="'.get_string('cancel').'" />
346 <input type="submit" value="'.get_string('savechanges').'" />
347 </div>
348 </form>
349 </div>';
350 break;
353 print_footer($course);