Moodle  2.2.1
http://www.collinsharper.com
C:/xampp/htdocs/moodle/mod/lesson/essay.php
Go to the documentation of this file.
00001 <?php
00002 
00003 // This file is part of Moodle - http://moodle.org/
00004 //
00005 // Moodle is free software: you can redistribute it and/or modify
00006 // it under the terms of the GNU General Public License as published by
00007 // the Free Software Foundation, either version 3 of the License, or
00008 // (at your option) any later version.
00009 //
00010 // Moodle is distributed in the hope that it will be useful,
00011 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013 // GNU General Public License for more details.
00014 //
00015 // You should have received a copy of the GNU General Public License
00016 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
00017 
00027 require_once('../../config.php');
00028 require_once($CFG->dirroot.'/mod/lesson/locallib.php');
00029 require_once($CFG->dirroot.'/mod/lesson/essay_form.php');
00030 require_once($CFG->libdir.'/eventslib.php');
00031 
00032 $id   = required_param('id', PARAM_INT);             // Course Module ID
00033 $mode = optional_param('mode', 'display', PARAM_ALPHA);
00034 
00035 $cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST);;
00036 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
00037 $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST));
00038 
00039 require_login($course, false, $cm);
00040 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
00041 require_capability('mod/lesson:edit', $context);
00042 
00043 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$id));
00044 if ($mode !== 'display') {
00045     $url->param('mode', $mode);
00046 }
00047 $PAGE->set_url($url);
00048 
00049 $attempt = new stdClass();
00050 $user = new stdClass();
00051 $attemptid = optional_param('attemptid', 0, PARAM_INT);
00052 
00053 if ($attemptid > 0) {
00054     $attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid));
00055     $answer = $DB->get_record('lesson_answers', array('lessonid' => $lesson->id, 'pageid' => $attempt->pageid));
00056     $user = $DB->get_record('user', array('id' => $attempt->userid));
00057     $scoreoptions = array();
00058     if ($lesson->custom) {
00059         $i = $answer->score;
00060         while ($i >= 0) {
00061             $scoreoptions[$i] = (string)$i;
00062             $i--;
00063         }
00064     } else {
00065         $scoreoptions[0] = get_string('nocredit', 'lesson');
00066         $scoreoptions[1] = get_string('credit', 'lesson');
00067     }
00068 }
00069 
00071 switch ($mode) {
00072     case 'grade':
00073         // Grading form - get the necessary data
00074         require_sesskey();
00075 
00076         if (empty($attempt)) {
00077             print_error('cannotfindattempt', 'lesson');
00078         }
00079         if (empty($user)) {
00080             print_error('cannotfinduser', 'lesson');
00081         }
00082         if (empty($answer)) {
00083             print_error('cannotfindanswer', 'lesson');
00084         }
00085         break;
00086 
00087     case 'update':
00088         require_sesskey();
00089 
00090         if (empty($attempt)) {
00091             print_error('cannotfindattempt', 'lesson');
00092         }
00093         if (empty($user)) {
00094             print_error('cannotfinduser', 'lesson');
00095         }
00096 
00097         $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
00098         if ($mform->is_cancelled()) {
00099             redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
00100         }
00101         if ($form = $mform->get_data()) {
00102             if (!$grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1)) {
00103                 print_error('cannotfindgrade', 'lesson');
00104             }
00105 
00106             $essayinfo = new stdClass;
00107             $essayinfo = unserialize($attempt->useranswer);
00108 
00109             $essayinfo->graded = 1;
00110             $essayinfo->score = $form->score;
00111             $essayinfo->response = clean_param($form->response, PARAM_RAW);
00112             $essayinfo->sent = 0;
00113             if (!$lesson->custom && $essayinfo->score == 1) {
00114                 $attempt->correct = 1;
00115             } else {
00116                 $attempt->correct = 0;
00117             }
00118 
00119             $attempt->useranswer = serialize($essayinfo);
00120 
00121             $DB->update_record('lesson_attempts', $attempt);
00122 
00123             // Get grade information
00124             $grade = current($grades);
00125             $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
00126 
00127             // Set and update
00128             $updategrade = new stdClass();
00129             $updategrade->id = $grade->id;
00130             $updategrade->grade = $gradeinfo->grade;
00131             $DB->update_record('lesson_grades', $updategrade);
00132             // Log it
00133             add_to_log($course->id, 'lesson', 'update grade', "essay.php?id=$cm->id", $lesson->name, $cm->id);
00134 
00135             $lesson->add_message(get_string('changessaved'), 'notifysuccess');
00136 
00137             // update central gradebook
00138             lesson_update_grades($lesson, $grade->userid);
00139 
00140             redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
00141         } else {
00142             print_error('invalidformdata');
00143         }
00144         break;
00145     case 'email':
00146         // Sending an email(s) to a single user or all
00147         require_sesskey();
00148 
00149         // Get our users (could be singular)
00150         if ($userid = optional_param('userid', 0, PARAM_INT)) {
00151             $queryadd = " AND userid = ?";
00152             if (! $users = $DB->get_records('user', array('id' => $userid))) {
00153                 print_error('cannotfinduser', 'lesson');
00154             }
00155         } else {
00156             $queryadd = '';
00157             $params = array ("lessonid" => $lesson->id);
00158             // Need to use inner view to avoid distinct + text
00159             if (!$users = $DB->get_records_sql("
00160                 SELECT u.*
00161                   FROM {user} u
00162                   JOIN (
00163                     SELECT DISTINCT u.id
00164                       FROM {user} u,
00165                            {lesson_attempts} a
00166                      WHERE a.lessonid = :lessonid and
00167                            u.id = a.userid) ui ON (u.id = ui.id)
00168                   ORDER BY u.lastname", $params)) {
00169                 print_error('cannotfinduser', 'lesson');
00170             }
00171         }
00172 
00173         $pages = $lesson->load_all_pages();
00174         foreach ($pages as $key=>$page) {
00175             if ($page->qtype !== LESSON_PAGE_ESSAY) {
00176                 unset($pages[$key]);
00177             }
00178         }
00179 
00180         // Get only the attempts that are in response to essay questions
00181         list($usql, $params) = $DB->get_in_or_equal(array_keys($pages));
00182         if (!empty($queryadd)) {
00183             $params[] = $userid;
00184         }
00185         if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
00186             print_error('nooneansweredthisquestion', 'lesson');
00187         }
00188         // Get the answers
00189         list($answerUsql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
00190         array_unshift($parameters, $lesson->id);
00191         if (!$answers = $DB->get_records_select('lesson_answers', "lessonid = ? AND pageid $answerUsql", $parameters, '', 'pageid, score')) {
00192             print_error('cannotfindanswer', 'lesson');
00193         }
00194         $options = new stdClass;
00195         $options->noclean = true;
00196 
00197         foreach ($attempts as $attempt) {
00198             $essayinfo = unserialize($attempt->useranswer);
00199             if ($essayinfo->graded && !$essayinfo->sent) {
00200                 // Holds values for the essayemailsubject string for the email message
00201                 $a = new stdClass;
00202 
00203                 // Set the grade
00204                 $grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1);
00205                 $grade  = current($grades);
00206                 $a->newgrade = $grade->grade;
00207 
00208                 // Set the points
00209                 if ($lesson->custom) {
00210                     $a->earned = $essayinfo->score;
00211                     $a->outof  = $answers[$attempt->pageid]->score;
00212                 } else {
00213                     $a->earned = $essayinfo->score;
00214                     $a->outof  = 1;
00215                 }
00216 
00217                 // Set rest of the message values
00218                 $currentpage = $lesson->load_page($attempt->pageid);
00219                 $a->question = format_text($currentpage->contents, $currentpage->contentsformat, $options);
00220                 $a->response = s($essayinfo->answer);
00221                 $a->comment  = s($essayinfo->response);
00222 
00223                 // Fetch message HTML and plain text formats
00224                 $message  = get_string('essayemailmessage2', 'lesson', $a);
00225                 $plaintext = format_text_email($message, FORMAT_HTML);
00226 
00227                 // Subject
00228                 $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));
00229 
00230                 $eventdata = new stdClass();
00231                 $eventdata->modulename       = 'lesson';
00232                 $eventdata->userfrom         = $USER;
00233                 $eventdata->userto           = $users[$attempt->userid];
00234                 $eventdata->subject          = $subject;
00235                 $eventdata->fullmessage      = $plaintext;
00236                 $eventdata->fullmessageformat = FORMAT_PLAIN;
00237                 $eventdata->fullmessagehtml  = $message;
00238                 $eventdata->smallmessage     = '';
00239 
00240                 // Required for messaging framework
00241                 $eventdata->component = 'mod_lesson';
00242                 $eventdata->name = 'graded_essay';
00243 
00244                 message_send($eventdata);
00245                 $essayinfo->sent = 1;
00246                 $attempt->useranswer = serialize($essayinfo);
00247                 $DB->update_record('lesson_attempts', $attempt);
00248                 // Log it
00249                 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);
00250             }
00251         }
00252         $lesson->add_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
00253         redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
00254         break;
00255     case 'display':  // Default view - get the necessary data
00256     default:
00257         // Get lesson pages that are essay
00258         $pages = $lesson->load_all_pages();
00259         foreach ($pages as $key=>$page) {
00260             if ($page->qtype !== LESSON_PAGE_ESSAY) {
00261                 unset($pages[$key]);
00262             }
00263         }
00264         if (count($pages) > 0) {
00265             $params = array ("lessonid" => $lesson->id, "qtype" => LESSON_PAGE_ESSAY);
00266             // Get only the attempts that are in response to essay questions
00267             list($usql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
00268             if ($essayattempts = $DB->get_records_select('lesson_attempts', 'pageid '.$usql, $parameters)) {
00269                 // Get all the users who have taken this lesson, order by their last name
00270                 $ufields = user_picture::fields('u');
00271                 if (!empty($cm->groupingid)) {
00272                     $params["groupinid"] = $cm->groupingid;
00273                     $sql = "SELECT DISTINCT $ufields
00274                             FROM {lesson_attempts} a
00275                                 INNER JOIN {user} u ON u.id = a.userid
00276                                 INNER JOIN {groups_members} gm ON gm.userid = u.id
00277                                 INNER JOIN {groupings_groups} gg ON gm.groupid = :groupinid
00278                             WHERE a.lessonid = :lessonid
00279                             ORDER BY u.lastname";
00280                 } else {
00281                     $sql = "SELECT DISTINCT $ufields
00282                             FROM {user} u,
00283                                  {lesson_attempts} a
00284                             WHERE a.lessonid = :lessonid and
00285                                   u.id = a.userid
00286                             ORDER BY u.lastname";
00287                 }
00288                 if (!$users = $DB->get_records_sql($sql, $params)) {
00289                     $mode = 'none'; // not displaying anything
00290                     $lesson->add_message(get_string('noonehasanswered', 'lesson'));
00291                 }
00292             } else {
00293                 $mode = 'none'; // not displaying anything
00294                 $lesson->add_message(get_string('noonehasanswered', 'lesson'));
00295             }
00296         } else {
00297             $mode = 'none'; // not displaying anything
00298             $lesson->add_message(get_string('noessayquestionsfound', 'lesson'));
00299         }
00300         break;
00301 }
00302 // Log it
00303 add_to_log($course->id, 'lesson', 'view grade', "essay.php?id=$cm->id", get_string('manualgrading', 'lesson'), $cm->id);
00304 
00305 $lessonoutput = $PAGE->get_renderer('mod_lesson');
00306 echo $lessonoutput->header($lesson, $cm, 'essay');
00307 
00308 switch ($mode) {
00309     case 'display':
00310         // Expects $user, $essayattempts and $pages to be set already
00311 
00312         // Group all the essays by userid
00313         $studentessays = array();
00314         foreach ($essayattempts as $essay) {
00315             // Not very nice :) but basically
00316             //   this organizes the essays so we know how many
00317             //   times a student answered an essay per try and per page
00318             $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
00319         }
00320 
00321         // Setup table
00322         $table = new html_table();
00323         $table->head = array(get_string('name'), get_string('essays', 'lesson'), get_string('email', 'lesson'));
00324         $table->attributes['class'] = 'standardtable generaltable';
00325         $table->align = array('left', 'left', 'left');
00326         $table->wrap = array('nowrap', 'nowrap', '');
00327 
00328         // Cycle through all the students
00329         foreach (array_keys($studentessays) as $userid) {
00330             $studentname = fullname($users[$userid], true);
00331             $essaylinks = array();
00332 
00333             // Number of attempts on the lesson
00334             $attempts = $DB->count_records('lesson_grades', array('userid'=>$userid, 'lessonid'=>$lesson->id));
00335 
00336             // Go through each essay page
00337             foreach ($studentessays[$userid] as $page => $tries) {
00338                 $count = 0;
00339 
00340                 // Go through each attempt per page
00341                 foreach($tries as $try) {
00342                     if ($count == $attempts) {
00343                         break;  // Stop displaying essays (attempt not completed)
00344                     }
00345                     $count++;
00346 
00347                     // Make sure they didn't answer it more than the max number of attmepts
00348                     if (count($try) > $lesson->maxattempts) {
00349                         $essay = $try[$lesson->maxattempts-1];
00350                     } else {
00351                         $essay = end($try);
00352                     }
00353 
00354                     // Start processing the attempt
00355                     $essayinfo = unserialize($essay->useranswer);
00356 
00357                     // link for each essay
00358                     $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'grade','attemptid'=>$essay->id,'sesskey'=>sesskey()));
00359                     $attributes = array();
00360                     // Different colors for all the states of an essay (graded, if sent, not graded)
00361                     if (!$essayinfo->graded) {
00362                         $attributes['class'] = "graded";
00363                     } elseif (!$essayinfo->sent) {
00364                         $attributes['class'] = "sent";
00365                     } else {
00366                         $attributes['class'] = "ungraded";
00367                     }
00368                     $essaylinks[] = html_writer::link($url, userdate($essay->timeseen, get_string('strftimedatetime')).' '.format_string($pages[$essay->pageid]->title,true), $attributes);
00369                 }
00370             }
00371             // email link for this user
00372             $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','userid'=>$userid,'sesskey'=>sesskey()));
00373             $emaillink = html_writer::link($url, get_string('emailgradedessays', 'lesson'));
00374 
00375             $table->data[] = array($OUTPUT->user_picture($users[$userid], array('courseid'=>$course->id)).$studentname, implode("<br />", $essaylinks), $emaillink);
00376         }
00377 
00378         // email link for all users
00379         $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','sesskey'=>sesskey()));
00380         $emailalllink = html_writer::link($url, get_string('emailallgradedessays', 'lesson'));
00381 
00382         $table->data[] = array(' ', ' ', $emailalllink);
00383 
00384         echo html_writer::table($table);
00385         break;
00386     case 'grade':
00387         // Grading form
00388         // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
00389         $essayinfo = unserialize($attempt->useranswer);
00390 
00391         $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
00392         $data = new stdClass;
00393         $data->id = $cm->id;
00394         $data->attemptid = $attemptid;
00395         $data->score = $essayinfo->score;
00396         $data->studentanswer = format_string($essayinfo->answer, FORMAT_MOODLE);
00397         $data->response = $essayinfo->response;
00398         $mform->set_data($data);
00399 
00400         $mform->display();
00401         break;
00402 }
00403 
00404 echo $OUTPUT->footer();
 All Data Structures Namespaces Files Functions Variables Enumerations