[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/mod/workshop/form/accumulative/ -> lib.php (source)

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * This file defines a class with accumulative grading strategy logic
  20   *
  21   * @package    workshopform_accumulative
  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_accumulative_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_accumulative', 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_accumulative/$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_accumulative_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 embeded 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_accumulative', '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_accumulative_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->accumulative;  // records to be saved into {workshopform_accumulative}
 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_accumulative', $record);
 186              } else {
 187                  // exiting field
 188                  $DB->update_record('workshopform_accumulative', $record);
 189              }
 190              // re-save with correct path to embeded media files
 191              $record = file_postupdate_standard_editor($record, 'description', $this->descriptionopts,
 192                                                        $PAGE->context, 'workshopform_accumulative', 'description', $record->id);
 193              $DB->update_record('workshopform_accumulative', $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 embeded 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_accumulative', '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->{'grade__idx_'.$i}        = $grades[$dimid]->grade;
 231                      $current->{'peercomment__idx_'.$i}  = $grades[$dimid]->peercomment;
 232                  }
 233              }
 234          }
 235  
 236          // set up the required custom data common for all strategies
 237          $customdata['strategy'] = $this;
 238          $customdata['workshop'] = $this->workshop;
 239          $customdata['mode']     = $mode;
 240          $customdata['options']  = $options;
 241  
 242          // set up strategy-specific custom data
 243          $customdata['nodims']   = $nodimensions;
 244          $customdata['fields']   = $fields;
 245          $customdata['current']  = isset($current) ? $current : null;
 246          $attributes = array('class' => 'assessmentform accumulative');
 247  
 248          return new workshop_accumulative_assessment_form($actionurl, $customdata, 'post', '', $attributes, $editable);
 249      }
 250  
 251      /**
 252       * Saves the filled assessment
 253       *
 254       * This method processes data submitted using the form returned by {@link get_assessment_form()}
 255       *
 256       * @param stdClass $assessment Assessment being filled
 257       * @param stdClass $data       Raw data as returned by the assessment form
 258       * @return float|null          Raw grade (0.00000 to 100.00000) for submission as suggested by the peer
 259       */
 260      public function save_assessment(stdclass $assessment, stdclass $data) {
 261          global $DB;
 262  
 263          if (!isset($data->nodims)) {
 264              throw new coding_exception('You did not send me the number of assessment dimensions to process');
 265          }
 266          for ($i = 0; $i < $data->nodims; $i++) {
 267              $grade = new stdclass();
 268              $grade->id = $data->{'gradeid__idx_' . $i};
 269              $grade->assessmentid = $assessment->id;
 270              $grade->strategy = 'accumulative';
 271              $grade->dimensionid = $data->{'dimensionid__idx_' . $i};
 272              $grade->grade = $data->{'grade__idx_' . $i};
 273              $grade->peercomment = $data->{'peercomment__idx_' . $i};
 274              $grade->peercommentformat = FORMAT_MOODLE;
 275              if (empty($grade->id)) {
 276                  // new grade
 277                  $grade->id = $DB->insert_record('workshop_grades', $grade);
 278              } else {
 279                  // updated grade
 280                  $DB->update_record('workshop_grades', $grade);
 281              }
 282          }
 283          return $this->update_peer_grade($assessment);
 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, g.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          $sql = 'SELECT d.id, d.grade, d.weight, s.scale
 335                    FROM {workshopform_accumulative} d
 336               LEFT JOIN {scale} s ON (d.grade < 0 AND -d.grade = s.id)
 337                   WHERE d.workshopid = :workshopid';
 338          $params = array('workshopid' => $this->workshop->id);
 339          $dimrecords = $DB->get_records_sql($sql, $params);
 340          $diminfo = array();
 341          foreach ($dimrecords as $dimid => $dimrecord) {
 342              $diminfo[$dimid] = new stdclass();
 343              $diminfo[$dimid]->id = $dimid;
 344              $diminfo[$dimid]->weight = $dimrecord->weight;
 345              if ($dimrecord->grade < 0) {
 346                  // the dimension uses a scale
 347                  $diminfo[$dimid]->min = 1;
 348                  $diminfo[$dimid]->max = count(explode(',', $dimrecord->scale));
 349              } else {
 350                  // the dimension uses points
 351                  $diminfo[$dimid]->min = 0;
 352                  $diminfo[$dimid]->max = grade_floatval($dimrecord->grade);
 353              }
 354          }
 355          return $diminfo;
 356      }
 357  
 358      /**
 359       * Is a given scale used by the instance of workshop?
 360       *
 361       * @param int $scaleid id of the scale to check
 362       * @param int|null $workshopid id of workshop instance to check, checks all in case of null
 363       * @return bool
 364       */
 365      public static function scale_used($scaleid, $workshopid=null) {
 366          global $DB;
 367  
 368          $conditions['grade'] = -$scaleid;
 369          if (!is_null($workshopid)) {
 370              $conditions['workshopid'] = $workshopid;
 371          }
 372          return $DB->record_exists('workshopform_accumulative', $conditions);
 373      }
 374  
 375      /**
 376       * Delete all data related to a given workshop module instance
 377       *
 378       * @see workshop_delete_instance()
 379       * @param int $workshopid id of the workshop module instance being deleted
 380       * @return void
 381       */
 382      public static function delete_instance($workshopid) {
 383          global $DB;
 384  
 385          $DB->delete_records('workshopform_accumulative', array('workshopid' => $workshopid));
 386      }
 387  
 388      ////////////////////////////////////////////////////////////////////////////////
 389      // Internal methods                                                           //
 390      ////////////////////////////////////////////////////////////////////////////////
 391  
 392      /**
 393       * Loads the fields of the assessment form currently used in this workshop
 394       *
 395       * @return array definition of assessment dimensions
 396       */
 397      protected function load_fields() {
 398          global $DB;
 399  
 400          $sql = 'SELECT *
 401                    FROM {workshopform_accumulative}
 402                   WHERE workshopid = :workshopid
 403                   ORDER BY sort';
 404          $params = array('workshopid' => $this->workshop->id);
 405  
 406          return $DB->get_records_sql($sql, $params);
 407      }
 408  
 409      /**
 410       * Maps the dimension data from DB to the form fields
 411       *
 412       * @param array $raw Array of raw dimension records as returned by {@link load_fields()}
 413       * @return array Array of fields data to be used by the mform set_data
 414       */
 415      protected function prepare_form_fields(array $raw) {
 416  
 417          $formdata = new stdclass();
 418          $key = 0;
 419          foreach ($raw as $dimension) {
 420              $formdata->{'dimensionid__idx_' . $key}             = $dimension->id;
 421              $formdata->{'description__idx_' . $key}             = $dimension->description;
 422              $formdata->{'description__idx_' . $key.'format'}    = $dimension->descriptionformat;
 423              $formdata->{'grade__idx_' . $key}                   = $dimension->grade;
 424              $formdata->{'weight__idx_' . $key}                  = $dimension->weight;
 425              $key++;
 426          }
 427          return $formdata;
 428      }
 429  
 430      /**
 431       * Deletes dimensions and removes embedded media from its descriptions
 432       *
 433       * todo we may check that there are no assessments done using these dimensions and probably remove them
 434       *
 435       * @param array $masterids
 436       * @return void
 437       */
 438      protected function delete_dimensions(array $ids) {
 439          global $DB, $PAGE;
 440  
 441          $fs = get_file_storage();
 442          foreach ($ids as $id) {
 443              if (!empty($id)) {   // to prevent accidental removal of all files in the area
 444                  $fs->delete_area_files($PAGE->context->id, 'workshopform_accumulative', 'description', $id);
 445              }
 446          }
 447          $DB->delete_records_list('workshopform_accumulative', 'id', $ids);
 448      }
 449  
 450      /**
 451       * Prepares data returned by {@link workshop_edit_accumulative_strategy_form} so they can be saved into database
 452       *
 453       * It automatically adds some columns into every record. The sorting is
 454       * done by the order of the returned array and starts with 1.
 455       * Called internally from {@link save_edit_strategy_form()} only. Could be private but
 456       * keeping protected for unit testing purposes.
 457       *
 458       * @param stdClass $raw Raw data returned by mform
 459       * @return array Array of objects to be inserted/updated in DB
 460       */
 461      protected function prepare_database_fields(stdclass $raw) {
 462          global $PAGE;
 463  
 464          $cook               = new stdclass(); // to be returned
 465          $cook->accumulative = array();        // records to be stored in {workshopform_accumulative}
 466  
 467          for ($i = 0; $i < $raw->norepeats; $i++) {
 468              $cook->accumulative[$i]                     = new stdclass();
 469              $cook->accumulative[$i]->id                 = $raw->{'dimensionid__idx_'.$i};
 470              $cook->accumulative[$i]->workshopid         = $this->workshop->id;
 471              $cook->accumulative[$i]->sort               = $i + 1;
 472              $cook->accumulative[$i]->description_editor = $raw->{'description__idx_'.$i.'_editor'};
 473              $cook->accumulative[$i]->grade              = $raw->{'grade__idx_'.$i};
 474              $cook->accumulative[$i]->weight             = $raw->{'weight__idx_'.$i};
 475          }
 476          return $cook;
 477      }
 478  
 479      /**
 480       * Returns the list of current grades filled by the reviewer indexed by dimensionid
 481       *
 482       * @param stdClass $assessment Assessment record
 483       * @return array [int dimensionid] => stdclass workshop_grades record
 484       */
 485      protected function get_current_assessment_data(stdclass $assessment) {
 486          global $DB;
 487  
 488          if (empty($this->dimensions)) {
 489              return array();
 490          }
 491          list($dimsql, $dimparams) = $DB->get_in_or_equal(array_keys($this->dimensions), SQL_PARAMS_NAMED);
 492          // beware! the caller may rely on the returned array is indexed by dimensionid
 493          $sql = "SELECT dimensionid, wg.*
 494                    FROM {workshop_grades} wg
 495                   WHERE assessmentid = :assessmentid AND strategy= :strategy AND dimensionid $dimsql";
 496          $params = array('assessmentid' => $assessment->id, 'strategy' => 'accumulative');
 497          $params = array_merge($params, $dimparams);
 498  
 499          return $DB->get_records_sql($sql, $params);
 500      }
 501  
 502      /**
 503       * Aggregates the assessment form data and sets the grade for the submission given by the peer
 504       *
 505       * @param stdClass $assessment Assessment record
 506       * @return float|null          Raw grade (from 0.00000 to 100.00000) for submission as suggested by the peer
 507       */
 508      protected function update_peer_grade(stdclass $assessment) {
 509          $grades     = $this->get_current_assessment_data($assessment);
 510          $suggested  = $this->calculate_peer_grade($grades);
 511          if (!is_null($suggested)) {
 512              $this->workshop->set_peer_grade($assessment->id, $suggested);
 513          }
 514          return $suggested;
 515      }
 516  
 517      /**
 518       * Calculates the aggregated grade given by the reviewer
 519       *
 520       * @param array $grades Grade records as returned by {@link get_current_assessment_data}
 521       * @uses $this->dimensions
 522       * @return float|null   Raw grade (from 0.00000 to 100.00000) for submission as suggested by the peer
 523       */
 524      protected function calculate_peer_grade(array $grades) {
 525  
 526          if (empty($grades)) {
 527              return null;
 528          }
 529          $sumgrades  = 0;
 530          $sumweights = 0;
 531          foreach ($grades as $grade) {
 532              $dimension = $this->dimensions[$grade->dimensionid];
 533              if ($dimension->weight < 0) {
 534                  throw new coding_exception('Negative weights are not supported any more. Something is wrong with your data');
 535              }
 536              if (grade_floats_equal($dimension->weight, 0) or grade_floats_equal($dimension->grade, 0)) {
 537                  // does not influence the final grade
 538                  continue;
 539              }
 540              if ($dimension->grade < 0) {
 541                  // this is a scale
 542                  $scaleid    = -$dimension->grade;
 543                  $sumgrades  += $this->scale_to_grade($scaleid, $grade->grade) * $dimension->weight * 100;
 544                  $sumweights += $dimension->weight;
 545              } else {
 546                  // regular grade
 547                  $sumgrades  += ($grade->grade / $dimension->grade) * $dimension->weight * 100;
 548                  $sumweights += $dimension->weight;
 549              }
 550          }
 551  
 552          if ($sumweights === 0) {
 553              return 0;
 554          }
 555          return grade_floatval($sumgrades / $sumweights);
 556      }
 557  
 558      /**
 559       * Convert scale grade to numerical grades
 560       *
 561       * In accumulative grading strategy, scales are considered as grades from 0 to M-1, where M is the number of scale items.
 562       *
 563       * @throws coding_exception
 564       * @param string $scaleid Scale identifier
 565       * @param int    $item    Selected scale item number, numbered 1, 2, 3, ... M
 566       * @return float
 567       */
 568      protected function scale_to_grade($scaleid, $item) {
 569          global $DB;
 570  
 571          /** @var cache of numbers of scale items */
 572          static $numofscaleitems = array();
 573  
 574          if (!isset($numofscaleitems[$scaleid])) {
 575              $scale = $DB->get_field('scale', 'scale', array('id' => $scaleid), MUST_EXIST);
 576              $items = explode(',', $scale);
 577              $numofscaleitems[$scaleid] = count($items);
 578              unset($scale);
 579              unset($items);
 580          }
 581  
 582          if ($numofscaleitems[$scaleid] <= 1) {
 583              throw new coding_exception('Invalid scale definition, no scale items found');
 584          }
 585  
 586          if ($item <= 0 or $numofscaleitems[$scaleid] < $item) {
 587              throw new coding_exception('Invalid scale item number');
 588          }
 589  
 590          return ($item - 1) / ($numofscaleitems[$scaleid] - 1);
 591      }
 592  }


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