[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/grade/grading/form/rubric/ -> lib.php (source)

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Grading method controller for the Rubric plugin
  19   *
  20   * @package    gradingform_rubric
  21   * @copyright  2011 David Mudrak <david@moodle.com>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  require_once($CFG->dirroot.'/grade/grading/form/lib.php');
  28  
  29  /**
  30   * This controller encapsulates the rubric grading logic
  31   *
  32   * @package    gradingform_rubric
  33   * @copyright  2011 David Mudrak <david@moodle.com>
  34   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   */
  36  class gradingform_rubric_controller extends gradingform_controller {
  37      // Modes of displaying the rubric (used in gradingform_rubric_renderer)
  38      /** Rubric display mode: For editing (moderator or teacher creates a rubric) */
  39      const DISPLAY_EDIT_FULL     = 1;
  40      /** Rubric display mode: Preview the rubric design with hidden fields */
  41      const DISPLAY_EDIT_FROZEN   = 2;
  42      /** Rubric display mode: Preview the rubric design (for person with manage permission) */
  43      const DISPLAY_PREVIEW       = 3;
  44      /** Rubric display mode: Preview the rubric (for people being graded) */
  45      const DISPLAY_PREVIEW_GRADED= 8;
  46      /** Rubric display mode: For evaluation, enabled (teacher grades a student) */
  47      const DISPLAY_EVAL          = 4;
  48      /** Rubric display mode: For evaluation, with hidden fields */
  49      const DISPLAY_EVAL_FROZEN   = 5;
  50      /** Rubric display mode: Teacher reviews filled rubric */
  51      const DISPLAY_REVIEW        = 6;
  52      /** Rubric display mode: Dispaly filled rubric (i.e. students see their grades) */
  53      const DISPLAY_VIEW          = 7;
  54  
  55      /**
  56       * Extends the module settings navigation with the rubric grading settings
  57       *
  58       * This function is called when the context for the page is an activity module with the
  59       * FEATURE_ADVANCED_GRADING, the user has the permission moodle/grade:managegradingforms
  60       * and there is an area with the active grading method set to 'rubric'.
  61       *
  62       * @param settings_navigation $settingsnav {@link settings_navigation}
  63       * @param navigation_node $node {@link navigation_node}
  64       */
  65      public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $node=null) {
  66          $node->add(get_string('definerubric', 'gradingform_rubric'),
  67              $this->get_editor_url(), settings_navigation::TYPE_CUSTOM,
  68              null, null, new pix_icon('icon', '', 'gradingform_rubric'));
  69      }
  70  
  71      /**
  72       * Extends the module navigation
  73       *
  74       * This function is called when the context for the page is an activity module with the
  75       * FEATURE_ADVANCED_GRADING and there is an area with the active grading method set to the given plugin.
  76       *
  77       * @param global_navigation $navigation {@link global_navigation}
  78       * @param navigation_node $node {@link navigation_node}
  79       */
  80      public function extend_navigation(global_navigation $navigation, navigation_node $node=null) {
  81          if (has_capability('moodle/grade:managegradingforms', $this->get_context())) {
  82              // no need for preview if user can manage forms, he will have link to manage.php in settings instead
  83              return;
  84          }
  85          if ($this->is_form_defined() && ($options = $this->get_options()) && !empty($options['alwaysshowdefinition'])) {
  86              $node->add(get_string('gradingof', 'gradingform_rubric', get_grading_manager($this->get_areaid())->get_area_title()),
  87                      new moodle_url('/grade/grading/form/'.$this->get_method_name().'/preview.php', array('areaid' => $this->get_areaid())),
  88                      settings_navigation::TYPE_CUSTOM);
  89          }
  90      }
  91  
  92      /**
  93       * Saves the rubric definition into the database
  94       *
  95       * @see parent::update_definition()
  96       * @param stdClass $newdefinition rubric definition data as coming from gradingform_rubric_editrubric::get_data()
  97       * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
  98       */
  99      public function update_definition(stdClass $newdefinition, $usermodified = null) {
 100          $this->update_or_check_rubric($newdefinition, $usermodified, true);
 101          if (isset($newdefinition->rubric['regrade']) && $newdefinition->rubric['regrade']) {
 102              $this->mark_for_regrade();
 103          }
 104      }
 105  
 106      /**
 107       * Either saves the rubric definition into the database or check if it has been changed.
 108       * Returns the level of changes:
 109       * 0 - no changes
 110       * 1 - only texts or criteria sortorders are changed, students probably do not require re-grading
 111       * 2 - added levels but maximum score on rubric is the same, students still may not require re-grading
 112       * 3 - removed criteria or added levels or changed number of points, students require re-grading but may be re-graded automatically
 113       * 4 - removed levels - students require re-grading and not all students may be re-graded automatically
 114       * 5 - added criteria - all students require manual re-grading
 115       *
 116       * @param stdClass $newdefinition rubric definition data as coming from gradingform_rubric_editrubric::get_data()
 117       * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
 118       * @param boolean $doupdate if true actually updates DB, otherwise performs a check
 119       *
 120       */
 121      public function update_or_check_rubric(stdClass $newdefinition, $usermodified = null, $doupdate = false) {
 122          global $DB;
 123  
 124          // firstly update the common definition data in the {grading_definition} table
 125          if ($this->definition === false) {
 126              if (!$doupdate) {
 127                  // if we create the new definition there is no such thing as re-grading anyway
 128                  return 5;
 129              }
 130              // if definition does not exist yet, create a blank one
 131              // (we need id to save files embedded in description)
 132              parent::update_definition(new stdClass(), $usermodified);
 133              parent::load_definition();
 134          }
 135          if (!isset($newdefinition->rubric['options'])) {
 136              $newdefinition->rubric['options'] = self::get_default_options();
 137          }
 138          $newdefinition->options = json_encode($newdefinition->rubric['options']);
 139          $editoroptions = self::description_form_field_options($this->get_context());
 140          $newdefinition = file_postupdate_standard_editor($newdefinition, 'description', $editoroptions, $this->get_context(),
 141              'grading', 'description', $this->definition->id);
 142  
 143          // reload the definition from the database
 144          $currentdefinition = $this->get_definition(true);
 145  
 146          // update rubric data
 147          $haschanges = array();
 148          if (empty($newdefinition->rubric['criteria'])) {
 149              $newcriteria = array();
 150          } else {
 151              $newcriteria = $newdefinition->rubric['criteria']; // new ones to be saved
 152          }
 153          $currentcriteria = $currentdefinition->rubric_criteria;
 154          $criteriafields = array('sortorder', 'description', 'descriptionformat');
 155          $levelfields = array('score', 'definition', 'definitionformat');
 156          foreach ($newcriteria as $id => $criterion) {
 157              // get list of submitted levels
 158              $levelsdata = array();
 159              if (array_key_exists('levels', $criterion)) {
 160                  $levelsdata = $criterion['levels'];
 161              }
 162              $criterionmaxscore = null;
 163              if (preg_match('/^NEWID\d+$/', $id)) {
 164                  // insert criterion into DB
 165                  $data = array('definitionid' => $this->definition->id, 'descriptionformat' => FORMAT_MOODLE); // TODO MDL-31235 format is not supported yet
 166                  foreach ($criteriafields as $key) {
 167                      if (array_key_exists($key, $criterion)) {
 168                          $data[$key] = $criterion[$key];
 169                      }
 170                  }
 171                  if ($doupdate) {
 172                      $id = $DB->insert_record('gradingform_rubric_criteria', $data);
 173                  }
 174                  $haschanges[5] = true;
 175              } else {
 176                  // update criterion in DB
 177                  $data = array();
 178                  foreach ($criteriafields as $key) {
 179                      if (array_key_exists($key, $criterion) && $criterion[$key] != $currentcriteria[$id][$key]) {
 180                          $data[$key] = $criterion[$key];
 181                      }
 182                  }
 183                  if (!empty($data)) {
 184                      // update only if something is changed
 185                      $data['id'] = $id;
 186                      if ($doupdate) {
 187                          $DB->update_record('gradingform_rubric_criteria', $data);
 188                      }
 189                      $haschanges[1] = true;
 190                  }
 191                  // remove deleted levels from DB and calculate the maximum score for this criteria
 192                  foreach ($currentcriteria[$id]['levels'] as $levelid => $currentlevel) {
 193                      if ($criterionmaxscore === null || $criterionmaxscore < $currentlevel['score']) {
 194                          $criterionmaxscore = $currentlevel['score'];
 195                      }
 196                      if (!array_key_exists($levelid, $levelsdata)) {
 197                          if ($doupdate) {
 198                              $DB->delete_records('gradingform_rubric_levels', array('id' => $levelid));
 199                          }
 200                          $haschanges[4] = true;
 201                      }
 202                  }
 203              }
 204              foreach ($levelsdata as $levelid => $level) {
 205                  if (isset($level['score'])) {
 206                      $level['score'] = (float)$level['score'];
 207                      if ($level['score']<0) {
 208                          $level['score'] = 0;
 209                      }
 210                  }
 211                  if (preg_match('/^NEWID\d+$/', $levelid)) {
 212                      // insert level into DB
 213                      $data = array('criterionid' => $id, 'definitionformat' => FORMAT_MOODLE); // TODO MDL-31235 format is not supported yet
 214                      foreach ($levelfields as $key) {
 215                          if (array_key_exists($key, $level)) {
 216                              $data[$key] = $level[$key];
 217                          }
 218                      }
 219                      if ($doupdate) {
 220                          $levelid = $DB->insert_record('gradingform_rubric_levels', $data);
 221                      }
 222                      if ($criterionmaxscore !== null && $criterionmaxscore >= $level['score']) {
 223                          // new level is added but the maximum score for this criteria did not change, re-grading may not be necessary
 224                          $haschanges[2] = true;
 225                      } else {
 226                          $haschanges[3] = true;
 227                      }
 228                  } else {
 229                      // update level in DB
 230                      $data = array();
 231                      foreach ($levelfields as $key) {
 232                          if (array_key_exists($key, $level) && $level[$key] != $currentcriteria[$id]['levels'][$levelid][$key]) {
 233                              $data[$key] = $level[$key];
 234                          }
 235                      }
 236                      if (!empty($data)) {
 237                          // update only if something is changed
 238                          $data['id'] = $levelid;
 239                          if ($doupdate) {
 240                              $DB->update_record('gradingform_rubric_levels', $data);
 241                          }
 242                          if (isset($data['score'])) {
 243                              $haschanges[3] = true;
 244                          }
 245                          $haschanges[1] = true;
 246                      }
 247                  }
 248              }
 249          }
 250          // remove deleted criteria from DB
 251          foreach (array_keys($currentcriteria) as $id) {
 252              if (!array_key_exists($id, $newcriteria)) {
 253                  if ($doupdate) {
 254                      $DB->delete_records('gradingform_rubric_criteria', array('id' => $id));
 255                      $DB->delete_records('gradingform_rubric_levels', array('criterionid' => $id));
 256                  }
 257                  $haschanges[3] = true;
 258              }
 259          }
 260          foreach (array('status', 'description', 'descriptionformat', 'name', 'options') as $key) {
 261              if (isset($newdefinition->$key) && $newdefinition->$key != $this->definition->$key) {
 262                  $haschanges[1] = true;
 263              }
 264          }
 265          if ($usermodified && $usermodified != $this->definition->usermodified) {
 266              $haschanges[1] = true;
 267          }
 268          if (!count($haschanges)) {
 269              return 0;
 270          }
 271          if ($doupdate) {
 272              parent::update_definition($newdefinition, $usermodified);
 273              $this->load_definition();
 274          }
 275          // return the maximum level of changes
 276          $changelevels = array_keys($haschanges);
 277          sort($changelevels);
 278          return array_pop($changelevels);
 279      }
 280  
 281      /**
 282       * Marks all instances filled with this rubric with the status INSTANCE_STATUS_NEEDUPDATE
 283       */
 284      public function mark_for_regrade() {
 285          global $DB;
 286          if ($this->has_active_instances()) {
 287              $conditions = array('definitionid'  => $this->definition->id,
 288                          'status'  => gradingform_instance::INSTANCE_STATUS_ACTIVE);
 289              $DB->set_field('grading_instances', 'status', gradingform_instance::INSTANCE_STATUS_NEEDUPDATE, $conditions);
 290          }
 291      }
 292  
 293      /**
 294       * Loads the rubric form definition if it exists
 295       *
 296       * There is a new array called 'rubric_criteria' appended to the list of parent's definition properties.
 297       */
 298      protected function load_definition() {
 299          global $DB;
 300          $sql = "SELECT gd.*,
 301                         rc.id AS rcid, rc.sortorder AS rcsortorder, rc.description AS rcdescription, rc.descriptionformat AS rcdescriptionformat,
 302                         rl.id AS rlid, rl.score AS rlscore, rl.definition AS rldefinition, rl.definitionformat AS rldefinitionformat
 303                    FROM {grading_definitions} gd
 304               LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.definitionid = gd.id)
 305               LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)
 306                   WHERE gd.areaid = :areaid AND gd.method = :method
 307                ORDER BY rc.sortorder,rl.score";
 308          $params = array('areaid' => $this->areaid, 'method' => $this->get_method_name());
 309  
 310          $rs = $DB->get_recordset_sql($sql, $params);
 311          $this->definition = false;
 312          foreach ($rs as $record) {
 313              // pick the common definition data
 314              if ($this->definition === false) {
 315                  $this->definition = new stdClass();
 316                  foreach (array('id', 'name', 'description', 'descriptionformat', 'status', 'copiedfromid',
 317                          'timecreated', 'usercreated', 'timemodified', 'usermodified', 'timecopied', 'options') as $fieldname) {
 318                      $this->definition->$fieldname = $record->$fieldname;
 319                  }
 320                  $this->definition->rubric_criteria = array();
 321              }
 322              // pick the criterion data
 323              if (!empty($record->rcid) and empty($this->definition->rubric_criteria[$record->rcid])) {
 324                  foreach (array('id', 'sortorder', 'description', 'descriptionformat') as $fieldname) {
 325                      $this->definition->rubric_criteria[$record->rcid][$fieldname] = $record->{'rc'.$fieldname};
 326                  }
 327                  $this->definition->rubric_criteria[$record->rcid]['levels'] = array();
 328              }
 329              // pick the level data
 330              if (!empty($record->rlid)) {
 331                  foreach (array('id', 'score', 'definition', 'definitionformat') as $fieldname) {
 332                      $value = $record->{'rl'.$fieldname};
 333                      if ($fieldname == 'score') {
 334                          $value = (float)$value; // To prevent display like 1.00000
 335                      }
 336                      $this->definition->rubric_criteria[$record->rcid]['levels'][$record->rlid][$fieldname] = $value;
 337                  }
 338              }
 339          }
 340          $rs->close();
 341          $options = $this->get_options();
 342          if (!$options['sortlevelsasc']) {
 343              foreach (array_keys($this->definition->rubric_criteria) as $rcid) {
 344                  $this->definition->rubric_criteria[$rcid]['levels'] = array_reverse($this->definition->rubric_criteria[$rcid]['levels'], true);
 345              }
 346          }
 347      }
 348  
 349      /**
 350       * Returns the default options for the rubric display
 351       *
 352       * @return array
 353       */
 354      public static function get_default_options() {
 355          $options = array(
 356              'sortlevelsasc' => 1,
 357              'alwaysshowdefinition' => 1,
 358              'showdescriptionteacher' => 1,
 359              'showdescriptionstudent' => 1,
 360              'showscoreteacher' => 1,
 361              'showscorestudent' => 1,
 362              'enableremarks' => 1,
 363              'showremarksstudent' => 1
 364          );
 365          return $options;
 366      }
 367  
 368      /**
 369       * Gets the options of this rubric definition, fills the missing options with default values
 370       *
 371       * @return array
 372       */
 373      public function get_options() {
 374          $options = self::get_default_options();
 375          if (!empty($this->definition->options)) {
 376              $thisoptions = json_decode($this->definition->options);
 377              foreach ($thisoptions as $option => $value) {
 378                  $options[$option] = $value;
 379              }
 380          }
 381          return $options;
 382      }
 383  
 384      /**
 385       * Converts the current definition into an object suitable for the editor form's set_data()
 386       *
 387       * @param boolean $addemptycriterion whether to add an empty criterion if the rubric is completely empty (just being created)
 388       * @return stdClass
 389       */
 390      public function get_definition_for_editing($addemptycriterion = false) {
 391  
 392          $definition = $this->get_definition();
 393          $properties = new stdClass();
 394          $properties->areaid = $this->areaid;
 395          if ($definition) {
 396              foreach (array('id', 'name', 'description', 'descriptionformat', 'status') as $key) {
 397                  $properties->$key = $definition->$key;
 398              }
 399              $options = self::description_form_field_options($this->get_context());
 400              $properties = file_prepare_standard_editor($properties, 'description', $options, $this->get_context(),
 401                  'grading', 'description', $definition->id);
 402          }
 403          $properties->rubric = array('criteria' => array(), 'options' => $this->get_options());
 404          if (!empty($definition->rubric_criteria)) {
 405              $properties->rubric['criteria'] = $definition->rubric_criteria;
 406          } else if (!$definition && $addemptycriterion) {
 407              $properties->rubric['criteria'] = array('addcriterion' => 1);
 408          }
 409  
 410          return $properties;
 411      }
 412  
 413      /**
 414       * Returns the form definition suitable for cloning into another area
 415       *
 416       * @see parent::get_definition_copy()
 417       * @param gradingform_controller $target the controller of the new copy
 418       * @return stdClass definition structure to pass to the target's {@link update_definition()}
 419       */
 420      public function get_definition_copy(gradingform_controller $target) {
 421  
 422          $new = parent::get_definition_copy($target);
 423          $old = $this->get_definition_for_editing();
 424          $new->description_editor = $old->description_editor;
 425          $new->rubric = array('criteria' => array(), 'options' => $old->rubric['options']);
 426          $newcritid = 1;
 427          $newlevid = 1;
 428          foreach ($old->rubric['criteria'] as $oldcritid => $oldcrit) {
 429              unset($oldcrit['id']);
 430              if (isset($oldcrit['levels'])) {
 431                  foreach ($oldcrit['levels'] as $oldlevid => $oldlev) {
 432                      unset($oldlev['id']);
 433                      $oldcrit['levels']['NEWID'.$newlevid] = $oldlev;
 434                      unset($oldcrit['levels'][$oldlevid]);
 435                      $newlevid++;
 436                  }
 437              } else {
 438                  $oldcrit['levels'] = array();
 439              }
 440              $new->rubric['criteria']['NEWID'.$newcritid] = $oldcrit;
 441              $newcritid++;
 442          }
 443  
 444          return $new;
 445      }
 446  
 447      /**
 448       * Options for displaying the rubric description field in the form
 449       *
 450       * @param object $context
 451       * @return array options for the form description field
 452       */
 453      public static function description_form_field_options($context) {
 454          global $CFG;
 455          return array(
 456              'maxfiles' => -1,
 457              'maxbytes' => get_user_max_upload_file_size($context, $CFG->maxbytes),
 458              'context'  => $context,
 459          );
 460      }
 461  
 462      /**
 463       * Formats the definition description for display on page
 464       *
 465       * @return string
 466       */
 467      public function get_formatted_description() {
 468          if (!isset($this->definition->description)) {
 469              return '';
 470          }
 471          $context = $this->get_context();
 472  
 473          $options = self::description_form_field_options($this->get_context());
 474          $description = file_rewrite_pluginfile_urls($this->definition->description, 'pluginfile.php', $context->id,
 475              'grading', 'description', $this->definition->id, $options);
 476  
 477          $formatoptions = array(
 478              'noclean' => false,
 479              'trusted' => false,
 480              'filter' => true,
 481              'context' => $context
 482          );
 483          return format_text($description, $this->definition->descriptionformat, $formatoptions);
 484      }
 485  
 486      /**
 487       * Returns the rubric plugin renderer
 488       *
 489       * @param moodle_page $page the target page
 490       * @return gradingform_rubric_renderer
 491       */
 492      public function get_renderer(moodle_page $page) {
 493          return $page->get_renderer('gradingform_'. $this->get_method_name());
 494      }
 495  
 496      /**
 497       * Returns the HTML code displaying the preview of the grading form
 498       *
 499       * @param moodle_page $page the target page
 500       * @return string
 501       */
 502      public function render_preview(moodle_page $page) {
 503  
 504          if (!$this->is_form_defined()) {
 505              throw new coding_exception('It is the caller\'s responsibility to make sure that the form is actually defined');
 506          }
 507  
 508          $criteria = $this->definition->rubric_criteria;
 509          $options = $this->get_options();
 510          $rubric = '';
 511          if (has_capability('moodle/grade:managegradingforms', $page->context)) {
 512              $showdescription = true;
 513          } else {
 514              if (empty($options['alwaysshowdefinition']))  {
 515                  // ensure we don't display unless show rubric option enabled
 516                  return '';
 517              }
 518              $showdescription = $options['showdescriptionstudent'];
 519          }
 520          $output = $this->get_renderer($page);
 521          if ($showdescription) {
 522              $rubric .= $output->box($this->get_formatted_description(), 'gradingform_rubric-description');
 523          }
 524          if (has_capability('moodle/grade:managegradingforms', $page->context)) {
 525              $rubric .= $output->display_rubric_mapping_explained($this->get_min_max_score());
 526              $rubric .= $output->display_rubric($criteria, $options, self::DISPLAY_PREVIEW, 'rubric');
 527          } else {
 528              $rubric .= $output->display_rubric($criteria, $options, self::DISPLAY_PREVIEW_GRADED, 'rubric');
 529          }
 530  
 531          return $rubric;
 532      }
 533  
 534      /**
 535       * Deletes the rubric definition and all the associated information
 536       */
 537      protected function delete_plugin_definition() {
 538          global $DB;
 539  
 540          // get the list of instances
 541          $instances = array_keys($DB->get_records('grading_instances', array('definitionid' => $this->definition->id), '', 'id'));
 542          // delete all fillings
 543          $DB->delete_records_list('gradingform_rubric_fillings', 'instanceid', $instances);
 544          // delete instances
 545          $DB->delete_records_list('grading_instances', 'id', $instances);
 546          // get the list of criteria records
 547          $criteria = array_keys($DB->get_records('gradingform_rubric_criteria', array('definitionid' => $this->definition->id), '', 'id'));
 548          // delete levels
 549          $DB->delete_records_list('gradingform_rubric_levels', 'criterionid', $criteria);
 550          // delete critera
 551          $DB->delete_records_list('gradingform_rubric_criteria', 'id', $criteria);
 552      }
 553  
 554      /**
 555       * If instanceid is specified and grading instance exists and it is created by this rater for
 556       * this item, this instance is returned.
 557       * If there exists a draft for this raterid+itemid, take this draft (this is the change from parent)
 558       * Otherwise new instance is created for the specified rater and itemid
 559       *
 560       * @param int $instanceid
 561       * @param int $raterid
 562       * @param int $itemid
 563       * @return gradingform_instance
 564       */
 565      public function get_or_create_instance($instanceid, $raterid, $itemid) {
 566          global $DB;
 567          if ($instanceid &&
 568                  $instance = $DB->get_record('grading_instances', array('id'  => $instanceid, 'raterid' => $raterid, 'itemid' => $itemid), '*', IGNORE_MISSING)) {
 569              return $this->get_instance($instance);
 570          }
 571          if ($itemid && $raterid) {
 572              $params = array('definitionid' => $this->definition->id, 'raterid' => $raterid, 'itemid' => $itemid);
 573              if ($rs = $DB->get_records('grading_instances', $params, 'timemodified DESC', '*', 0, 1)) {
 574                  $record = reset($rs);
 575                  $currentinstance = $this->get_current_instance($raterid, $itemid);
 576                  if ($record->status == gradingform_rubric_instance::INSTANCE_STATUS_INCOMPLETE &&
 577                          (!$currentinstance || $record->timemodified > $currentinstance->get_data('timemodified'))) {
 578                      $record->isrestored = true;
 579                      return $this->get_instance($record);
 580                  }
 581              }
 582          }
 583          return $this->create_instance($raterid, $itemid);
 584      }
 585  
 586      /**
 587       * Returns html code to be included in student's feedback.
 588       *
 589       * @param moodle_page $page
 590       * @param int $itemid
 591       * @param array $gradinginfo result of function grade_get_grades
 592       * @param string $defaultcontent default string to be returned if no active grading is found
 593       * @param boolean $cangrade whether current user has capability to grade in this context
 594       * @return string
 595       */
 596      public function render_grade($page, $itemid, $gradinginfo, $defaultcontent, $cangrade) {
 597          return $this->get_renderer($page)->display_instances($this->get_active_instances($itemid), $defaultcontent, $cangrade);
 598      }
 599  
 600      // ///// full-text search support /////////////////////////////////////////////
 601  
 602      /**
 603       * Prepare the part of the search query to append to the FROM statement
 604       *
 605       * @param string $gdid the alias of grading_definitions.id column used by the caller
 606       * @return string
 607       */
 608      public static function sql_search_from_tables($gdid) {
 609          return " LEFT JOIN {gradingform_rubric_criteria} rc ON (rc.definitionid = $gdid)
 610                   LEFT JOIN {gradingform_rubric_levels} rl ON (rl.criterionid = rc.id)";
 611      }
 612  
 613      /**
 614       * Prepare the parts of the SQL WHERE statement to search for the given token
 615       *
 616       * The returned array cosists of the list of SQL comparions and the list of
 617       * respective parameters for the comparisons. The returned chunks will be joined
 618       * with other conditions using the OR operator.
 619       *
 620       * @param string $token token to search for
 621       * @return array
 622       */
 623      public static function sql_search_where($token) {
 624          global $DB;
 625  
 626          $subsql = array();
 627          $params = array();
 628  
 629          // search in rubric criteria description
 630          $subsql[] = $DB->sql_like('rc.description', '?', false, false);
 631          $params[] = '%'.$DB->sql_like_escape($token).'%';
 632  
 633          // search in rubric levels definition
 634          $subsql[] = $DB->sql_like('rl.definition', '?', false, false);
 635          $params[] = '%'.$DB->sql_like_escape($token).'%';
 636  
 637          return array($subsql, $params);
 638      }
 639  
 640      /**
 641       * Calculates and returns the possible minimum and maximum score (in points) for this rubric
 642       *
 643       * @return array
 644       */
 645      public function get_min_max_score() {
 646          if (!$this->is_form_available()) {
 647              return null;
 648          }
 649          $returnvalue = array('minscore' => 0, 'maxscore' => 0);
 650          foreach ($this->get_definition()->rubric_criteria as $id => $criterion) {
 651              $scores = array();
 652              foreach ($criterion['levels'] as $level) {
 653                  $scores[] = $level['score'];
 654              }
 655              sort($scores);
 656              $returnvalue['minscore'] += $scores[0];
 657              $returnvalue['maxscore'] += $scores[sizeof($scores)-1];
 658          }
 659          return $returnvalue;
 660      }
 661  
 662      /**
 663       * @return array An array containing a single key/value pair with the 'rubric_criteria' external_multiple_structure.
 664       * @see gradingform_controller::get_external_definition_details()
 665       * @since Moodle 2.5
 666       */
 667      public static function get_external_definition_details() {
 668          $rubric_criteria = new external_multiple_structure(
 669              new external_single_structure(
 670                  array(
 671                     'id'   => new external_value(PARAM_INT, 'criterion id', VALUE_OPTIONAL),
 672                     'sortorder' => new external_value(PARAM_INT, 'sortorder', VALUE_OPTIONAL),
 673                     'description' => new external_value(PARAM_RAW, 'description', VALUE_OPTIONAL),
 674                     'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
 675                     'levels' => new external_multiple_structure(
 676                                     new external_single_structure(
 677                                         array(
 678                                          'id' => new external_value(PARAM_INT, 'level id', VALUE_OPTIONAL),
 679                                          'score' => new external_value(PARAM_FLOAT, 'score', VALUE_OPTIONAL),
 680                                          'definition' => new external_value(PARAM_RAW, 'definition', VALUE_OPTIONAL),
 681                                          'definitionformat' => new external_format_value('definition', VALUE_OPTIONAL)
 682                                         )
 683                                    ), 'levels', VALUE_OPTIONAL
 684                                )
 685                     )
 686                ), 'definition details', VALUE_OPTIONAL
 687          );
 688          return array('rubric_criteria' => $rubric_criteria);
 689      }
 690  
 691      /**
 692       * Returns an array that defines the structure of the rubric's filling. This function is used by
 693       * the web service function core_grading_external::get_gradingform_instances().
 694       *
 695       * @return An array containing a single key/value pair with the 'criteria' external_multiple_structure
 696       * @see gradingform_controller::get_external_instance_filling_details()
 697       * @since Moodle 2.6
 698       */
 699      public static function get_external_instance_filling_details() {
 700          $criteria = new external_multiple_structure(
 701              new external_single_structure(
 702                  array(
 703                      'id' => new external_value(PARAM_INT, 'filling id'),
 704                      'criterionid' => new external_value(PARAM_INT, 'criterion id'),
 705                      'levelid' => new external_value(PARAM_INT, 'level id', VALUE_OPTIONAL),
 706                      'remark' => new external_value(PARAM_RAW, 'remark', VALUE_OPTIONAL),
 707                      'remarkformat' => new external_format_value('remark', VALUE_OPTIONAL)
 708                  )
 709              ), 'filling', VALUE_OPTIONAL
 710          );
 711          return array ('criteria' => $criteria);
 712      }
 713  
 714  }
 715  
 716  /**
 717   * Class to manage one rubric grading instance.
 718   *
 719   * Stores information and performs actions like update, copy, validate, submit, etc.
 720   *
 721   * @package    gradingform_rubric
 722   * @copyright  2011 Marina Glancy
 723   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 724   */
 725  class gradingform_rubric_instance extends gradingform_instance {
 726  
 727      /** @var array stores the rubric, has two keys: 'criteria' and 'options' */
 728      protected $rubric;
 729  
 730      /**
 731       * Deletes this (INCOMPLETE) instance from database.
 732       */
 733      public function cancel() {
 734          global $DB;
 735          parent::cancel();
 736          $DB->delete_records('gradingform_rubric_fillings', array('instanceid' => $this->get_id()));
 737      }
 738  
 739      /**
 740       * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
 741       * the specified values)
 742       *
 743       * @param int $raterid value for raterid in the duplicate
 744       * @param int $itemid value for itemid in the duplicate
 745       * @return int id of the new instance
 746       */
 747      public function copy($raterid, $itemid) {
 748          global $DB;
 749          $instanceid = parent::copy($raterid, $itemid);
 750          $currentgrade = $this->get_rubric_filling();
 751          foreach ($currentgrade['criteria'] as $criterionid => $record) {
 752              $params = array('instanceid' => $instanceid, 'criterionid' => $criterionid,
 753                  'levelid' => $record['levelid'], 'remark' => $record['remark'], 'remarkformat' => $record['remarkformat']);
 754              $DB->insert_record('gradingform_rubric_fillings', $params);
 755          }
 756          return $instanceid;
 757      }
 758  
 759      /**
 760       * Determines whether the submitted form was empty.
 761       *
 762       * @param array $elementvalue value of element submitted from the form
 763       * @return boolean true if the form is empty
 764       */
 765      public function is_empty_form($elementvalue) {
 766          $criteria = $this->get_controller()->get_definition()->rubric_criteria;
 767  
 768          foreach ($criteria as $id => $criterion) {
 769              if (isset($elementvalue['criteria'][$id]['levelid'])
 770                      || !empty($elementvalue['criteria'][$id]['remark'])) {
 771                  return false;
 772              }
 773          }
 774          return true;
 775      }
 776  
 777      /**
 778       * Removes the attempt from the gradingform_guide_fillings table
 779       * @param array $data the attempt data
 780       */
 781      public function clear_attempt($data) {
 782          global $DB;
 783  
 784          foreach ($data['criteria'] as $criterionid => $record) {
 785              $DB->delete_records('gradingform_rubric_fillings',
 786                  array('criterionid' => $criterionid, 'instanceid' => $this->get_id()));
 787          }
 788      }
 789  
 790      /**
 791       * Validates that rubric is fully completed and contains valid grade on each criterion
 792       *
 793       * @param array $elementvalue value of element as came in form submit
 794       * @return boolean true if the form data is validated and contains no errors
 795       */
 796      public function validate_grading_element($elementvalue) {
 797          $criteria = $this->get_controller()->get_definition()->rubric_criteria;
 798          if (!isset($elementvalue['criteria']) || !is_array($elementvalue['criteria']) || sizeof($elementvalue['criteria']) < sizeof($criteria)) {
 799              return false;
 800          }
 801          foreach ($criteria as $id => $criterion) {
 802              if (!isset($elementvalue['criteria'][$id]['levelid'])
 803                      || !array_key_exists($elementvalue['criteria'][$id]['levelid'], $criterion['levels'])) {
 804                  return false;
 805              }
 806          }
 807          return true;
 808      }
 809  
 810      /**
 811       * Retrieves from DB and returns the data how this rubric was filled
 812       *
 813       * @param boolean $force whether to force DB query even if the data is cached
 814       * @return array
 815       */
 816      public function get_rubric_filling($force = false) {
 817          global $DB;
 818          if ($this->rubric === null || $force) {
 819              $records = $DB->get_records('gradingform_rubric_fillings', array('instanceid' => $this->get_id()));
 820              $this->rubric = array('criteria' => array());
 821              foreach ($records as $record) {
 822                  $this->rubric['criteria'][$record->criterionid] = (array)$record;
 823              }
 824          }
 825          return $this->rubric;
 826      }
 827  
 828      /**
 829       * Updates the instance with the data received from grading form. This function may be
 830       * called via AJAX when grading is not yet completed, so it does not change the
 831       * status of the instance.
 832       *
 833       * @param array $data
 834       */
 835      public function update($data) {
 836          global $DB;
 837          $currentgrade = $this->get_rubric_filling();
 838          parent::update($data);
 839          foreach ($data['criteria'] as $criterionid => $record) {
 840              if (!array_key_exists($criterionid, $currentgrade['criteria'])) {
 841                  $newrecord = array('instanceid' => $this->get_id(), 'criterionid' => $criterionid,
 842                      'levelid' => $record['levelid'], 'remarkformat' => FORMAT_MOODLE);
 843                  if (isset($record['remark'])) {
 844                      $newrecord['remark'] = $record['remark'];
 845                  }
 846                  $DB->insert_record('gradingform_rubric_fillings', $newrecord);
 847              } else {
 848                  $newrecord = array('id' => $currentgrade['criteria'][$criterionid]['id']);
 849                  foreach (array('levelid', 'remark'/*, 'remarkformat' */) as $key) {
 850                      // TODO MDL-31235 format is not supported yet
 851                      if (isset($record[$key]) && $currentgrade['criteria'][$criterionid][$key] != $record[$key]) {
 852                          $newrecord[$key] = $record[$key];
 853                      }
 854                  }
 855                  if (count($newrecord) > 1) {
 856                      $DB->update_record('gradingform_rubric_fillings', $newrecord);
 857                  }
 858              }
 859          }
 860          foreach ($currentgrade['criteria'] as $criterionid => $record) {
 861              if (!array_key_exists($criterionid, $data['criteria'])) {
 862                  $DB->delete_records('gradingform_rubric_fillings', array('id' => $record['id']));
 863              }
 864          }
 865          $this->get_rubric_filling(true);
 866      }
 867  
 868      /**
 869       * Calculates the grade to be pushed to the gradebook
 870       *
 871       * @return float|int the valid grade from $this->get_controller()->get_grade_range()
 872       */
 873      public function get_grade() {
 874          $grade = $this->get_rubric_filling();
 875  
 876          if (!($scores = $this->get_controller()->get_min_max_score()) || $scores['maxscore'] <= $scores['minscore']) {
 877              return -1;
 878          }
 879  
 880          $graderange = array_keys($this->get_controller()->get_grade_range());
 881          if (empty($graderange)) {
 882              return -1;
 883          }
 884          sort($graderange);
 885          $mingrade = $graderange[0];
 886          $maxgrade = $graderange[sizeof($graderange) - 1];
 887  
 888          $curscore = 0;
 889          foreach ($grade['criteria'] as $id => $record) {
 890              $curscore += $this->get_controller()->get_definition()->rubric_criteria[$id]['levels'][$record['levelid']]['score'];
 891          }
 892          $gradeoffset = ($curscore-$scores['minscore'])/($scores['maxscore']-$scores['minscore'])*($maxgrade-$mingrade);
 893          if ($this->get_controller()->get_allow_grade_decimals()) {
 894              return $gradeoffset + $mingrade;
 895          }
 896          return round($gradeoffset, 0) + $mingrade;
 897      }
 898  
 899      /**
 900       * Returns html for form element of type 'grading'.
 901       *
 902       * @param moodle_page $page
 903       * @param MoodleQuickForm_grading $gradingformelement
 904       * @return string
 905       */
 906      public function render_grading_element($page, $gradingformelement) {
 907          global $USER;
 908          if (!$gradingformelement->_flagFrozen) {
 909              $module = array('name'=>'gradingform_rubric', 'fullpath'=>'/grade/grading/form/rubric/js/rubric.js');
 910              $page->requires->js_init_call('M.gradingform_rubric.init', array(array('name' => $gradingformelement->getName())), true, $module);
 911              $mode = gradingform_rubric_controller::DISPLAY_EVAL;
 912          } else {
 913              if ($gradingformelement->_persistantFreeze) {
 914                  $mode = gradingform_rubric_controller::DISPLAY_EVAL_FROZEN;
 915              } else {
 916                  $mode = gradingform_rubric_controller::DISPLAY_REVIEW;
 917              }
 918          }
 919          $criteria = $this->get_controller()->get_definition()->rubric_criteria;
 920          $options = $this->get_controller()->get_options();
 921          $value = $gradingformelement->getValue();
 922          $html = '';
 923          if ($value === null) {
 924              $value = $this->get_rubric_filling();
 925          } else if (!$this->validate_grading_element($value)) {
 926              $html .= html_writer::tag('div', get_string('rubricnotcompleted', 'gradingform_rubric'), array('class' => 'gradingform_rubric-error'));
 927          }
 928          $currentinstance = $this->get_current_instance();
 929          if ($currentinstance && $currentinstance->get_status() == gradingform_instance::INSTANCE_STATUS_NEEDUPDATE) {
 930              $html .= html_writer::div(get_string('needregrademessage', 'gradingform_rubric'), 'gradingform_rubric-regrade',
 931                                        array('role' => 'alert'));
 932          }
 933          $haschanges = false;
 934          if ($currentinstance) {
 935              $curfilling = $currentinstance->get_rubric_filling();
 936              foreach ($curfilling['criteria'] as $criterionid => $curvalues) {
 937                  $value['criteria'][$criterionid]['savedlevelid'] = $curvalues['levelid'];
 938                  $newremark = null;
 939                  $newlevelid = null;
 940                  if (isset($value['criteria'][$criterionid]['remark'])) $newremark = $value['criteria'][$criterionid]['remark'];
 941                  if (isset($value['criteria'][$criterionid]['levelid'])) $newlevelid = $value['criteria'][$criterionid]['levelid'];
 942                  if ($newlevelid != $curvalues['levelid'] || $newremark != $curvalues['remark']) {
 943                      $haschanges = true;
 944                  }
 945              }
 946          }
 947          if ($this->get_data('isrestored') && $haschanges) {
 948              $html .= html_writer::tag('div', get_string('restoredfromdraft', 'gradingform_rubric'), array('class' => 'gradingform_rubric-restored'));
 949          }
 950          if (!empty($options['showdescriptionteacher'])) {
 951              $html .= html_writer::tag('div', $this->get_controller()->get_formatted_description(), array('class' => 'gradingform_rubric-description'));
 952          }
 953          $html .= $this->get_controller()->get_renderer($page)->display_rubric($criteria, $options, $mode, $gradingformelement->getName(), $value);
 954          return $html;
 955      }
 956  }


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1