Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 39 and 403]

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * This file defines a class with comments grading strategy logic
  20   *
  21   * @package    workshopform_comments
  22   * @copyright  2009 David Mudrak <david.mudrak@gmail.com>
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  require_once (__DIR__ . '/../lib.php');  // interface definition
  29  require_once($CFG->libdir . '/gradelib.php');           // to handle float vs decimal issues
  30  
  31  /**
  32   * Server workshop files
  33   *
  34   * @category files
  35   * @param stdClass $course course object
  36   * @param stdClass $cm course module object
  37   * @param stdClass $context context object
  38   * @param string $filearea file area
  39   * @param array $args extra arguments
  40   * @param bool $forcedownload whether or not force download
  41   * @param array $options additional options affecting the file serving
  42   * @return bool
  43   */
  44  function workshopform_comments_pluginfile($course, $cm, $context, $filearea, array $args, $forcedownload, array $options=array()) {
  45      global $DB;
  46  
  47      if ($context->contextlevel != CONTEXT_MODULE) {
  48          return false;
  49      }
  50  
  51      require_login($course, true, $cm);
  52  
  53      if ($filearea !== 'description') {
  54          return false;
  55      }
  56  
  57      $itemid = (int)array_shift($args); // the id of the assessment form dimension
  58      if (!$workshop = $DB->get_record('workshop', array('id' => $cm->instance))) {
  59          send_file_not_found();
  60      }
  61  
  62      if (!$dimension = $DB->get_record('workshopform_comments', array('id' => $itemid ,'workshopid' => $workshop->id))) {
  63          send_file_not_found();
  64      }
  65  
  66      // TODO now make sure the user is allowed to see the file
  67      // (media embedded into the dimension description)
  68      $fs = get_file_storage();
  69      $relativepath = implode('/', $args);
  70      $fullpath = "/$context->id/workshopform_comments/$filearea/$itemid/$relativepath";
  71      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  72          return false;
  73      }
  74  
  75      // finally send the file
  76      send_stored_file($file, 0, 0, $forcedownload, $options);
  77  }
  78  
  79  /**
  80   * Accumulative grading strategy logic.
  81   */
  82  class workshop_comments_strategy implements workshop_strategy {
  83  
  84      /** @const default number of dimensions to show */
  85      const MINDIMS = 3;
  86  
  87      /** @const number of dimensions to add */
  88      const ADDDIMS = 2;
  89  
  90      /** @var workshop the parent workshop instance */
  91      protected $workshop;
  92  
  93      /** @var array definition of the assessment form fields */
  94      protected $dimensions = null;
  95  
  96      /** @var array options for dimension description fields */
  97      protected $descriptionopts;
  98  
  99      /**
 100       * Constructor
 101       *
 102       * @param workshop $workshop The workshop instance record
 103       * @return void
 104       */
 105      public function __construct(workshop $workshop) {
 106          $this->workshop         = $workshop;
 107          $this->dimensions       = $this->load_fields();
 108          $this->descriptionopts  = array('trusttext' => true, 'subdirs' => false, 'maxfiles' => -1);
 109      }
 110  
 111      /**
 112       * Factory method returning an instance of an assessment form editor class
 113       *
 114       * @param $actionurl URL of form handler, defaults to auto detect the current url
 115       */
 116      public function get_edit_strategy_form($actionurl=null) {
 117          global $CFG;    // needed because the included files use it
 118          global $PAGE;
 119  
 120          require_once (__DIR__ . '/edit_form.php');
 121  
 122          $fields             = $this->prepare_form_fields($this->dimensions);
 123          $nodimensions       = count($this->dimensions);
 124          $norepeatsdefault   = max($nodimensions + self::ADDDIMS, self::MINDIMS);
 125          $norepeats          = optional_param('norepeats', $norepeatsdefault, PARAM_INT);    // number of dimensions
 126          $noadddims          = optional_param('noadddims', '', PARAM_ALPHA);                 // shall we add more?
 127          if ($noadddims) {
 128              $norepeats += self::ADDDIMS;
 129          }
 130  
 131          // Append editor context to editor options, giving preference to existing context.
 132          $this->descriptionopts = array_merge(array('context' => $PAGE->context), $this->descriptionopts);
 133  
 134          // prepare the embedded files
 135          for ($i = 0; $i < $nodimensions; $i++) {
 136              // prepare all editor elements
 137              $fields = file_prepare_standard_editor($fields, 'description__idx_'.$i, $this->descriptionopts,
 138                  $PAGE->context, 'workshopform_comments', 'description', $fields->{'dimensionid__idx_'.$i});
 139          }
 140  
 141          $customdata = array();
 142          $customdata['workshop'] = $this->workshop;
 143          $customdata['strategy'] = $this;
 144          $customdata['norepeats'] = $norepeats;
 145          $customdata['descriptionopts'] = $this->descriptionopts;
 146          $customdata['current']  = $fields;
 147          $attributes = array('class' => 'editstrategyform');
 148  
 149          return new workshop_edit_comments_strategy_form($actionurl, $customdata, 'post', '', $attributes);
 150      }
 151  
 152      /**
 153       * Save the assessment dimensions into database
 154       *
 155       * Saves data into the main strategy form table. If the record->id is null or zero,
 156       * new record is created. If the record->id is not empty, the existing record is updated. Records with
 157       * empty 'description' field are removed from database.
 158       * The passed data object are the raw data returned by the get_data().
 159       *
 160       * @uses $DB
 161       * @param stdClass $data Raw data returned by the dimension editor form
 162       * @return void
 163       */
 164      public function save_edit_strategy_form(stdclass $data) {
 165          global $DB, $PAGE;
 166  
 167          $workshopid = $data->workshopid;
 168          $norepeats  = $data->norepeats;
 169  
 170          $data       = $this->prepare_database_fields($data);
 171          $records    = $data->comments;  // records to be saved into {workshopform_comments}
 172          $todelete   = array();              // dimension ids to be deleted
 173  
 174          for ($i=0; $i < $norepeats; $i++) {
 175              $record = $records[$i];
 176              if (0 == strlen(trim($record->description_editor['text']))) {
 177                  if (!empty($record->id)) {
 178                      // existing record with empty description - to be deleted
 179                      $todelete[] = $record->id;
 180                  }
 181                  continue;
 182              }
 183              if (empty($record->id)) {
 184                  // new field
 185                  $record->id         = $DB->insert_record('workshopform_comments', $record);
 186              } else {
 187                  // exiting field
 188                  $DB->update_record('workshopform_comments', $record);
 189              }
 190              // re-save with correct path to embedded media files
 191              $record = file_postupdate_standard_editor($record, 'description', $this->descriptionopts,
 192                                                        $PAGE->context, 'workshopform_comments', 'description', $record->id);
 193              $DB->update_record('workshopform_comments', $record);
 194          }
 195          $this->delete_dimensions($todelete);
 196      }
 197  
 198      /**
 199       * Factory method returning an instance of an assessment form
 200       *
 201       * @param moodle_url $actionurl URL of form handler, defaults to auto detect the current url
 202       * @param string $mode          Mode to open the form in: preview/assessment
 203       * @param stdClass $assessment  The current assessment
 204       * @param bool $editable
 205       * @param array $options
 206       */
 207      public function get_assessment_form(moodle_url $actionurl=null, $mode='preview', stdclass $assessment=null, $editable=true, $options=array()) {
 208          global $CFG;    // needed because the included files use it
 209          global $PAGE;
 210          global $DB;
 211          require_once (__DIR__ . '/assessment_form.php');
 212  
 213          $fields         = $this->prepare_form_fields($this->dimensions);
 214          $nodimensions   = count($this->dimensions);
 215  
 216          // rewrite URLs to the embedded files
 217          for ($i = 0; $i < $nodimensions; $i++) {
 218              $fields->{'description__idx_'.$i} = file_rewrite_pluginfile_urls($fields->{'description__idx_'.$i},
 219                  'pluginfile.php', $PAGE->context->id, 'workshopform_comments', 'description', $fields->{'dimensionid__idx_'.$i});
 220          }
 221  
 222          if ('assessment' === $mode and !empty($assessment)) {
 223              // load the previously saved assessment data
 224              $grades = $this->get_current_assessment_data($assessment);
 225              $current = new stdclass();
 226              for ($i = 0; $i < $nodimensions; $i++) {
 227                  $dimid = $fields->{'dimensionid__idx_'.$i};
 228                  if (isset($grades[$dimid])) {
 229                      $current->{'gradeid__idx_'.$i}      = $grades[$dimid]->id;
 230                      $current->{'peercomment__idx_'.$i}  = $grades[$dimid]->peercomment;
 231                  }
 232              }
 233          }
 234  
 235          // set up the required custom data common for all strategies
 236          $customdata['strategy'] = $this;
 237          $customdata['workshop'] = $this->workshop;
 238          $customdata['mode']     = $mode;
 239          $customdata['options']  = $options;
 240  
 241          // set up strategy-specific custom data
 242          $customdata['nodims']   = $nodimensions;
 243          $customdata['fields']   = $fields;
 244          $customdata['current']  = isset($current) ? $current : null;
 245          $attributes = array('class' => 'assessmentform comments');
 246  
 247          return new workshop_comments_assessment_form($actionurl, $customdata, 'post', '', $attributes, $editable);
 248      }
 249  
 250      /**
 251       * Saves the filled assessment
 252       *
 253       * This method processes data submitted using the form returned by {@link get_assessment_form()}
 254       *
 255       * @param stdClass $assessment Assessment being filled
 256       * @param stdClass $data       Raw data as returned by the assessment form
 257       * @return float|null          Constant raw grade 100.00000 for submission as suggested by the peer
 258       */
 259      public function save_assessment(stdclass $assessment, stdclass $data) {
 260          global $DB;
 261  
 262          if (!isset($data->nodims)) {
 263              throw new coding_exception('You did not send me the number of assessment dimensions to process');
 264          }
 265          for ($i = 0; $i < $data->nodims; $i++) {
 266              $grade = new stdclass();
 267              $grade->id = $data->{'gradeid__idx_' . $i};
 268              $grade->assessmentid = $assessment->id;
 269              $grade->strategy = 'comments';
 270              $grade->dimensionid = $data->{'dimensionid__idx_' . $i};
 271              $grade->grade = 100.00000;
 272              $grade->peercomment = $data->{'peercomment__idx_' . $i};
 273              $grade->peercommentformat = FORMAT_MOODLE;
 274              if (empty($grade->id)) {
 275                  // new grade
 276                  $grade->id = $DB->insert_record('workshop_grades', $grade);
 277              } else {
 278                  // updated grade
 279                  $DB->update_record('workshop_grades', $grade);
 280              }
 281          }
 282          $this->workshop->set_peer_grade($assessment->id, 100.00000);
 283          return 100.0000;
 284      }
 285  
 286      /**
 287       * Has the assessment form been defined and is ready to be used by the reviewers?
 288       *
 289       * @return boolean
 290       */
 291      public function form_ready() {
 292          if (count($this->dimensions) > 0) {
 293              return true;
 294          }
 295          return false;
 296      }
 297  
 298      /**
 299       * @see parent::get_assessments_recordset()
 300       */
 301      public function get_assessments_recordset($restrict=null) {
 302          global $DB;
 303  
 304          $sql = 'SELECT s.id AS submissionid,
 305                         a.id AS assessmentid, a.weight AS assessmentweight, a.reviewerid, a.gradinggrade,
 306                         g.dimensionid, 100.00000 AS grade
 307                    FROM {workshop_submissions} s
 308                    JOIN {workshop_assessments} a ON (a.submissionid = s.id)
 309                    JOIN {workshop_grades} g ON (g.assessmentid = a.id AND g.strategy = :strategy)
 310                   WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
 311          $params = array('workshopid' => $this->workshop->id, 'strategy' => $this->workshop->strategy);
 312  
 313          if (is_null($restrict)) {
 314              // update all users - no more conditions
 315          } elseif (!empty($restrict)) {
 316              list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
 317              $sql .= " AND a.reviewerid $usql";
 318              $params = array_merge($params, $uparams);
 319          } else {
 320              throw new coding_exception('Empty value is not a valid parameter here');
 321          }
 322  
 323          $sql .= ' ORDER BY s.id'; // this is important for bulk processing
 324  
 325          return $DB->get_recordset_sql($sql, $params);
 326      }
 327  
 328      /**
 329       * @see parent::get_dimensions_info()
 330       */
 331      public function get_dimensions_info() {
 332          global $DB;
 333  
 334          $params = array('workshopid' => $this->workshop->id);
 335          $dimrecords = $DB->get_records('workshopform_comments', array('workshopid' => $this->workshop->id), 'sort', 'id');
 336          $diminfo = array();
 337          foreach ($dimrecords as $dimid => $dimrecord) {
 338              $diminfo[$dimid] = new stdclass();
 339              $diminfo[$dimid]->id = $dimid;
 340              $diminfo[$dimid]->weight = 1;
 341              $diminfo[$dimid]->min = 100;
 342              $diminfo[$dimid]->max = 100;
 343          }
 344          return $diminfo;
 345      }
 346  
 347      /**
 348       * Is a given scale used by the instance of workshop?
 349       *
 350       * This grading strategy does not use scales.
 351       *
 352       * @param int $scaleid id of the scale to check
 353       * @param int|null $workshopid id of workshop instance to check, checks all in case of null
 354       * @return bool
 355       */
 356      public static function scale_used($scaleid, $workshopid=null) {
 357          return false;
 358      }
 359  
 360      /**
 361       * Delete all data related to a given workshop module instance
 362       *
 363       * @see workshop_delete_instance()
 364       * @param int $workshopid id of the workshop module instance being deleted
 365       * @return void
 366       */
 367      public static function delete_instance($workshopid) {
 368          global $DB;
 369  
 370          $DB->delete_records('workshopform_comments', array('workshopid' => $workshopid));
 371      }
 372  
 373      ////////////////////////////////////////////////////////////////////////////////
 374      // Internal methods                                                           //
 375      ////////////////////////////////////////////////////////////////////////////////
 376  
 377      /**
 378       * Loads the fields of the assessment form currently used in this workshop
 379       *
 380       * @return array definition of assessment dimensions
 381       */
 382      protected function load_fields() {
 383          global $DB;
 384          return $DB->get_records('workshopform_comments', array('workshopid' => $this->workshop->id), 'sort');
 385      }
 386  
 387      /**
 388       * Maps the dimension data from DB to the form fields
 389       *
 390       * @param array $raw Array of raw dimension records as returned by {@link load_fields()}
 391       * @return array Array of fields data to be used by the mform set_data
 392       */
 393      protected function prepare_form_fields(array $raw) {
 394  
 395          $formdata = new stdclass();
 396          $key = 0;
 397          foreach ($raw as $dimension) {
 398              $formdata->{'dimensionid__idx_' . $key}             = $dimension->id;
 399              $formdata->{'description__idx_' . $key}             = $dimension->description;
 400              $formdata->{'description__idx_' . $key.'format'}    = $dimension->descriptionformat;
 401              $key++;
 402          }
 403          return $formdata;
 404      }
 405  
 406      /**
 407       * Deletes dimensions and removes embedded media from its descriptions
 408       *
 409       * todo we may check that there are no assessments done using these dimensions and probably remove them
 410       *
 411       * @param array $masterids
 412       * @return void
 413       */
 414      protected function delete_dimensions(array $ids) {
 415          global $DB, $PAGE;
 416  
 417          $fs = get_file_storage();
 418          foreach ($ids as $id) {
 419              if (!empty($id)) {   // to prevent accidental removal of all files in the area
 420                  $fs->delete_area_files($PAGE->context->id, 'workshopform_comments', 'description', $id);
 421              }
 422          }
 423          $DB->delete_records_list('workshopform_comments', 'id', $ids);
 424      }
 425  
 426      /**
 427       * Prepares data returned by {@link workshop_edit_comments_strategy_form} so they can be saved into database
 428       *
 429       * It automatically adds some columns into every record. The sorting is
 430       * done by the order of the returned array and starts with 1.
 431       * Called internally from {@link save_edit_strategy_form()} only. Could be private but
 432       * keeping protected for unit testing purposes.
 433       *
 434       * @param stdClass $raw Raw data returned by mform
 435       * @return array Array of objects to be inserted/updated in DB
 436       */
 437      protected function prepare_database_fields(stdclass $raw) {
 438          global $PAGE;
 439  
 440          $cook               = new stdclass(); // to be returned
 441          $cook->comments = array();        // records to be stored in {workshopform_comments}
 442  
 443          for ($i = 0; $i < $raw->norepeats; $i++) {
 444              $cook->comments[$i]                     = new stdclass();
 445              $cook->comments[$i]->id                 = $raw->{'dimensionid__idx_'.$i};
 446              $cook->comments[$i]->workshopid         = $this->workshop->id;
 447              $cook->comments[$i]->sort               = $i + 1;
 448              $cook->comments[$i]->description_editor = $raw->{'description__idx_'.$i.'_editor'};
 449          }
 450          return $cook;
 451      }
 452  
 453      /**
 454       * Returns the list of current grades filled by the reviewer indexed by dimensionid
 455       *
 456       * @param stdClass $assessment Assessment record
 457       * @return array [int dimensionid] => stdclass workshop_grades record
 458       */
 459      protected function get_current_assessment_data(stdclass $assessment) {
 460          global $DB;
 461  
 462          if (empty($this->dimensions)) {
 463              return array();
 464          }
 465          list($dimsql, $dimparams) = $DB->get_in_or_equal(array_keys($this->dimensions), SQL_PARAMS_NAMED);
 466          // beware! the caller may rely on the returned array is indexed by dimensionid
 467          $sql = "SELECT dimensionid, wg.*
 468                    FROM {workshop_grades} wg
 469                   WHERE assessmentid = :assessmentid AND strategy= :strategy AND dimensionid $dimsql";
 470          $params = array('assessmentid' => $assessment->id, 'strategy' => 'comments');
 471          $params = array_merge($params, $dimparams);
 472  
 473          return $DB->get_records_sql($sql, $params);
 474      }
 475  }