[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

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


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