[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/mod/lesson/ -> essay.php (source)

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Provides the interface for grading essay questions
  20   *
  21   * @package mod_lesson
  22   * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   **/
  25  
  26  require_once('../../config.php');
  27  require_once($CFG->dirroot.'/mod/lesson/locallib.php');
  28  require_once($CFG->dirroot.'/mod/lesson/essay_form.php');
  29  require_once($CFG->libdir.'/eventslib.php');
  30  
  31  $id   = required_param('id', PARAM_INT);             // Course Module ID
  32  $mode = optional_param('mode', 'display', PARAM_ALPHA);
  33  
  34  $cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST);
  35  $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
  36  $dblesson = $DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST);
  37  $lesson = new lesson($dblesson);
  38  
  39  require_login($course, false, $cm);
  40  $context = context_module::instance($cm->id);
  41  require_capability('mod/lesson:grade', $context);
  42  
  43  $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$id));
  44  if ($mode !== 'display') {
  45      $url->param('mode', $mode);
  46  }
  47  $PAGE->set_url($url);
  48  
  49  $attempt = new stdClass();
  50  $user = new stdClass();
  51  $attemptid = optional_param('attemptid', 0, PARAM_INT);
  52  
  53  if ($attemptid > 0) {
  54      $attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid));
  55      $answer = $DB->get_record('lesson_answers', array('lessonid' => $lesson->id, 'pageid' => $attempt->pageid));
  56      $user = $DB->get_record('user', array('id' => $attempt->userid));
  57      $scoreoptions = array();
  58      if ($lesson->custom) {
  59          $i = $answer->score;
  60          while ($i >= 0) {
  61              $scoreoptions[$i] = (string)$i;
  62              $i--;
  63          }
  64      } else {
  65          $scoreoptions[0] = get_string('nocredit', 'lesson');
  66          $scoreoptions[1] = get_string('credit', 'lesson');
  67      }
  68  }
  69  
  70  /// Handle any preprocessing before header is printed - based on $mode
  71  switch ($mode) {
  72      case 'grade':
  73          // Grading form - get the necessary data
  74          require_sesskey();
  75  
  76          if (empty($attempt)) {
  77              print_error('cannotfindattempt', 'lesson');
  78          }
  79          if (empty($user)) {
  80              print_error('cannotfinduser', 'lesson');
  81          }
  82          if (empty($answer)) {
  83              print_error('cannotfindanswer', 'lesson');
  84          }
  85          break;
  86  
  87      case 'update':
  88          require_sesskey();
  89  
  90          if (empty($attempt)) {
  91              print_error('cannotfindattempt', 'lesson');
  92          }
  93          if (empty($user)) {
  94              print_error('cannotfinduser', 'lesson');
  95          }
  96  
  97          $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
  98          if ($mform->is_cancelled()) {
  99              redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
 100          }
 101          if ($form = $mform->get_data()) {
 102              if (!$grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1)) {
 103                  print_error('cannotfindgrade', 'lesson');
 104              }
 105  
 106              $essayinfo = new stdClass;
 107              $essayinfo = unserialize($attempt->useranswer);
 108  
 109              $essayinfo->graded = 1;
 110              $essayinfo->score = $form->score;
 111              $essayinfo->response = clean_param($form->response, PARAM_RAW);
 112              $essayinfo->sent = 0;
 113              if (!$lesson->custom && $essayinfo->score == 1) {
 114                  $attempt->correct = 1;
 115              } else {
 116                  $attempt->correct = 0;
 117              }
 118  
 119              $attempt->useranswer = serialize($essayinfo);
 120  
 121              $DB->update_record('lesson_attempts', $attempt);
 122  
 123              // Get grade information
 124              $grade = current($grades);
 125              $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);
 126  
 127              // Set and update
 128              $updategrade = new stdClass();
 129              $updategrade->id = $grade->id;
 130              $updategrade->grade = $gradeinfo->grade;
 131              $DB->update_record('lesson_grades', $updategrade);
 132  
 133              $params = array(
 134                  'context' => $context,
 135                  'objectid' => $grade->id,
 136                  'courseid' => $course->id,
 137                  'relateduserid' => $attempt->userid,
 138                  'other' => array(
 139                      'lessonid' => $lesson->id,
 140                      'attemptid' => $attemptid
 141                  )
 142              );
 143              $event = \mod_lesson\event\essay_assessed::create($params);
 144              $event->add_record_snapshot('lesson', $dblesson);
 145              $event->trigger();
 146  
 147              $lesson->add_message(get_string('changessaved'), 'notifysuccess');
 148  
 149              // update central gradebook
 150              lesson_update_grades($lesson, $grade->userid);
 151  
 152              redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
 153          } else {
 154              print_error('invalidformdata');
 155          }
 156          break;
 157      case 'email':
 158          // Sending an email(s) to a single user or all
 159          require_sesskey();
 160  
 161          // Get our users (could be singular)
 162          if ($userid = optional_param('userid', 0, PARAM_INT)) {
 163              $queryadd = " AND userid = ?";
 164              if (! $users = $DB->get_records('user', array('id' => $userid))) {
 165                  print_error('cannotfinduser', 'lesson');
 166              }
 167          } else {
 168              $queryadd = '';
 169              $params = array ("lessonid" => $lesson->id);
 170              // Need to use inner view to avoid distinct + text
 171              if (!$users = $DB->get_records_sql("
 172                  SELECT u.*
 173                    FROM {user} u
 174                    JOIN (
 175                             SELECT DISTINCT userid
 176                               FROM {lesson_attempts}
 177                              WHERE lessonid = :lessonid
 178                         ) ui ON u.id = ui.userid", $params)) {
 179                  print_error('cannotfinduser', 'lesson');
 180              }
 181          }
 182  
 183          $pages = $lesson->load_all_pages();
 184          foreach ($pages as $key=>$page) {
 185              if ($page->qtype != LESSON_PAGE_ESSAY) {
 186                  unset($pages[$key]);
 187              }
 188          }
 189  
 190          // Get only the attempts that are in response to essay questions
 191          list($usql, $params) = $DB->get_in_or_equal(array_keys($pages));
 192          if (!empty($queryadd)) {
 193              $params[] = $userid;
 194          }
 195          if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
 196              print_error('nooneansweredthisquestion', 'lesson');
 197          }
 198          // Get the answers
 199          list($answerUsql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
 200          array_unshift($parameters, $lesson->id);
 201          if (!$answers = $DB->get_records_select('lesson_answers', "lessonid = ? AND pageid $answerUsql", $parameters, '', 'pageid, score')) {
 202              print_error('cannotfindanswer', 'lesson');
 203          }
 204          $options = new stdClass;
 205          $options->noclean = true;
 206  
 207          foreach ($attempts as $attempt) {
 208              $essayinfo = unserialize($attempt->useranswer);
 209              if ($essayinfo->graded && !$essayinfo->sent) {
 210                  // Holds values for the essayemailsubject string for the email message
 211                  $a = new stdClass;
 212  
 213                  // Set the grade
 214                  $grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1);
 215                  $grade  = current($grades);
 216                  $a->newgrade = $grade->grade;
 217  
 218                  // Set the points
 219                  if ($lesson->custom) {
 220                      $a->earned = $essayinfo->score;
 221                      $a->outof  = $answers[$attempt->pageid]->score;
 222                  } else {
 223                      $a->earned = $essayinfo->score;
 224                      $a->outof  = 1;
 225                  }
 226  
 227                  // Set rest of the message values
 228                  $currentpage = $lesson->load_page($attempt->pageid);
 229                  $a->question = format_text($currentpage->contents, $currentpage->contentsformat, $options);
 230                  $a->response = s($essayinfo->answer);
 231                  $a->comment  = s($essayinfo->response);
 232  
 233                  // Fetch message HTML and plain text formats
 234                  $message  = get_string('essayemailmessage2', 'lesson', $a);
 235                  $plaintext = format_text_email($message, FORMAT_HTML);
 236  
 237                  // Subject
 238                  $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));
 239  
 240                  $eventdata = new stdClass();
 241                  $eventdata->modulename       = 'lesson';
 242                  $eventdata->userfrom         = $USER;
 243                  $eventdata->userto           = $users[$attempt->userid];
 244                  $eventdata->subject          = $subject;
 245                  $eventdata->fullmessage      = $plaintext;
 246                  $eventdata->fullmessageformat = FORMAT_PLAIN;
 247                  $eventdata->fullmessagehtml  = $message;
 248                  $eventdata->smallmessage     = '';
 249  
 250                  // Required for messaging framework
 251                  $eventdata->component = 'mod_lesson';
 252                  $eventdata->name = 'graded_essay';
 253  
 254                  message_send($eventdata);
 255                  $essayinfo->sent = 1;
 256                  $attempt->useranswer = serialize($essayinfo);
 257                  $DB->update_record('lesson_attempts', $attempt);
 258              }
 259          }
 260          $lesson->add_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
 261          redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
 262          break;
 263      case 'display':  // Default view - get the necessary data
 264      default:
 265          // Get lesson pages that are essay
 266          $pages = $lesson->load_all_pages();
 267          foreach ($pages as $key=>$page) {
 268              if ($page->qtype != LESSON_PAGE_ESSAY) {
 269                  unset($pages[$key]);
 270              }
 271          }
 272          if (count($pages) > 0) {
 273              $params = array ("lessonid" => $lesson->id, "qtype" => LESSON_PAGE_ESSAY);
 274              // Get only the attempts that are in response to essay questions
 275              list($usql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
 276              if ($essayattempts = $DB->get_records_select('lesson_attempts', 'pageid '.$usql, $parameters)) {
 277                  // Get all the users who have taken this lesson, order by their last name
 278                  $ufields = user_picture::fields('u');
 279                  list($sort, $sortparams) = users_order_by_sql('u');
 280                  $params = array_merge($params, $sortparams);
 281                  $sql = "SELECT DISTINCT $ufields
 282                          FROM {user} u,
 283                               {lesson_attempts} a
 284                          WHERE a.lessonid = :lessonid and
 285                                u.id = a.userid
 286                          ORDER BY $sort";
 287                  if (!$users = $DB->get_records_sql($sql, $params)) {
 288                      $mode = 'none'; // not displaying anything
 289                      $lesson->add_message(get_string('noonehasanswered', 'lesson'));
 290                  }
 291              } else {
 292                  $mode = 'none'; // not displaying anything
 293                  $lesson->add_message(get_string('noonehasanswered', 'lesson'));
 294              }
 295          } else {
 296              $mode = 'none'; // not displaying anything
 297              $lesson->add_message(get_string('noessayquestionsfound', 'lesson'));
 298          }
 299          break;
 300  }
 301  
 302  $lessonoutput = $PAGE->get_renderer('mod_lesson');
 303  echo $lessonoutput->header($lesson, $cm, 'essay', false, null, get_string('manualgrading', 'lesson'));
 304  
 305  switch ($mode) {
 306      case 'display':
 307          // Expects $user, $essayattempts and $pages to be set already
 308  
 309          // Group all the essays by userid
 310          $studentessays = array();
 311          foreach ($essayattempts as $essay) {
 312              // Not very nice :) but basically
 313              //   this organizes the essays so we know how many
 314              //   times a student answered an essay per try and per page
 315              $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
 316          }
 317  
 318          // Setup table
 319          $table = new html_table();
 320          $table->head = array(get_string('name'), get_string('essays', 'lesson'), get_string('email', 'lesson'));
 321          $table->attributes['class'] = 'standardtable generaltable';
 322          $table->align = array('left', 'left', 'left');
 323          $table->wrap = array('nowrap', 'nowrap', '');
 324  
 325          // Cycle through all the students
 326          foreach (array_keys($studentessays) as $userid) {
 327              $studentname = fullname($users[$userid], true);
 328              $essaylinks = array();
 329  
 330              // Number of attempts on the lesson
 331              $attempts = $DB->count_records('lesson_grades', array('userid'=>$userid, 'lessonid'=>$lesson->id));
 332  
 333              // Go through each essay page
 334              foreach ($studentessays[$userid] as $page => $tries) {
 335                  $count = 0;
 336  
 337                  // Go through each attempt per page
 338                  foreach($tries as $try) {
 339                      if ($count == $attempts) {
 340                          break;  // Stop displaying essays (attempt not completed)
 341                      }
 342                      $count++;
 343  
 344                      // Make sure they didn't answer it more than the max number of attmepts
 345                      if (count($try) > $lesson->maxattempts) {
 346                          $essay = $try[$lesson->maxattempts-1];
 347                      } else {
 348                          $essay = end($try);
 349                      }
 350  
 351                      // Start processing the attempt
 352                      $essayinfo = unserialize($essay->useranswer);
 353  
 354                      // link for each essay
 355                      $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'grade','attemptid'=>$essay->id,'sesskey'=>sesskey()));
 356                      $attributes = array();
 357                      // Different colors for all the states of an essay (graded, if sent, not graded)
 358                      if (!$essayinfo->graded) {
 359                          $attributes['class'] = "graded";
 360                      } elseif (!$essayinfo->sent) {
 361                          $attributes['class'] = "sent";
 362                      } else {
 363                          $attributes['class'] = "ungraded";
 364                      }
 365                      $essaylinks[] = html_writer::link($url, userdate($essay->timeseen, get_string('strftimedatetime')).' '.format_string($pages[$essay->pageid]->title,true), $attributes);
 366                  }
 367              }
 368              // email link for this user
 369              $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','userid'=>$userid,'sesskey'=>sesskey()));
 370              $emaillink = html_writer::link($url, get_string('emailgradedessays', 'lesson'));
 371  
 372              $table->data[] = array($OUTPUT->user_picture($users[$userid], array('courseid'=>$course->id)).$studentname, implode("<br />", $essaylinks), $emaillink);
 373          }
 374  
 375          // email link for all users
 376          $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','sesskey'=>sesskey()));
 377          $emailalllink = html_writer::link($url, get_string('emailallgradedessays', 'lesson'));
 378  
 379          $table->data[] = array(' ', ' ', $emailalllink);
 380  
 381          echo html_writer::table($table);
 382          break;
 383      case 'grade':
 384          // Trigger the essay grade viewed event.
 385          $event = \mod_lesson\event\essay_attempt_viewed::create(array(
 386              'objectid' => $attempt->id,
 387              'relateduserid' => $attempt->userid,
 388              'context' => $context,
 389              'courseid' => $course->id,
 390          ));
 391          $event->add_record_snapshot('lesson_attempts', $attempt);
 392          $event->trigger();
 393  
 394          // Grading form
 395          // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt
 396          $essayinfo = unserialize($attempt->useranswer);
 397          $currentpage = $lesson->load_page($attempt->pageid);
 398  
 399          $mform = new essay_grading_form(null, array('scoreoptions'=>$scoreoptions, 'user'=>$user));
 400          $data = new stdClass;
 401          $data->id = $cm->id;
 402          $data->attemptid = $attemptid;
 403          $data->score = $essayinfo->score;
 404          $data->question = format_string($currentpage->contents, $currentpage->contentsformat);
 405          $data->studentanswer = format_string($essayinfo->answer, $essayinfo->answerformat);
 406          $data->response = $essayinfo->response;
 407          $mform->set_data($data);
 408  
 409          $mform->display();
 410          break;
 411  }
 412  
 413  echo $OUTPUT->footer();


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1