MDL-51088 completion: Do not require hover to confirm xpath
[moodle.git] / mod / workshop / locallib.php
blob4f98583aa540f3a372a7b61c048cdc7450ec1372
1 <?php
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.
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/>.
18 /**
19 * Library of internal classes and functions for module workshop
21 * All the workshop specific functions, needed to implement the module
22 * logic, should go to here. Instead of having bunch of function named
23 * workshop_something() taking the workshop instance as the first
24 * parameter, we use a class workshop that provides all methods.
26 * @package mod_workshop
27 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 require_once(dirname(__FILE__).'/lib.php'); // we extend this library here
34 require_once($CFG->libdir . '/gradelib.php'); // we use some rounding and comparing routines here
35 require_once($CFG->libdir . '/filelib.php');
37 /**
38 * Full-featured workshop API
40 * This wraps the workshop database record with a set of methods that are called
41 * from the module itself. The class should be initialized right after you get
42 * $workshop, $cm and $course records at the begining of the script.
44 class workshop {
46 /** error status of the {@link self::add_allocation()} */
47 const ALLOCATION_EXISTS = -9999;
49 /** the internal code of the workshop phases as are stored in the database */
50 const PHASE_SETUP = 10;
51 const PHASE_SUBMISSION = 20;
52 const PHASE_ASSESSMENT = 30;
53 const PHASE_EVALUATION = 40;
54 const PHASE_CLOSED = 50;
56 /** the internal code of the examples modes as are stored in the database */
57 const EXAMPLES_VOLUNTARY = 0;
58 const EXAMPLES_BEFORE_SUBMISSION = 1;
59 const EXAMPLES_BEFORE_ASSESSMENT = 2;
61 /** @var cm_info course module record */
62 public $cm;
64 /** @var stdclass course record */
65 public $course;
67 /** @var stdclass context object */
68 public $context;
70 /** @var int workshop instance identifier */
71 public $id;
73 /** @var string workshop activity name */
74 public $name;
76 /** @var string introduction or description of the activity */
77 public $intro;
79 /** @var int format of the {@link $intro} */
80 public $introformat;
82 /** @var string instructions for the submission phase */
83 public $instructauthors;
85 /** @var int format of the {@link $instructauthors} */
86 public $instructauthorsformat;
88 /** @var string instructions for the assessment phase */
89 public $instructreviewers;
91 /** @var int format of the {@link $instructreviewers} */
92 public $instructreviewersformat;
94 /** @var int timestamp of when the module was modified */
95 public $timemodified;
97 /** @var int current phase of workshop, for example {@link workshop::PHASE_SETUP} */
98 public $phase;
100 /** @var bool optional feature: students practise evaluating on example submissions from teacher */
101 public $useexamples;
103 /** @var bool optional feature: students perform peer assessment of others' work (deprecated, consider always enabled) */
104 public $usepeerassessment;
106 /** @var bool optional feature: students perform self assessment of their own work */
107 public $useselfassessment;
109 /** @var float number (10, 5) unsigned, the maximum grade for submission */
110 public $grade;
112 /** @var float number (10, 5) unsigned, the maximum grade for assessment */
113 public $gradinggrade;
115 /** @var string type of the current grading strategy used in this workshop, for example 'accumulative' */
116 public $strategy;
118 /** @var string the name of the evaluation plugin to use for grading grades calculation */
119 public $evaluation;
121 /** @var int number of digits that should be shown after the decimal point when displaying grades */
122 public $gradedecimals;
124 /** @var int number of allowed submission attachments and the files embedded into submission */
125 public $nattachments;
127 /** @var bool allow submitting the work after the deadline */
128 public $latesubmissions;
130 /** @var int maximum size of the one attached file in bytes */
131 public $maxbytes;
133 /** @var int mode of example submissions support, for example {@link workshop::EXAMPLES_VOLUNTARY} */
134 public $examplesmode;
136 /** @var int if greater than 0 then the submission is not allowed before this timestamp */
137 public $submissionstart;
139 /** @var int if greater than 0 then the submission is not allowed after this timestamp */
140 public $submissionend;
142 /** @var int if greater than 0 then the peer assessment is not allowed before this timestamp */
143 public $assessmentstart;
145 /** @var int if greater than 0 then the peer assessment is not allowed after this timestamp */
146 public $assessmentend;
148 /** @var bool automatically switch to the assessment phase after the submissions deadline */
149 public $phaseswitchassessment;
151 /** @var string conclusion text to be displayed at the end of the activity */
152 public $conclusion;
154 /** @var int format of the conclusion text */
155 public $conclusionformat;
157 /** @var int the mode of the overall feedback */
158 public $overallfeedbackmode;
160 /** @var int maximum number of overall feedback attachments */
161 public $overallfeedbackfiles;
163 /** @var int maximum size of one file attached to the overall feedback */
164 public $overallfeedbackmaxbytes;
167 * @var workshop_strategy grading strategy instance
168 * Do not use directly, get the instance using {@link workshop::grading_strategy_instance()}
170 protected $strategyinstance = null;
173 * @var workshop_evaluation grading evaluation instance
174 * Do not use directly, get the instance using {@link workshop::grading_evaluation_instance()}
176 protected $evaluationinstance = null;
179 * Initializes the workshop API instance using the data from DB
181 * Makes deep copy of all passed records properties.
183 * For unit testing only, $cm and $course may be set to null. This is so that
184 * you can test without having any real database objects if you like. Not all
185 * functions will work in this situation.
187 * @param stdClass $dbrecord Workshop instance data from {workshop} table
188 * @param stdClass|cm_info $cm Course module record
189 * @param stdClass $course Course record from {course} table
190 * @param stdClass $context The context of the workshop instance
192 public function __construct(stdclass $dbrecord, $cm, $course, stdclass $context=null) {
193 foreach ($dbrecord as $field => $value) {
194 if (property_exists('workshop', $field)) {
195 $this->{$field} = $value;
198 if (is_null($cm) || is_null($course)) {
199 throw new coding_exception('Must specify $cm and $course');
201 $this->course = $course;
202 if ($cm instanceof cm_info) {
203 $this->cm = $cm;
204 } else {
205 $modinfo = get_fast_modinfo($course);
206 $this->cm = $modinfo->get_cm($cm->id);
208 if (is_null($context)) {
209 $this->context = context_module::instance($this->cm->id);
210 } else {
211 $this->context = $context;
215 ////////////////////////////////////////////////////////////////////////////////
216 // Static methods //
217 ////////////////////////////////////////////////////////////////////////////////
220 * Return list of available allocation methods
222 * @return array Array ['string' => 'string'] of localized allocation method names
224 public static function installed_allocators() {
225 $installed = core_component::get_plugin_list('workshopallocation');
226 $forms = array();
227 foreach ($installed as $allocation => $allocationpath) {
228 if (file_exists($allocationpath . '/lib.php')) {
229 $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation);
232 // usability - make sure that manual allocation appears the first
233 if (isset($forms['manual'])) {
234 $m = array('manual' => $forms['manual']);
235 unset($forms['manual']);
236 $forms = array_merge($m, $forms);
238 return $forms;
242 * Returns an array of options for the editors that are used for submitting and assessing instructions
244 * @param stdClass $context
245 * @uses EDITOR_UNLIMITED_FILES hard-coded value for the 'maxfiles' option
246 * @return array
248 public static function instruction_editors_options(stdclass $context) {
249 return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => -1,
250 'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0);
254 * Given the percent and the total, returns the number
256 * @param float $percent from 0 to 100
257 * @param float $total the 100% value
258 * @return float
260 public static function percent_to_value($percent, $total) {
261 if ($percent < 0 or $percent > 100) {
262 throw new coding_exception('The percent can not be less than 0 or higher than 100');
265 return $total * $percent / 100;
269 * Returns an array of numeric values that can be used as maximum grades
271 * @return array Array of integers
273 public static function available_maxgrades_list() {
274 $grades = array();
275 for ($i=100; $i>=0; $i--) {
276 $grades[$i] = $i;
278 return $grades;
282 * Returns the localized list of supported examples modes
284 * @return array
286 public static function available_example_modes_list() {
287 $options = array();
288 $options[self::EXAMPLES_VOLUNTARY] = get_string('examplesvoluntary', 'workshop');
289 $options[self::EXAMPLES_BEFORE_SUBMISSION] = get_string('examplesbeforesubmission', 'workshop');
290 $options[self::EXAMPLES_BEFORE_ASSESSMENT] = get_string('examplesbeforeassessment', 'workshop');
291 return $options;
295 * Returns the list of available grading strategy methods
297 * @return array ['string' => 'string']
299 public static function available_strategies_list() {
300 $installed = core_component::get_plugin_list('workshopform');
301 $forms = array();
302 foreach ($installed as $strategy => $strategypath) {
303 if (file_exists($strategypath . '/lib.php')) {
304 $forms[$strategy] = get_string('pluginname', 'workshopform_' . $strategy);
307 return $forms;
311 * Returns the list of available grading evaluation methods
313 * @return array of (string)name => (string)localized title
315 public static function available_evaluators_list() {
316 $evals = array();
317 foreach (core_component::get_plugin_list_with_file('workshopeval', 'lib.php', false) as $eval => $evalpath) {
318 $evals[$eval] = get_string('pluginname', 'workshopeval_' . $eval);
320 return $evals;
324 * Return an array of possible values of assessment dimension weight
326 * @return array of integers 0, 1, 2, ..., 16
328 public static function available_dimension_weights_list() {
329 $weights = array();
330 for ($i=16; $i>=0; $i--) {
331 $weights[$i] = $i;
333 return $weights;
337 * Return an array of possible values of assessment weight
339 * Note there is no real reason why the maximum value here is 16. It used to be 10 in
340 * workshop 1.x and I just decided to use the same number as in the maximum weight of
341 * a single assessment dimension.
342 * The value looks reasonable, though. Teachers who would want to assign themselves
343 * higher weight probably do not want peer assessment really...
345 * @return array of integers 0, 1, 2, ..., 16
347 public static function available_assessment_weights_list() {
348 $weights = array();
349 for ($i=16; $i>=0; $i--) {
350 $weights[$i] = $i;
352 return $weights;
356 * Helper function returning the greatest common divisor
358 * @param int $a
359 * @param int $b
360 * @return int
362 public static function gcd($a, $b) {
363 return ($b == 0) ? ($a):(self::gcd($b, $a % $b));
367 * Helper function returning the least common multiple
369 * @param int $a
370 * @param int $b
371 * @return int
373 public static function lcm($a, $b) {
374 return ($a / self::gcd($a,$b)) * $b;
378 * Returns an object suitable for strings containing dates/times
380 * The returned object contains properties date, datefullshort, datetime, ... containing the given
381 * timestamp formatted using strftimedate, strftimedatefullshort, strftimedatetime, ... from the
382 * current lang's langconfig.php
383 * This allows translators and administrators customize the date/time format.
385 * @param int $timestamp the timestamp in UTC
386 * @return stdclass
388 public static function timestamp_formats($timestamp) {
389 $formats = array('date', 'datefullshort', 'dateshort', 'datetime',
390 'datetimeshort', 'daydate', 'daydatetime', 'dayshort', 'daytime',
391 'monthyear', 'recent', 'recentfull', 'time');
392 $a = new stdclass();
393 foreach ($formats as $format) {
394 $a->{$format} = userdate($timestamp, get_string('strftime'.$format, 'langconfig'));
396 $day = userdate($timestamp, '%Y%m%d', 99, false);
397 $today = userdate(time(), '%Y%m%d', 99, false);
398 $tomorrow = userdate(time() + DAYSECS, '%Y%m%d', 99, false);
399 $yesterday = userdate(time() - DAYSECS, '%Y%m%d', 99, false);
400 $distance = (int)round(abs(time() - $timestamp) / DAYSECS);
401 if ($day == $today) {
402 $a->distanceday = get_string('daystoday', 'workshop');
403 } elseif ($day == $yesterday) {
404 $a->distanceday = get_string('daysyesterday', 'workshop');
405 } elseif ($day < $today) {
406 $a->distanceday = get_string('daysago', 'workshop', $distance);
407 } elseif ($day == $tomorrow) {
408 $a->distanceday = get_string('daystomorrow', 'workshop');
409 } elseif ($day > $today) {
410 $a->distanceday = get_string('daysleft', 'workshop', $distance);
412 return $a;
415 ////////////////////////////////////////////////////////////////////////////////
416 // Workshop API //
417 ////////////////////////////////////////////////////////////////////////////////
420 * Fetches all enrolled users with the capability mod/workshop:submit in the current workshop
422 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
423 * Only users with the active enrolment are returned.
425 * @param bool $musthavesubmission if true, return only users who have already submitted
426 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
427 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
428 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
429 * @return array array[userid] => stdClass
431 public function get_potential_authors($musthavesubmission=true, $groupid=0, $limitfrom=0, $limitnum=0) {
432 global $DB;
434 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
436 if (empty($sql)) {
437 return array();
440 list($sort, $sortparams) = users_order_by_sql('tmp');
441 $sql = "SELECT *
442 FROM ($sql) tmp
443 ORDER BY $sort";
445 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
449 * Returns the total number of users that would be fetched by {@link self::get_potential_authors()}
451 * @param bool $musthavesubmission if true, count only users who have already submitted
452 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
453 * @return int
455 public function count_potential_authors($musthavesubmission=true, $groupid=0) {
456 global $DB;
458 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
460 if (empty($sql)) {
461 return 0;
464 $sql = "SELECT COUNT(*)
465 FROM ($sql) tmp";
467 return $DB->count_records_sql($sql, $params);
471 * Fetches all enrolled users with the capability mod/workshop:peerassess in the current workshop
473 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
474 * Only users with the active enrolment are returned.
476 * @param bool $musthavesubmission if true, return only users who have already submitted
477 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
478 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
479 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
480 * @return array array[userid] => stdClass
482 public function get_potential_reviewers($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
483 global $DB;
485 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
487 if (empty($sql)) {
488 return array();
491 list($sort, $sortparams) = users_order_by_sql('tmp');
492 $sql = "SELECT *
493 FROM ($sql) tmp
494 ORDER BY $sort";
496 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
500 * Returns the total number of users that would be fetched by {@link self::get_potential_reviewers()}
502 * @param bool $musthavesubmission if true, count only users who have already submitted
503 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
504 * @return int
506 public function count_potential_reviewers($musthavesubmission=false, $groupid=0) {
507 global $DB;
509 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
511 if (empty($sql)) {
512 return 0;
515 $sql = "SELECT COUNT(*)
516 FROM ($sql) tmp";
518 return $DB->count_records_sql($sql, $params);
522 * Fetches all enrolled users that are authors or reviewers (or both) in the current workshop
524 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
525 * Only users with the active enrolment are returned.
527 * @see self::get_potential_authors()
528 * @see self::get_potential_reviewers()
529 * @param bool $musthavesubmission if true, return only users who have already submitted
530 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
531 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
532 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
533 * @return array array[userid] => stdClass
535 public function get_participants($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
536 global $DB;
538 list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
540 if (empty($sql)) {
541 return array();
544 list($sort, $sortparams) = users_order_by_sql('tmp');
545 $sql = "SELECT *
546 FROM ($sql) tmp
547 ORDER BY $sort";
549 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
553 * Returns the total number of records that would be returned by {@link self::get_participants()}
555 * @param bool $musthavesubmission if true, return only users who have already submitted
556 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
557 * @return int
559 public function count_participants($musthavesubmission=false, $groupid=0) {
560 global $DB;
562 list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
564 if (empty($sql)) {
565 return 0;
568 $sql = "SELECT COUNT(*)
569 FROM ($sql) tmp";
571 return $DB->count_records_sql($sql, $params);
575 * Checks if the given user is an actively enrolled participant in the workshop
577 * @param int $userid, defaults to the current $USER
578 * @return boolean
580 public function is_participant($userid=null) {
581 global $USER, $DB;
583 if (is_null($userid)) {
584 $userid = $USER->id;
587 list($sql, $params) = $this->get_participants_sql();
589 if (empty($sql)) {
590 return false;
593 $sql = "SELECT COUNT(*)
594 FROM {user} uxx
595 JOIN ({$sql}) pxx ON uxx.id = pxx.id
596 WHERE uxx.id = :uxxid";
597 $params['uxxid'] = $userid;
599 if ($DB->count_records_sql($sql, $params)) {
600 return true;
603 return false;
607 * Groups the given users by the group membership
609 * This takes the module grouping settings into account. If a grouping is
610 * set, returns only groups withing the course module grouping. Always
611 * returns group [0] with all the given users.
613 * @param array $users array[userid] => stdclass{->id ->lastname ->firstname}
614 * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname}
616 public function get_grouped($users) {
617 global $DB;
618 global $CFG;
620 $grouped = array(); // grouped users to be returned
621 if (empty($users)) {
622 return $grouped;
624 if ($this->cm->groupingid) {
625 // Group workshop set to specified grouping - only consider groups
626 // within this grouping, and leave out users who aren't members of
627 // this grouping.
628 $groupingid = $this->cm->groupingid;
629 // All users that are members of at least one group will be
630 // added into a virtual group id 0
631 $grouped[0] = array();
632 } else {
633 $groupingid = 0;
634 // there is no need to be member of a group so $grouped[0] will contain
635 // all users
636 $grouped[0] = $users;
638 $gmemberships = groups_get_all_groups($this->cm->course, array_keys($users), $groupingid,
639 'gm.id,gm.groupid,gm.userid');
640 foreach ($gmemberships as $gmembership) {
641 if (!isset($grouped[$gmembership->groupid])) {
642 $grouped[$gmembership->groupid] = array();
644 $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid];
645 $grouped[0][$gmembership->userid] = $users[$gmembership->userid];
647 return $grouped;
651 * Returns the list of all allocations (i.e. assigned assessments) in the workshop
653 * Assessments of example submissions are ignored
655 * @return array
657 public function get_allocations() {
658 global $DB;
660 $sql = 'SELECT a.id, a.submissionid, a.reviewerid, s.authorid
661 FROM {workshop_assessments} a
662 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
663 WHERE s.example = 0 AND s.workshopid = :workshopid';
664 $params = array('workshopid' => $this->id);
666 return $DB->get_records_sql($sql, $params);
670 * Returns the total number of records that would be returned by {@link self::get_submissions()}
672 * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
673 * @param int $groupid If non-zero, return only submissions by authors in the specified group
674 * @return int number of records
676 public function count_submissions($authorid='all', $groupid=0) {
677 global $DB;
679 $params = array('workshopid' => $this->id);
680 $sql = "SELECT COUNT(s.id)
681 FROM {workshop_submissions} s
682 JOIN {user} u ON (s.authorid = u.id)";
683 if ($groupid) {
684 $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
685 $params['groupid'] = $groupid;
687 $sql .= " WHERE s.example = 0 AND s.workshopid = :workshopid";
689 if ('all' === $authorid) {
690 // no additional conditions
691 } elseif (!empty($authorid)) {
692 list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
693 $sql .= " AND authorid $usql";
694 $params = array_merge($params, $uparams);
695 } else {
696 // $authorid is empty
697 return 0;
700 return $DB->count_records_sql($sql, $params);
705 * Returns submissions from this workshop
707 * Fetches data from {workshop_submissions} and adds some useful information from other
708 * tables. Does not return textual fields to prevent possible memory lack issues.
710 * @see self::count_submissions()
711 * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
712 * @param int $groupid If non-zero, return only submissions by authors in the specified group
713 * @param int $limitfrom Return a subset of records, starting at this point (optional)
714 * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
715 * @return array of records or an empty array
717 public function get_submissions($authorid='all', $groupid=0, $limitfrom=0, $limitnum=0) {
718 global $DB;
720 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
721 $gradeoverbyfields = user_picture::fields('t', null, 'gradeoverbyx', 'over');
722 $params = array('workshopid' => $this->id);
723 $sql = "SELECT s.id, s.workshopid, s.example, s.authorid, s.timecreated, s.timemodified,
724 s.title, s.grade, s.gradeover, s.gradeoverby, s.published,
725 $authorfields, $gradeoverbyfields
726 FROM {workshop_submissions} s
727 JOIN {user} u ON (s.authorid = u.id)";
728 if ($groupid) {
729 $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
730 $params['groupid'] = $groupid;
732 $sql .= " LEFT JOIN {user} t ON (s.gradeoverby = t.id)
733 WHERE s.example = 0 AND s.workshopid = :workshopid";
735 if ('all' === $authorid) {
736 // no additional conditions
737 } elseif (!empty($authorid)) {
738 list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
739 $sql .= " AND authorid $usql";
740 $params = array_merge($params, $uparams);
741 } else {
742 // $authorid is empty
743 return array();
745 list($sort, $sortparams) = users_order_by_sql('u');
746 $sql .= " ORDER BY $sort";
748 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
752 * Returns a submission record with the author's data
754 * @param int $id submission id
755 * @return stdclass
757 public function get_submission_by_id($id) {
758 global $DB;
760 // we intentionally check the workshopid here, too, so the workshop can't touch submissions
761 // from other instances
762 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
763 $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
764 $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
765 FROM {workshop_submissions} s
766 INNER JOIN {user} u ON (s.authorid = u.id)
767 LEFT JOIN {user} g ON (s.gradeoverby = g.id)
768 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.id = :id";
769 $params = array('workshopid' => $this->id, 'id' => $id);
770 return $DB->get_record_sql($sql, $params, MUST_EXIST);
774 * Returns a submission submitted by the given author
776 * @param int $id author id
777 * @return stdclass|false
779 public function get_submission_by_author($authorid) {
780 global $DB;
782 if (empty($authorid)) {
783 return false;
785 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
786 $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
787 $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
788 FROM {workshop_submissions} s
789 INNER JOIN {user} u ON (s.authorid = u.id)
790 LEFT JOIN {user} g ON (s.gradeoverby = g.id)
791 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.authorid = :authorid";
792 $params = array('workshopid' => $this->id, 'authorid' => $authorid);
793 return $DB->get_record_sql($sql, $params);
797 * Returns published submissions with their authors data
799 * @return array of stdclass
801 public function get_published_submissions($orderby='finalgrade DESC') {
802 global $DB;
804 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
805 $sql = "SELECT s.id, s.authorid, s.timecreated, s.timemodified,
806 s.title, s.grade, s.gradeover, COALESCE(s.gradeover,s.grade) AS finalgrade,
807 $authorfields
808 FROM {workshop_submissions} s
809 INNER JOIN {user} u ON (s.authorid = u.id)
810 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.published = 1
811 ORDER BY $orderby";
812 $params = array('workshopid' => $this->id);
813 return $DB->get_records_sql($sql, $params);
817 * Returns full record of the given example submission
819 * @param int $id example submission od
820 * @return object
822 public function get_example_by_id($id) {
823 global $DB;
824 return $DB->get_record('workshop_submissions',
825 array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST);
829 * Returns the list of example submissions in this workshop with reference assessments attached
831 * @return array of objects or an empty array
832 * @see workshop::prepare_example_summary()
834 public function get_examples_for_manager() {
835 global $DB;
837 $sql = 'SELECT s.id, s.title,
838 a.id AS assessmentid, a.grade, a.gradinggrade
839 FROM {workshop_submissions} s
840 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.weight = 1)
841 WHERE s.example = 1 AND s.workshopid = :workshopid
842 ORDER BY s.title';
843 return $DB->get_records_sql($sql, array('workshopid' => $this->id));
847 * Returns the list of all example submissions in this workshop with the information of assessments done by the given user
849 * @param int $reviewerid user id
850 * @return array of objects, indexed by example submission id
851 * @see workshop::prepare_example_summary()
853 public function get_examples_for_reviewer($reviewerid) {
854 global $DB;
856 if (empty($reviewerid)) {
857 return false;
859 $sql = 'SELECT s.id, s.title,
860 a.id AS assessmentid, a.grade, a.gradinggrade
861 FROM {workshop_submissions} s
862 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.reviewerid = :reviewerid AND a.weight = 0)
863 WHERE s.example = 1 AND s.workshopid = :workshopid
864 ORDER BY s.title';
865 return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid));
869 * Prepares renderable submission component
871 * @param stdClass $record required by {@see workshop_submission}
872 * @param bool $showauthor show the author-related information
873 * @return workshop_submission
875 public function prepare_submission(stdClass $record, $showauthor = false) {
877 $submission = new workshop_submission($this, $record, $showauthor);
878 $submission->url = $this->submission_url($record->id);
880 return $submission;
884 * Prepares renderable submission summary component
886 * @param stdClass $record required by {@see workshop_submission_summary}
887 * @param bool $showauthor show the author-related information
888 * @return workshop_submission_summary
890 public function prepare_submission_summary(stdClass $record, $showauthor = false) {
892 $summary = new workshop_submission_summary($this, $record, $showauthor);
893 $summary->url = $this->submission_url($record->id);
895 return $summary;
899 * Prepares renderable example submission component
901 * @param stdClass $record required by {@see workshop_example_submission}
902 * @return workshop_example_submission
904 public function prepare_example_submission(stdClass $record) {
906 $example = new workshop_example_submission($this, $record);
908 return $example;
912 * Prepares renderable example submission summary component
914 * If the example is editable, the caller must set the 'editable' flag explicitly.
916 * @param stdClass $example as returned by {@link workshop::get_examples_for_manager()} or {@link workshop::get_examples_for_reviewer()}
917 * @return workshop_example_submission_summary to be rendered
919 public function prepare_example_summary(stdClass $example) {
921 $summary = new workshop_example_submission_summary($this, $example);
923 if (is_null($example->grade)) {
924 $summary->status = 'notgraded';
925 $summary->assesslabel = get_string('assess', 'workshop');
926 } else {
927 $summary->status = 'graded';
928 $summary->assesslabel = get_string('reassess', 'workshop');
931 $summary->gradeinfo = new stdclass();
932 $summary->gradeinfo->received = $this->real_grade($example->grade);
933 $summary->gradeinfo->max = $this->real_grade(100);
935 $summary->url = new moodle_url($this->exsubmission_url($example->id));
936 $summary->editurl = new moodle_url($this->exsubmission_url($example->id), array('edit' => 'on'));
937 $summary->assessurl = new moodle_url($this->exsubmission_url($example->id), array('assess' => 'on', 'sesskey' => sesskey()));
939 return $summary;
943 * Prepares renderable assessment component
945 * The $options array supports the following keys:
946 * showauthor - should the author user info be available for the renderer
947 * showreviewer - should the reviewer user info be available for the renderer
948 * showform - show the assessment form if it is available
949 * showweight - should the assessment weight be available for the renderer
951 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
952 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
953 * @param array $options
954 * @return workshop_assessment
956 public function prepare_assessment(stdClass $record, $form, array $options = array()) {
958 $assessment = new workshop_assessment($this, $record, $options);
959 $assessment->url = $this->assess_url($record->id);
960 $assessment->maxgrade = $this->real_grade(100);
962 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
963 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
966 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
967 $assessment->form = $form;
970 if (empty($options['showweight'])) {
971 $assessment->weight = null;
974 if (!is_null($record->grade)) {
975 $assessment->realgrade = $this->real_grade($record->grade);
978 return $assessment;
982 * Prepares renderable example submission's assessment component
984 * The $options array supports the following keys:
985 * showauthor - should the author user info be available for the renderer
986 * showreviewer - should the reviewer user info be available for the renderer
987 * showform - show the assessment form if it is available
989 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
990 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
991 * @param array $options
992 * @return workshop_example_assessment
994 public function prepare_example_assessment(stdClass $record, $form = null, array $options = array()) {
996 $assessment = new workshop_example_assessment($this, $record, $options);
997 $assessment->url = $this->exassess_url($record->id);
998 $assessment->maxgrade = $this->real_grade(100);
1000 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1001 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1004 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1005 $assessment->form = $form;
1008 if (!is_null($record->grade)) {
1009 $assessment->realgrade = $this->real_grade($record->grade);
1012 $assessment->weight = null;
1014 return $assessment;
1018 * Prepares renderable example submission's reference assessment component
1020 * The $options array supports the following keys:
1021 * showauthor - should the author user info be available for the renderer
1022 * showreviewer - should the reviewer user info be available for the renderer
1023 * showform - show the assessment form if it is available
1025 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1026 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1027 * @param array $options
1028 * @return workshop_example_reference_assessment
1030 public function prepare_example_reference_assessment(stdClass $record, $form = null, array $options = array()) {
1032 $assessment = new workshop_example_reference_assessment($this, $record, $options);
1033 $assessment->maxgrade = $this->real_grade(100);
1035 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1036 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1039 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1040 $assessment->form = $form;
1043 if (!is_null($record->grade)) {
1044 $assessment->realgrade = $this->real_grade($record->grade);
1047 $assessment->weight = null;
1049 return $assessment;
1053 * Removes the submission and all relevant data
1055 * @param stdClass $submission record to delete
1056 * @return void
1058 public function delete_submission(stdclass $submission) {
1059 global $DB;
1061 $assessments = $DB->get_records('workshop_assessments', array('submissionid' => $submission->id), '', 'id');
1062 $this->delete_assessment(array_keys($assessments));
1064 $fs = get_file_storage();
1065 $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_content', $submission->id);
1066 $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
1068 $DB->delete_records('workshop_submissions', array('id' => $submission->id));
1072 * Returns the list of all assessments in the workshop with some data added
1074 * Fetches data from {workshop_assessments} and adds some useful information from other
1075 * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory
1076 * lack issues.
1078 * @return array [assessmentid] => assessment stdclass
1080 public function get_all_assessments() {
1081 global $DB;
1083 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1084 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1085 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1086 list($sort, $params) = users_order_by_sql('reviewer');
1087 $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified,
1088 a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby,
1089 $reviewerfields, $authorfields, $overbyfields,
1090 s.title
1091 FROM {workshop_assessments} a
1092 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1093 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1094 INNER JOIN {user} author ON (s.authorid = author.id)
1095 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1096 WHERE s.workshopid = :workshopid AND s.example = 0
1097 ORDER BY $sort";
1098 $params['workshopid'] = $this->id;
1100 return $DB->get_records_sql($sql, $params);
1104 * Get the complete information about the given assessment
1106 * @param int $id Assessment ID
1107 * @return stdclass
1109 public function get_assessment_by_id($id) {
1110 global $DB;
1112 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1113 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1114 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1115 $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1116 FROM {workshop_assessments} a
1117 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1118 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1119 INNER JOIN {user} author ON (s.authorid = author.id)
1120 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1121 WHERE a.id = :id AND s.workshopid = :workshopid";
1122 $params = array('id' => $id, 'workshopid' => $this->id);
1124 return $DB->get_record_sql($sql, $params, MUST_EXIST);
1128 * Get the complete information about the user's assessment of the given submission
1130 * @param int $sid submission ID
1131 * @param int $uid user ID of the reviewer
1132 * @return false|stdclass false if not found, stdclass otherwise
1134 public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
1135 global $DB;
1137 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1138 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1139 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1140 $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1141 FROM {workshop_assessments} a
1142 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1143 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1144 INNER JOIN {user} author ON (s.authorid = author.id)
1145 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1146 WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid";
1147 $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id);
1149 return $DB->get_record_sql($sql, $params, IGNORE_MISSING);
1153 * Get the complete information about all assessments of the given submission
1155 * @param int $submissionid
1156 * @return array
1158 public function get_assessments_of_submission($submissionid) {
1159 global $DB;
1161 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1162 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1163 list($sort, $params) = users_order_by_sql('reviewer');
1164 $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields
1165 FROM {workshop_assessments} a
1166 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1167 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1168 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1169 WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid
1170 ORDER BY $sort";
1171 $params['submissionid'] = $submissionid;
1172 $params['workshopid'] = $this->id;
1174 return $DB->get_records_sql($sql, $params);
1178 * Get the complete information about all assessments allocated to the given reviewer
1180 * @param int $reviewerid
1181 * @return array
1183 public function get_assessments_by_reviewer($reviewerid) {
1184 global $DB;
1186 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1187 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1188 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1189 $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields,
1190 s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated,
1191 s.timemodified AS submissionmodified
1192 FROM {workshop_assessments} a
1193 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1194 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1195 INNER JOIN {user} author ON (s.authorid = author.id)
1196 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1197 WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid";
1198 $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id);
1200 return $DB->get_records_sql($sql, $params);
1204 * Get allocated assessments not graded yet by the given reviewer
1206 * @see self::get_assessments_by_reviewer()
1207 * @param int $reviewerid the reviewer id
1208 * @param null|int|array $exclude optional assessment id (or list of them) to be excluded
1209 * @return array
1211 public function get_pending_assessments_by_reviewer($reviewerid, $exclude = null) {
1213 $assessments = $this->get_assessments_by_reviewer($reviewerid);
1215 foreach ($assessments as $id => $assessment) {
1216 if (!is_null($assessment->grade)) {
1217 unset($assessments[$id]);
1218 continue;
1220 if (!empty($exclude)) {
1221 if (is_array($exclude) and in_array($id, $exclude)) {
1222 unset($assessments[$id]);
1223 continue;
1224 } else if ($id == $exclude) {
1225 unset($assessments[$id]);
1226 continue;
1231 return $assessments;
1235 * Allocate a submission to a user for review
1237 * @param stdClass $submission Submission object with at least id property
1238 * @param int $reviewerid User ID
1239 * @param int $weight of the new assessment, from 0 to 16
1240 * @param bool $bulk repeated inserts into DB expected
1241 * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists
1243 public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
1244 global $DB;
1246 if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
1247 return self::ALLOCATION_EXISTS;
1250 $weight = (int)$weight;
1251 if ($weight < 0) {
1252 $weight = 0;
1254 if ($weight > 16) {
1255 $weight = 16;
1258 $now = time();
1259 $assessment = new stdclass();
1260 $assessment->submissionid = $submission->id;
1261 $assessment->reviewerid = $reviewerid;
1262 $assessment->timecreated = $now; // do not set timemodified here
1263 $assessment->weight = $weight;
1264 $assessment->feedbackauthorformat = editors_get_preferred_format();
1265 $assessment->feedbackreviewerformat = editors_get_preferred_format();
1267 return $DB->insert_record('workshop_assessments', $assessment, true, $bulk);
1271 * Delete assessment record or records.
1273 * Removes associated records from the workshop_grades table, too.
1275 * @param int|array $id assessment id or array of assessments ids
1276 * @todo Give grading strategy plugins a chance to clean up their data, too.
1277 * @return bool true
1279 public function delete_assessment($id) {
1280 global $DB;
1282 if (empty($id)) {
1283 return true;
1286 $fs = get_file_storage();
1288 if (is_array($id)) {
1289 $DB->delete_records_list('workshop_grades', 'assessmentid', $id);
1290 foreach ($id as $itemid) {
1291 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $itemid);
1292 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $itemid);
1294 $DB->delete_records_list('workshop_assessments', 'id', $id);
1296 } else {
1297 $DB->delete_records('workshop_grades', array('assessmentid' => $id));
1298 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $id);
1299 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $id);
1300 $DB->delete_records('workshop_assessments', array('id' => $id));
1303 return true;
1307 * Returns instance of grading strategy class
1309 * @return stdclass Instance of a grading strategy
1311 public function grading_strategy_instance() {
1312 global $CFG; // because we require other libs here
1314 if (is_null($this->strategyinstance)) {
1315 $strategylib = dirname(__FILE__) . '/form/' . $this->strategy . '/lib.php';
1316 if (is_readable($strategylib)) {
1317 require_once($strategylib);
1318 } else {
1319 throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
1321 $classname = 'workshop_' . $this->strategy . '_strategy';
1322 $this->strategyinstance = new $classname($this);
1323 if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) {
1324 throw new coding_exception($classname . ' does not implement workshop_strategy interface');
1327 return $this->strategyinstance;
1331 * Sets the current evaluation method to the given plugin.
1333 * @param string $method the name of the workshopeval subplugin
1334 * @return bool true if successfully set
1335 * @throws coding_exception if attempting to set a non-installed evaluation method
1337 public function set_grading_evaluation_method($method) {
1338 global $DB;
1340 $evaluationlib = dirname(__FILE__) . '/eval/' . $method . '/lib.php';
1342 if (is_readable($evaluationlib)) {
1343 $this->evaluationinstance = null;
1344 $this->evaluation = $method;
1345 $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id));
1346 return true;
1349 throw new coding_exception('Attempt to set a non-existing evaluation method.');
1353 * Returns instance of grading evaluation class
1355 * @return stdclass Instance of a grading evaluation
1357 public function grading_evaluation_instance() {
1358 global $CFG; // because we require other libs here
1360 if (is_null($this->evaluationinstance)) {
1361 if (empty($this->evaluation)) {
1362 $this->evaluation = 'best';
1364 $evaluationlib = dirname(__FILE__) . '/eval/' . $this->evaluation . '/lib.php';
1365 if (is_readable($evaluationlib)) {
1366 require_once($evaluationlib);
1367 } else {
1368 // Fall back in case the subplugin is not available.
1369 $this->evaluation = 'best';
1370 $evaluationlib = dirname(__FILE__) . '/eval/' . $this->evaluation . '/lib.php';
1371 if (is_readable($evaluationlib)) {
1372 require_once($evaluationlib);
1373 } else {
1374 // Fall back in case the subplugin is not available any more.
1375 throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
1378 $classname = 'workshop_' . $this->evaluation . '_evaluation';
1379 $this->evaluationinstance = new $classname($this);
1380 if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) {
1381 throw new coding_exception($classname . ' does not extend workshop_evaluation class');
1384 return $this->evaluationinstance;
1388 * Returns instance of submissions allocator
1390 * @param string $method The name of the allocation method, must be PARAM_ALPHA
1391 * @return stdclass Instance of submissions allocator
1393 public function allocator_instance($method) {
1394 global $CFG; // because we require other libs here
1396 $allocationlib = dirname(__FILE__) . '/allocation/' . $method . '/lib.php';
1397 if (is_readable($allocationlib)) {
1398 require_once($allocationlib);
1399 } else {
1400 throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
1402 $classname = 'workshop_' . $method . '_allocator';
1403 return new $classname($this);
1407 * @return moodle_url of this workshop's view page
1409 public function view_url() {
1410 global $CFG;
1411 return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
1415 * @return moodle_url of the page for editing this workshop's grading form
1417 public function editform_url() {
1418 global $CFG;
1419 return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
1423 * @return moodle_url of the page for previewing this workshop's grading form
1425 public function previewform_url() {
1426 global $CFG;
1427 return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
1431 * @param int $assessmentid The ID of assessment record
1432 * @return moodle_url of the assessment page
1434 public function assess_url($assessmentid) {
1435 global $CFG;
1436 $assessmentid = clean_param($assessmentid, PARAM_INT);
1437 return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
1441 * @param int $assessmentid The ID of assessment record
1442 * @return moodle_url of the example assessment page
1444 public function exassess_url($assessmentid) {
1445 global $CFG;
1446 $assessmentid = clean_param($assessmentid, PARAM_INT);
1447 return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
1451 * @return moodle_url of the page to view a submission, defaults to the own one
1453 public function submission_url($id=null) {
1454 global $CFG;
1455 return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
1459 * @param int $id example submission id
1460 * @return moodle_url of the page to view an example submission
1462 public function exsubmission_url($id) {
1463 global $CFG;
1464 return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
1468 * @param int $sid submission id
1469 * @param array $aid of int assessment ids
1470 * @return moodle_url of the page to compare assessments of the given submission
1472 public function compare_url($sid, array $aids) {
1473 global $CFG;
1475 $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
1476 $i = 0;
1477 foreach ($aids as $aid) {
1478 $url->param("aid{$i}", $aid);
1479 $i++;
1481 return $url;
1485 * @param int $sid submission id
1486 * @param int $aid assessment id
1487 * @return moodle_url of the page to compare the reference assessments of the given example submission
1489 public function excompare_url($sid, $aid) {
1490 global $CFG;
1491 return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
1495 * @return moodle_url of the mod_edit form
1497 public function updatemod_url() {
1498 global $CFG;
1499 return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
1503 * @param string $method allocation method
1504 * @return moodle_url to the allocation page
1506 public function allocation_url($method=null) {
1507 global $CFG;
1508 $params = array('cmid' => $this->cm->id);
1509 if (!empty($method)) {
1510 $params['method'] = $method;
1512 return new moodle_url('/mod/workshop/allocation.php', $params);
1516 * @param int $phasecode The internal phase code
1517 * @return moodle_url of the script to change the current phase to $phasecode
1519 public function switchphase_url($phasecode) {
1520 global $CFG;
1521 $phasecode = clean_param($phasecode, PARAM_INT);
1522 return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
1526 * @return moodle_url to the aggregation page
1528 public function aggregate_url() {
1529 global $CFG;
1530 return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
1534 * @return moodle_url of this workshop's toolbox page
1536 public function toolbox_url($tool) {
1537 global $CFG;
1538 return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
1542 * Workshop wrapper around {@see add_to_log()}
1543 * @deprecated since 2.7 Please use the provided event classes for logging actions.
1545 * @param string $action to be logged
1546 * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends
1547 * @param mixed $info additional info, usually id in a table
1548 * @param bool $return true to return the arguments for add_to_log.
1549 * @return void|array array of arguments for add_to_log if $return is true
1551 public function log($action, moodle_url $url = null, $info = null, $return = false) {
1552 debugging('The log method is now deprecated, please use event classes instead', DEBUG_DEVELOPER);
1554 if (is_null($url)) {
1555 $url = $this->view_url();
1558 if (is_null($info)) {
1559 $info = $this->id;
1562 $logurl = $this->log_convert_url($url);
1563 $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
1564 if ($return) {
1565 return $args;
1567 call_user_func_array('add_to_log', $args);
1571 * Is the given user allowed to create their submission?
1573 * @param int $userid
1574 * @return bool
1576 public function creating_submission_allowed($userid) {
1578 $now = time();
1579 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1581 if ($this->latesubmissions) {
1582 if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) {
1583 // late submissions are allowed in the submission and assessment phase only
1584 return false;
1586 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1587 // late submissions are not allowed before the submission start
1588 return false;
1590 return true;
1592 } else {
1593 if ($this->phase != self::PHASE_SUBMISSION) {
1594 // submissions are allowed during the submission phase only
1595 return false;
1597 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1598 // if enabled, submitting is not allowed before the date/time defined in the mod_form
1599 return false;
1601 if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) {
1602 // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed
1603 return false;
1605 return true;
1610 * Is the given user allowed to modify their existing submission?
1612 * @param int $userid
1613 * @return bool
1615 public function modifying_submission_allowed($userid) {
1617 $now = time();
1618 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1620 if ($this->phase != self::PHASE_SUBMISSION) {
1621 // submissions can be edited during the submission phase only
1622 return false;
1624 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1625 // if enabled, re-submitting is not allowed before the date/time defined in the mod_form
1626 return false;
1628 if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) {
1629 // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed
1630 return false;
1632 return true;
1636 * Is the given reviewer allowed to create/edit their assessments?
1638 * @param int $userid
1639 * @return bool
1641 public function assessing_allowed($userid) {
1643 if ($this->phase != self::PHASE_ASSESSMENT) {
1644 // assessing is allowed in the assessment phase only, unless the user is a teacher
1645 // providing additional assessment during the evaluation phase
1646 if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) {
1647 return false;
1651 $now = time();
1652 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1654 if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) {
1655 // if enabled, assessing is not allowed before the date/time defined in the mod_form
1656 return false;
1658 if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) {
1659 // if enabled, assessing is not allowed after the date/time defined in the mod_form
1660 return false;
1662 // here we go, assessing is allowed
1663 return true;
1667 * Are reviewers allowed to create/edit their assessments of the example submissions?
1669 * Returns null if example submissions are not enabled in this workshop. Otherwise returns
1670 * true or false. Note this does not check other conditions like the number of already
1671 * assessed examples, examples mode etc.
1673 * @return null|bool
1675 public function assessing_examples_allowed() {
1676 if (empty($this->useexamples)) {
1677 return null;
1679 if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
1680 return true;
1682 if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
1683 return true;
1685 if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
1686 return true;
1688 return false;
1692 * Are the peer-reviews available to the authors?
1694 * @return bool
1696 public function assessments_available() {
1697 return $this->phase == self::PHASE_CLOSED;
1701 * Switch to a new workshop phase
1703 * Modifies the underlying database record. You should terminate the script shortly after calling this.
1705 * @param int $newphase new phase code
1706 * @return bool true if success, false otherwise
1708 public function switch_phase($newphase) {
1709 global $DB;
1711 $known = $this->available_phases_list();
1712 if (!isset($known[$newphase])) {
1713 return false;
1716 if (self::PHASE_CLOSED == $newphase) {
1717 // push the grades into the gradebook
1718 $workshop = new stdclass();
1719 foreach ($this as $property => $value) {
1720 $workshop->{$property} = $value;
1722 $workshop->course = $this->course->id;
1723 $workshop->cmidnumber = $this->cm->id;
1724 $workshop->modname = 'workshop';
1725 workshop_update_grades($workshop);
1728 $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
1729 $this->phase = $newphase;
1730 $eventdata = array(
1731 'objectid' => $this->id,
1732 'context' => $this->context,
1733 'other' => array(
1734 'workshopphase' => $this->phase
1737 $event = \mod_workshop\event\phase_switched::create($eventdata);
1738 $event->trigger();
1739 return true;
1743 * Saves a raw grade for submission as calculated from the assessment form fields
1745 * @param array $assessmentid assessment record id, must exists
1746 * @param mixed $grade raw percentual grade from 0.00000 to 100.00000
1747 * @return false|float the saved grade
1749 public function set_peer_grade($assessmentid, $grade) {
1750 global $DB;
1752 if (is_null($grade)) {
1753 return false;
1755 $data = new stdclass();
1756 $data->id = $assessmentid;
1757 $data->grade = $grade;
1758 $data->timemodified = time();
1759 $DB->update_record('workshop_assessments', $data);
1760 return $grade;
1764 * Prepares data object with all workshop grades to be rendered
1766 * @param int $userid the user we are preparing the report for
1767 * @param int $groupid if non-zero, prepare the report for the given group only
1768 * @param int $page the current page (for the pagination)
1769 * @param int $perpage participants per page (for the pagination)
1770 * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
1771 * @param string $sorthow ASC|DESC
1772 * @return stdclass data for the renderer
1774 public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
1775 global $DB;
1777 $canviewall = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
1778 $isparticipant = $this->is_participant($userid);
1780 if (!$canviewall and !$isparticipant) {
1781 // who the hell is this?
1782 return array();
1785 if (!in_array($sortby, array('lastname', 'firstname', 'submissiontitle', 'submissionmodified',
1786 'submissiongrade', 'gradinggrade'))) {
1787 $sortby = 'lastname';
1790 if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
1791 $sorthow = 'ASC';
1794 // get the list of user ids to be displayed
1795 if ($canviewall) {
1796 $participants = $this->get_participants(false, $groupid);
1797 } else {
1798 // this is an ordinary workshop participant (aka student) - display the report just for him/her
1799 $participants = array($userid => (object)array('id' => $userid));
1802 // we will need to know the number of all records later for the pagination purposes
1803 $numofparticipants = count($participants);
1805 if ($numofparticipants > 0) {
1806 // load all fields which can be used for sorting and paginate the records
1807 list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1808 $params['workshopid1'] = $this->id;
1809 $params['workshopid2'] = $this->id;
1810 $sqlsort = array();
1811 $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
1812 foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
1813 $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
1815 $sqlsort = implode(',', $sqlsort);
1816 $picturefields = user_picture::fields('u', array(), 'userid');
1817 $sql = "SELECT $picturefields, s.title AS submissiontitle, s.timemodified AS submissionmodified,
1818 s.grade AS submissiongrade, ag.gradinggrade
1819 FROM {user} u
1820 LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)
1821 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)
1822 WHERE u.id $participantids
1823 ORDER BY $sqlsort";
1824 $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1825 } else {
1826 $participants = array();
1829 // this will hold the information needed to display user names and pictures
1830 $userinfo = array();
1832 // get the user details for all participants to display
1833 $additionalnames = get_all_user_name_fields();
1834 foreach ($participants as $participant) {
1835 if (!isset($userinfo[$participant->userid])) {
1836 $userinfo[$participant->userid] = new stdclass();
1837 $userinfo[$participant->userid]->id = $participant->userid;
1838 $userinfo[$participant->userid]->picture = $participant->picture;
1839 $userinfo[$participant->userid]->imagealt = $participant->imagealt;
1840 $userinfo[$participant->userid]->email = $participant->email;
1841 foreach ($additionalnames as $addname) {
1842 $userinfo[$participant->userid]->$addname = $participant->$addname;
1847 // load the submissions details
1848 $submissions = $this->get_submissions(array_keys($participants));
1850 // get the user details for all moderators (teachers) that have overridden a submission grade
1851 foreach ($submissions as $submission) {
1852 if (!isset($userinfo[$submission->gradeoverby])) {
1853 $userinfo[$submission->gradeoverby] = new stdclass();
1854 $userinfo[$submission->gradeoverby]->id = $submission->gradeoverby;
1855 $userinfo[$submission->gradeoverby]->picture = $submission->overpicture;
1856 $userinfo[$submission->gradeoverby]->imagealt = $submission->overimagealt;
1857 $userinfo[$submission->gradeoverby]->email = $submission->overemail;
1858 foreach ($additionalnames as $addname) {
1859 $temp = 'over' . $addname;
1860 $userinfo[$submission->gradeoverby]->$addname = $submission->$temp;
1865 // get the user details for all reviewers of the displayed participants
1866 $reviewers = array();
1868 if ($submissions) {
1869 list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
1870 list($sort, $sortparams) = users_order_by_sql('r');
1871 $picturefields = user_picture::fields('r', array(), 'reviewerid');
1872 $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,
1873 $picturefields, s.id AS submissionid, s.authorid
1874 FROM {workshop_assessments} a
1875 JOIN {user} r ON (a.reviewerid = r.id)
1876 JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1877 WHERE a.submissionid $submissionids
1878 ORDER BY a.weight DESC, $sort";
1879 $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
1880 foreach ($reviewers as $reviewer) {
1881 if (!isset($userinfo[$reviewer->reviewerid])) {
1882 $userinfo[$reviewer->reviewerid] = new stdclass();
1883 $userinfo[$reviewer->reviewerid]->id = $reviewer->reviewerid;
1884 $userinfo[$reviewer->reviewerid]->picture = $reviewer->picture;
1885 $userinfo[$reviewer->reviewerid]->imagealt = $reviewer->imagealt;
1886 $userinfo[$reviewer->reviewerid]->email = $reviewer->email;
1887 foreach ($additionalnames as $addname) {
1888 $userinfo[$reviewer->reviewerid]->$addname = $reviewer->$addname;
1894 // get the user details for all reviewees of the displayed participants
1895 $reviewees = array();
1896 if ($participants) {
1897 list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1898 list($sort, $sortparams) = users_order_by_sql('e');
1899 $params['workshopid'] = $this->id;
1900 $picturefields = user_picture::fields('e', array(), 'authorid');
1901 $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,
1902 s.id AS submissionid, $picturefields
1903 FROM {user} u
1904 JOIN {workshop_assessments} a ON (a.reviewerid = u.id)
1905 JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1906 JOIN {user} e ON (s.authorid = e.id)
1907 WHERE u.id $participantids AND s.workshopid = :workshopid
1908 ORDER BY a.weight DESC, $sort";
1909 $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
1910 foreach ($reviewees as $reviewee) {
1911 if (!isset($userinfo[$reviewee->authorid])) {
1912 $userinfo[$reviewee->authorid] = new stdclass();
1913 $userinfo[$reviewee->authorid]->id = $reviewee->authorid;
1914 $userinfo[$reviewee->authorid]->picture = $reviewee->picture;
1915 $userinfo[$reviewee->authorid]->imagealt = $reviewee->imagealt;
1916 $userinfo[$reviewee->authorid]->email = $reviewee->email;
1917 foreach ($additionalnames as $addname) {
1918 $userinfo[$reviewee->authorid]->$addname = $reviewee->$addname;
1924 // finally populate the object to be rendered
1925 $grades = $participants;
1927 foreach ($participants as $participant) {
1928 // set up default (null) values
1929 $grades[$participant->userid]->submissionid = null;
1930 $grades[$participant->userid]->submissiontitle = null;
1931 $grades[$participant->userid]->submissiongrade = null;
1932 $grades[$participant->userid]->submissiongradeover = null;
1933 $grades[$participant->userid]->submissiongradeoverby = null;
1934 $grades[$participant->userid]->submissionpublished = null;
1935 $grades[$participant->userid]->reviewedby = array();
1936 $grades[$participant->userid]->reviewerof = array();
1938 unset($participants);
1939 unset($participant);
1941 foreach ($submissions as $submission) {
1942 $grades[$submission->authorid]->submissionid = $submission->id;
1943 $grades[$submission->authorid]->submissiontitle = $submission->title;
1944 $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
1945 $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
1946 $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
1947 $grades[$submission->authorid]->submissionpublished = $submission->published;
1949 unset($submissions);
1950 unset($submission);
1952 foreach($reviewers as $reviewer) {
1953 $info = new stdclass();
1954 $info->userid = $reviewer->reviewerid;
1955 $info->assessmentid = $reviewer->assessmentid;
1956 $info->submissionid = $reviewer->submissionid;
1957 $info->grade = $this->real_grade($reviewer->grade);
1958 $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
1959 $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
1960 $info->weight = $reviewer->weight;
1961 $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
1963 unset($reviewers);
1964 unset($reviewer);
1966 foreach($reviewees as $reviewee) {
1967 $info = new stdclass();
1968 $info->userid = $reviewee->authorid;
1969 $info->assessmentid = $reviewee->assessmentid;
1970 $info->submissionid = $reviewee->submissionid;
1971 $info->grade = $this->real_grade($reviewee->grade);
1972 $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
1973 $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
1974 $info->weight = $reviewee->weight;
1975 $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
1977 unset($reviewees);
1978 unset($reviewee);
1980 foreach ($grades as $grade) {
1981 $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
1984 $data = new stdclass();
1985 $data->grades = $grades;
1986 $data->userinfo = $userinfo;
1987 $data->totalcount = $numofparticipants;
1988 $data->maxgrade = $this->real_grade(100);
1989 $data->maxgradinggrade = $this->real_grading_grade(100);
1990 return $data;
1994 * Calculates the real value of a grade
1996 * @param float $value percentual value from 0 to 100
1997 * @param float $max the maximal grade
1998 * @return string
2000 public function real_grade_value($value, $max) {
2001 $localized = true;
2002 if (is_null($value) or $value === '') {
2003 return null;
2004 } elseif ($max == 0) {
2005 return 0;
2006 } else {
2007 return format_float($max * $value / 100, $this->gradedecimals, $localized);
2012 * Calculates the raw (percentual) value from a real grade
2014 * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save
2015 * this value in a raw percentual form into DB
2016 * @param float $value given grade
2017 * @param float $max the maximal grade
2018 * @return float suitable to be stored as numeric(10,5)
2020 public function raw_grade_value($value, $max) {
2021 if (is_null($value) or $value === '') {
2022 return null;
2024 if ($max == 0 or $value < 0) {
2025 return 0;
2027 $p = $value / $max * 100;
2028 if ($p > 100) {
2029 return $max;
2031 return grade_floatval($p);
2035 * Calculates the real value of grade for submission
2037 * @param float $value percentual value from 0 to 100
2038 * @return string
2040 public function real_grade($value) {
2041 return $this->real_grade_value($value, $this->grade);
2045 * Calculates the real value of grade for assessment
2047 * @param float $value percentual value from 0 to 100
2048 * @return string
2050 public function real_grading_grade($value) {
2051 return $this->real_grade_value($value, $this->gradinggrade);
2055 * Sets the given grades and received grading grades to null
2057 * This does not clear the information about how the peers filled the assessment forms, but
2058 * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess
2059 * the allocated submissions.
2061 * @return void
2063 public function clear_assessments() {
2064 global $DB;
2066 $submissions = $this->get_submissions();
2067 if (empty($submissions)) {
2068 // no money, no love
2069 return;
2071 $submissions = array_keys($submissions);
2072 list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED);
2073 $sql = "submissionid $sql";
2074 $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params);
2075 $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params);
2079 * Sets the grades for submission to null
2081 * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2082 * @return void
2084 public function clear_submission_grades($restrict=null) {
2085 global $DB;
2087 $sql = "workshopid = :workshopid AND example = 0";
2088 $params = array('workshopid' => $this->id);
2090 if (is_null($restrict)) {
2091 // update all users - no more conditions
2092 } elseif (!empty($restrict)) {
2093 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2094 $sql .= " AND authorid $usql";
2095 $params = array_merge($params, $uparams);
2096 } else {
2097 throw new coding_exception('Empty value is not a valid parameter here');
2100 $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
2104 * Calculates grades for submission for the given participant(s) and updates it in the database
2106 * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2107 * @return void
2109 public function aggregate_submission_grades($restrict=null) {
2110 global $DB;
2112 // fetch a recordset with all assessments to process
2113 $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
2114 a.weight, a.grade
2115 FROM {workshop_submissions} s
2116 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id)
2117 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2118 $params = array('workshopid' => $this->id);
2120 if (is_null($restrict)) {
2121 // update all users - no more conditions
2122 } elseif (!empty($restrict)) {
2123 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2124 $sql .= " AND s.authorid $usql";
2125 $params = array_merge($params, $uparams);
2126 } else {
2127 throw new coding_exception('Empty value is not a valid parameter here');
2130 $sql .= ' ORDER BY s.id'; // this is important for bulk processing
2132 $rs = $DB->get_recordset_sql($sql, $params);
2133 $batch = array(); // will contain a set of all assessments of a single submission
2134 $previous = null; // a previous record in the recordset
2136 foreach ($rs as $current) {
2137 if (is_null($previous)) {
2138 // we are processing the very first record in the recordset
2139 $previous = $current;
2141 if ($current->submissionid == $previous->submissionid) {
2142 // we are still processing the current submission
2143 $batch[] = $current;
2144 } else {
2145 // process all the assessments of a sigle submission
2146 $this->aggregate_submission_grades_process($batch);
2147 // and then start to process another submission
2148 $batch = array($current);
2149 $previous = $current;
2152 // do not forget to process the last batch!
2153 $this->aggregate_submission_grades_process($batch);
2154 $rs->close();
2158 * Sets the aggregated grades for assessment to null
2160 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2161 * @return void
2163 public function clear_grading_grades($restrict=null) {
2164 global $DB;
2166 $sql = "workshopid = :workshopid";
2167 $params = array('workshopid' => $this->id);
2169 if (is_null($restrict)) {
2170 // update all users - no more conditions
2171 } elseif (!empty($restrict)) {
2172 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2173 $sql .= " AND userid $usql";
2174 $params = array_merge($params, $uparams);
2175 } else {
2176 throw new coding_exception('Empty value is not a valid parameter here');
2179 $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
2183 * Calculates grades for assessment for the given participant(s)
2185 * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator.
2186 * The assessment weight is not taken into account here.
2188 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2189 * @return void
2191 public function aggregate_grading_grades($restrict=null) {
2192 global $DB;
2194 // fetch a recordset with all assessments to process
2195 $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover,
2196 ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade
2197 FROM {workshop_assessments} a
2198 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
2199 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid)
2200 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2201 $params = array('workshopid' => $this->id);
2203 if (is_null($restrict)) {
2204 // update all users - no more conditions
2205 } elseif (!empty($restrict)) {
2206 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2207 $sql .= " AND a.reviewerid $usql";
2208 $params = array_merge($params, $uparams);
2209 } else {
2210 throw new coding_exception('Empty value is not a valid parameter here');
2213 $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing
2215 $rs = $DB->get_recordset_sql($sql, $params);
2216 $batch = array(); // will contain a set of all assessments of a single submission
2217 $previous = null; // a previous record in the recordset
2219 foreach ($rs as $current) {
2220 if (is_null($previous)) {
2221 // we are processing the very first record in the recordset
2222 $previous = $current;
2224 if ($current->reviewerid == $previous->reviewerid) {
2225 // we are still processing the current reviewer
2226 $batch[] = $current;
2227 } else {
2228 // process all the assessments of a sigle submission
2229 $this->aggregate_grading_grades_process($batch);
2230 // and then start to process another reviewer
2231 $batch = array($current);
2232 $previous = $current;
2235 // do not forget to process the last batch!
2236 $this->aggregate_grading_grades_process($batch);
2237 $rs->close();
2241 * Returns the mform the teachers use to put a feedback for the reviewer
2243 * @param moodle_url $actionurl
2244 * @param stdClass $assessment
2245 * @param array $options editable, editableweight, overridablegradinggrade
2246 * @return workshop_feedbackreviewer_form
2248 public function get_feedbackreviewer_form(moodle_url $actionurl, stdclass $assessment, $options=array()) {
2249 global $CFG;
2250 require_once(dirname(__FILE__) . '/feedbackreviewer_form.php');
2252 $current = new stdclass();
2253 $current->asid = $assessment->id;
2254 $current->weight = $assessment->weight;
2255 $current->gradinggrade = $this->real_grading_grade($assessment->gradinggrade);
2256 $current->gradinggradeover = $this->real_grading_grade($assessment->gradinggradeover);
2257 $current->feedbackreviewer = $assessment->feedbackreviewer;
2258 $current->feedbackreviewerformat = $assessment->feedbackreviewerformat;
2259 if (is_null($current->gradinggrade)) {
2260 $current->gradinggrade = get_string('nullgrade', 'workshop');
2262 if (!isset($options['editable'])) {
2263 $editable = true; // by default
2264 } else {
2265 $editable = (bool)$options['editable'];
2268 // prepare wysiwyg editor
2269 $current = file_prepare_standard_editor($current, 'feedbackreviewer', array());
2271 return new workshop_feedbackreviewer_form($actionurl,
2272 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2273 'post', '', null, $editable);
2277 * Returns the mform the teachers use to put a feedback for the author on their submission
2279 * @param moodle_url $actionurl
2280 * @param stdClass $submission
2281 * @param array $options editable
2282 * @return workshop_feedbackauthor_form
2284 public function get_feedbackauthor_form(moodle_url $actionurl, stdclass $submission, $options=array()) {
2285 global $CFG;
2286 require_once(dirname(__FILE__) . '/feedbackauthor_form.php');
2288 $current = new stdclass();
2289 $current->submissionid = $submission->id;
2290 $current->published = $submission->published;
2291 $current->grade = $this->real_grade($submission->grade);
2292 $current->gradeover = $this->real_grade($submission->gradeover);
2293 $current->feedbackauthor = $submission->feedbackauthor;
2294 $current->feedbackauthorformat = $submission->feedbackauthorformat;
2295 if (is_null($current->grade)) {
2296 $current->grade = get_string('nullgrade', 'workshop');
2298 if (!isset($options['editable'])) {
2299 $editable = true; // by default
2300 } else {
2301 $editable = (bool)$options['editable'];
2304 // prepare wysiwyg editor
2305 $current = file_prepare_standard_editor($current, 'feedbackauthor', array());
2307 return new workshop_feedbackauthor_form($actionurl,
2308 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2309 'post', '', null, $editable);
2313 * Returns the information about the user's grades as they are stored in the gradebook
2315 * The submission grade is returned for users with the capability mod/workshop:submit and the
2316 * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
2317 * user has the capability to view hidden grades, grades must be visible to be returned. Null
2318 * grades are not returned. If none grade is to be returned, this method returns false.
2320 * @param int $userid the user's id
2321 * @return workshop_final_grades|false
2323 public function get_gradebook_grades($userid) {
2324 global $CFG;
2325 require_once($CFG->libdir.'/gradelib.php');
2327 if (empty($userid)) {
2328 throw new coding_exception('User id expected, empty value given.');
2331 // Read data via the Gradebook API
2332 $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
2334 $grades = new workshop_final_grades();
2336 if (has_capability('mod/workshop:submit', $this->context, $userid)) {
2337 if (!empty($gradebook->items[0]->grades)) {
2338 $submissiongrade = reset($gradebook->items[0]->grades);
2339 if (!is_null($submissiongrade->grade)) {
2340 if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2341 $grades->submissiongrade = $submissiongrade;
2347 if (has_capability('mod/workshop:peerassess', $this->context, $userid)) {
2348 if (!empty($gradebook->items[1]->grades)) {
2349 $assessmentgrade = reset($gradebook->items[1]->grades);
2350 if (!is_null($assessmentgrade->grade)) {
2351 if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2352 $grades->assessmentgrade = $assessmentgrade;
2358 if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
2359 return $grades;
2362 return false;
2366 * Return the editor options for the overall feedback for the author.
2368 * @return array
2370 public function overall_feedback_content_options() {
2371 return array(
2372 'subdirs' => 0,
2373 'maxbytes' => $this->overallfeedbackmaxbytes,
2374 'maxfiles' => $this->overallfeedbackfiles,
2375 'changeformat' => 1,
2376 'context' => $this->context,
2381 * Return the filemanager options for the overall feedback for the author.
2383 * @return array
2385 public function overall_feedback_attachment_options() {
2386 return array(
2387 'subdirs' => 1,
2388 'maxbytes' => $this->overallfeedbackmaxbytes,
2389 'maxfiles' => $this->overallfeedbackfiles,
2390 'return_types' => FILE_INTERNAL,
2395 * Performs the reset of this workshop instance.
2397 * @param stdClass $data The actual course reset settings.
2398 * @return array List of results, each being array[(string)component, (string)item, (string)error]
2400 public function reset_userdata(stdClass $data) {
2402 $componentstr = get_string('pluginname', 'workshop').': '.format_string($this->name);
2403 $status = array();
2405 if (!empty($data->reset_workshop_assessments) or !empty($data->reset_workshop_submissions)) {
2406 // Reset all data related to assessments, including assessments of
2407 // example submissions.
2408 $result = $this->reset_userdata_assessments($data);
2409 if ($result === true) {
2410 $status[] = array(
2411 'component' => $componentstr,
2412 'item' => get_string('resetassessments', 'mod_workshop'),
2413 'error' => false,
2415 } else {
2416 $status[] = array(
2417 'component' => $componentstr,
2418 'item' => get_string('resetassessments', 'mod_workshop'),
2419 'error' => $result,
2424 if (!empty($data->reset_workshop_submissions)) {
2425 // Reset all remaining data related to submissions.
2426 $result = $this->reset_userdata_submissions($data);
2427 if ($result === true) {
2428 $status[] = array(
2429 'component' => $componentstr,
2430 'item' => get_string('resetsubmissions', 'mod_workshop'),
2431 'error' => false,
2433 } else {
2434 $status[] = array(
2435 'component' => $componentstr,
2436 'item' => get_string('resetsubmissions', 'mod_workshop'),
2437 'error' => $result,
2442 if (!empty($data->reset_workshop_phase)) {
2443 // Do not use the {@link workshop::switch_phase()} here, we do not
2444 // want to trigger events.
2445 $this->reset_phase();
2446 $status[] = array(
2447 'component' => $componentstr,
2448 'item' => get_string('resetsubmissions', 'mod_workshop'),
2449 'error' => false,
2453 return $status;
2457 ////////////////////////////////////////////////////////////////////////////////
2458 // Internal methods (implementation details) //
2459 ////////////////////////////////////////////////////////////////////////////////
2462 * Given an array of all assessments of a single submission, calculates the final grade for this submission
2464 * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade
2465 * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored.
2467 * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
2468 * @return void
2470 protected function aggregate_submission_grades_process(array $assessments) {
2471 global $DB;
2473 $submissionid = null; // the id of the submission being processed
2474 $current = null; // the grade currently saved in database
2475 $finalgrade = null; // the new grade to be calculated
2476 $sumgrades = 0;
2477 $sumweights = 0;
2479 foreach ($assessments as $assessment) {
2480 if (is_null($submissionid)) {
2481 // the id is the same in all records, fetch it during the first loop cycle
2482 $submissionid = $assessment->submissionid;
2484 if (is_null($current)) {
2485 // the currently saved grade is the same in all records, fetch it during the first loop cycle
2486 $current = $assessment->submissiongrade;
2488 if (is_null($assessment->grade)) {
2489 // this was not assessed yet
2490 continue;
2492 if ($assessment->weight == 0) {
2493 // this does not influence the calculation
2494 continue;
2496 $sumgrades += $assessment->grade * $assessment->weight;
2497 $sumweights += $assessment->weight;
2499 if ($sumweights > 0 and is_null($finalgrade)) {
2500 $finalgrade = grade_floatval($sumgrades / $sumweights);
2502 // check if the new final grade differs from the one stored in the database
2503 if (grade_floats_different($finalgrade, $current)) {
2504 // we need to save new calculation into the database
2505 $record = new stdclass();
2506 $record->id = $submissionid;
2507 $record->grade = $finalgrade;
2508 $record->timegraded = time();
2509 $DB->update_record('workshop_submissions', $record);
2514 * Given an array of all assessments done by a single reviewer, calculates the final grading grade
2516 * This calculates the simple mean of the passed grading grades. If, however, the grading grade
2517 * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored.
2519 * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade)
2520 * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time
2521 * @return void
2523 protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
2524 global $DB;
2526 $reviewerid = null; // the id of the reviewer being processed
2527 $current = null; // the gradinggrade currently saved in database
2528 $finalgrade = null; // the new grade to be calculated
2529 $agid = null; // aggregation id
2530 $sumgrades = 0;
2531 $count = 0;
2533 if (is_null($timegraded)) {
2534 $timegraded = time();
2537 foreach ($assessments as $assessment) {
2538 if (is_null($reviewerid)) {
2539 // the id is the same in all records, fetch it during the first loop cycle
2540 $reviewerid = $assessment->reviewerid;
2542 if (is_null($agid)) {
2543 // the id is the same in all records, fetch it during the first loop cycle
2544 $agid = $assessment->aggregationid;
2546 if (is_null($current)) {
2547 // the currently saved grade is the same in all records, fetch it during the first loop cycle
2548 $current = $assessment->aggregatedgrade;
2550 if (!is_null($assessment->gradinggradeover)) {
2551 // the grading grade for this assessment is overridden by a teacher
2552 $sumgrades += $assessment->gradinggradeover;
2553 $count++;
2554 } else {
2555 if (!is_null($assessment->gradinggrade)) {
2556 $sumgrades += $assessment->gradinggrade;
2557 $count++;
2561 if ($count > 0) {
2562 $finalgrade = grade_floatval($sumgrades / $count);
2565 // Event information.
2566 $params = array(
2567 'context' => $this->context,
2568 'courseid' => $this->course->id,
2569 'relateduserid' => $reviewerid
2572 // check if the new final grade differs from the one stored in the database
2573 if (grade_floats_different($finalgrade, $current)) {
2574 $params['other'] = array(
2575 'currentgrade' => $current,
2576 'finalgrade' => $finalgrade
2579 // we need to save new calculation into the database
2580 if (is_null($agid)) {
2581 // no aggregation record yet
2582 $record = new stdclass();
2583 $record->workshopid = $this->id;
2584 $record->userid = $reviewerid;
2585 $record->gradinggrade = $finalgrade;
2586 $record->timegraded = $timegraded;
2587 $record->id = $DB->insert_record('workshop_aggregations', $record);
2588 $params['objectid'] = $record->id;
2589 $event = \mod_workshop\event\assessment_evaluated::create($params);
2590 $event->trigger();
2591 } else {
2592 $record = new stdclass();
2593 $record->id = $agid;
2594 $record->gradinggrade = $finalgrade;
2595 $record->timegraded = $timegraded;
2596 $DB->update_record('workshop_aggregations', $record);
2597 $params['objectid'] = $agid;
2598 $event = \mod_workshop\event\assessment_reevaluated::create($params);
2599 $event->trigger();
2605 * Returns SQL to fetch all enrolled users with the given capability in the current workshop
2607 * The returned array consists of string $sql and the $params array. Note that the $sql can be
2608 * empty if a grouping is selected and it has no groups.
2610 * The list is automatically restricted according to any availability restrictions
2611 * that apply to user lists (e.g. group, grouping restrictions).
2613 * @param string $capability the name of the capability
2614 * @param bool $musthavesubmission ff true, return only users who have already submitted
2615 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2616 * @return array of (string)sql, (array)params
2618 protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) {
2619 global $CFG;
2620 /** @var int static counter used to generate unique parameter holders */
2621 static $inc = 0;
2622 $inc++;
2624 // If the caller requests all groups and we are using a selected grouping,
2625 // recursively call this function for each group in the grouping (this is
2626 // needed because get_enrolled_sql only supports a single group).
2627 if (empty($groupid) and $this->cm->groupingid) {
2628 $groupingid = $this->cm->groupingid;
2629 $groupinggroupids = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
2630 $sql = array();
2631 $params = array();
2632 foreach ($groupinggroupids as $groupinggroupid) {
2633 if ($groupinggroupid > 0) { // just in case in order not to fall into the endless loop
2634 list($gsql, $gparams) = $this->get_users_with_capability_sql($capability, $musthavesubmission, $groupinggroupid);
2635 $sql[] = $gsql;
2636 $params = array_merge($params, $gparams);
2639 $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql);
2640 return array($sql, $params);
2643 list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true);
2645 $userfields = user_picture::fields('u');
2647 $sql = "SELECT $userfields
2648 FROM {user} u
2649 JOIN ($esql) je ON (je.id = u.id AND u.deleted = 0) ";
2651 if ($musthavesubmission) {
2652 $sql .= " JOIN {workshop_submissions} ws ON (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid{$inc}) ";
2653 $params['workshopid'.$inc] = $this->id;
2656 // If the activity is restricted so that only certain users should appear
2657 // in user lists, integrate this into the same SQL.
2658 $info = new \core_availability\info_module($this->cm);
2659 list ($listsql, $listparams) = $info->get_user_list_sql(false);
2660 if ($listsql) {
2661 $sql .= " JOIN ($listsql) restricted ON restricted.id = u.id ";
2662 $params = array_merge($params, $listparams);
2665 return array($sql, $params);
2669 * Returns SQL statement that can be used to fetch all actively enrolled participants in the workshop
2671 * @param bool $musthavesubmission if true, return only users who have already submitted
2672 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2673 * @return array of (string)sql, (array)params
2675 protected function get_participants_sql($musthavesubmission=false, $groupid=0) {
2677 list($sql1, $params1) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
2678 list($sql2, $params2) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
2680 if (empty($sql1) or empty($sql2)) {
2681 if (empty($sql1) and empty($sql2)) {
2682 return array('', array());
2683 } else if (empty($sql1)) {
2684 $sql = $sql2;
2685 $params = $params2;
2686 } else {
2687 $sql = $sql1;
2688 $params = $params1;
2690 } else {
2691 $sql = $sql1.PHP_EOL." UNION ".PHP_EOL.$sql2;
2692 $params = array_merge($params1, $params2);
2695 return array($sql, $params);
2699 * @return array of available workshop phases
2701 protected function available_phases_list() {
2702 return array(
2703 self::PHASE_SETUP => true,
2704 self::PHASE_SUBMISSION => true,
2705 self::PHASE_ASSESSMENT => true,
2706 self::PHASE_EVALUATION => true,
2707 self::PHASE_CLOSED => true,
2712 * Converts absolute URL to relative URL needed by {@see add_to_log()}
2714 * @param moodle_url $url absolute URL
2715 * @return string
2717 protected function log_convert_url(moodle_url $fullurl) {
2718 static $baseurl;
2720 if (!isset($baseurl)) {
2721 $baseurl = new moodle_url('/mod/workshop/');
2722 $baseurl = $baseurl->out();
2725 return substr($fullurl->out(), strlen($baseurl));
2729 * Removes all user data related to assessments (including allocations).
2731 * This includes assessments of example submissions as long as they are not
2732 * referential assessments.
2734 * @param stdClass $data The actual course reset settings.
2735 * @return bool|string True on success, error message otherwise.
2737 protected function reset_userdata_assessments(stdClass $data) {
2738 global $DB;
2740 $sql = "SELECT a.id
2741 FROM {workshop_assessments} a
2742 JOIN {workshop_submissions} s ON (a.submissionid = s.id)
2743 WHERE s.workshopid = :workshopid
2744 AND (s.example = 0 OR (s.example = 1 AND a.weight = 0))";
2746 $assessments = $DB->get_records_sql($sql, array('workshopid' => $this->id));
2747 $this->delete_assessment(array_keys($assessments));
2749 $DB->delete_records('workshop_aggregations', array('workshopid' => $this->id));
2751 return true;
2755 * Removes all user data related to participants' submissions.
2757 * @param stdClass $data The actual course reset settings.
2758 * @return bool|string True on success, error message otherwise.
2760 protected function reset_userdata_submissions(stdClass $data) {
2761 global $DB;
2763 $submissions = $this->get_submissions();
2764 foreach ($submissions as $submission) {
2765 $this->delete_submission($submission);
2768 return true;
2772 * Hard set the workshop phase to the setup one.
2774 protected function reset_phase() {
2775 global $DB;
2777 $DB->set_field('workshop', 'phase', self::PHASE_SETUP, array('id' => $this->id));
2778 $this->phase = self::PHASE_SETUP;
2782 ////////////////////////////////////////////////////////////////////////////////
2783 // Renderable components
2784 ////////////////////////////////////////////////////////////////////////////////
2787 * Represents the user planner tool
2789 * Planner contains list of phases. Each phase contains list of tasks. Task is a simple object with
2790 * title, link and completed (true/false/null logic).
2792 class workshop_user_plan implements renderable {
2794 /** @var int id of the user this plan is for */
2795 public $userid;
2796 /** @var workshop */
2797 public $workshop;
2798 /** @var array of (stdclass)tasks */
2799 public $phases = array();
2800 /** @var null|array of example submissions to be assessed by the planner owner */
2801 protected $examples = null;
2804 * Prepare an individual workshop plan for the given user.
2806 * @param workshop $workshop instance
2807 * @param int $userid whom the plan is prepared for
2809 public function __construct(workshop $workshop, $userid) {
2810 global $DB;
2812 $this->workshop = $workshop;
2813 $this->userid = $userid;
2815 //---------------------------------------------------------
2816 // * SETUP | submission | assessment | evaluation | closed
2817 //---------------------------------------------------------
2818 $phase = new stdclass();
2819 $phase->title = get_string('phasesetup', 'workshop');
2820 $phase->tasks = array();
2821 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2822 $task = new stdclass();
2823 $task->title = get_string('taskintro', 'workshop');
2824 $task->link = $workshop->updatemod_url();
2825 $task->completed = !(trim($workshop->intro) == '');
2826 $phase->tasks['intro'] = $task;
2828 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2829 $task = new stdclass();
2830 $task->title = get_string('taskinstructauthors', 'workshop');
2831 $task->link = $workshop->updatemod_url();
2832 $task->completed = !(trim($workshop->instructauthors) == '');
2833 $phase->tasks['instructauthors'] = $task;
2835 if (has_capability('mod/workshop:editdimensions', $workshop->context, $userid)) {
2836 $task = new stdclass();
2837 $task->title = get_string('editassessmentform', 'workshop');
2838 $task->link = $workshop->editform_url();
2839 if ($workshop->grading_strategy_instance()->form_ready()) {
2840 $task->completed = true;
2841 } elseif ($workshop->phase > workshop::PHASE_SETUP) {
2842 $task->completed = false;
2844 $phase->tasks['editform'] = $task;
2846 if ($workshop->useexamples and has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2847 $task = new stdclass();
2848 $task->title = get_string('prepareexamples', 'workshop');
2849 if ($DB->count_records('workshop_submissions', array('example' => 1, 'workshopid' => $workshop->id)) > 0) {
2850 $task->completed = true;
2851 } elseif ($workshop->phase > workshop::PHASE_SETUP) {
2852 $task->completed = false;
2854 $phase->tasks['prepareexamples'] = $task;
2856 if (empty($phase->tasks) and $workshop->phase == workshop::PHASE_SETUP) {
2857 // if we are in the setup phase and there is no task (typical for students), let us
2858 // display some explanation what is going on
2859 $task = new stdclass();
2860 $task->title = get_string('undersetup', 'workshop');
2861 $task->completed = 'info';
2862 $phase->tasks['setupinfo'] = $task;
2864 $this->phases[workshop::PHASE_SETUP] = $phase;
2866 //---------------------------------------------------------
2867 // setup | * SUBMISSION | assessment | evaluation | closed
2868 //---------------------------------------------------------
2869 $phase = new stdclass();
2870 $phase->title = get_string('phasesubmission', 'workshop');
2871 $phase->tasks = array();
2872 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2873 $task = new stdclass();
2874 $task->title = get_string('taskinstructreviewers', 'workshop');
2875 $task->link = $workshop->updatemod_url();
2876 if (trim($workshop->instructreviewers)) {
2877 $task->completed = true;
2878 } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2879 $task->completed = false;
2881 $phase->tasks['instructreviewers'] = $task;
2883 if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION
2884 and has_capability('mod/workshop:submit', $workshop->context, $userid, false)
2885 and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2886 $task = new stdclass();
2887 $task->title = get_string('exampleassesstask', 'workshop');
2888 $examples = $this->get_examples();
2889 $a = new stdclass();
2890 $a->expected = count($examples);
2891 $a->assessed = 0;
2892 foreach ($examples as $exampleid => $example) {
2893 if (!is_null($example->grade)) {
2894 $a->assessed++;
2897 $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
2898 if ($a->assessed == $a->expected) {
2899 $task->completed = true;
2900 } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2901 $task->completed = false;
2903 $phase->tasks['examples'] = $task;
2905 if (has_capability('mod/workshop:submit', $workshop->context, $userid, false)) {
2906 $task = new stdclass();
2907 $task->title = get_string('tasksubmit', 'workshop');
2908 $task->link = $workshop->submission_url();
2909 if ($DB->record_exists('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0, 'authorid'=>$userid))) {
2910 $task->completed = true;
2911 } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2912 $task->completed = false;
2913 } else {
2914 $task->completed = null; // still has a chance to submit
2916 $phase->tasks['submit'] = $task;
2918 if (has_capability('mod/workshop:allocate', $workshop->context, $userid)) {
2919 if ($workshop->phaseswitchassessment) {
2920 $task = new stdClass();
2921 $allocator = $DB->get_record('workshopallocation_scheduled', array('workshopid' => $workshop->id));
2922 if (empty($allocator)) {
2923 $task->completed = false;
2924 } else if ($allocator->enabled and is_null($allocator->resultstatus)) {
2925 $task->completed = true;
2926 } else if ($workshop->submissionend > time()) {
2927 $task->completed = null;
2928 } else {
2929 $task->completed = false;
2931 $task->title = get_string('setup', 'workshopallocation_scheduled');
2932 $task->link = $workshop->allocation_url('scheduled');
2933 $phase->tasks['allocatescheduled'] = $task;
2935 $task = new stdclass();
2936 $task->title = get_string('allocate', 'workshop');
2937 $task->link = $workshop->allocation_url();
2938 $numofauthors = $workshop->count_potential_authors(false);
2939 $numofsubmissions = $DB->count_records('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0));
2940 $sql = 'SELECT COUNT(s.id) AS nonallocated
2941 FROM {workshop_submissions} s
2942 LEFT JOIN {workshop_assessments} a ON (a.submissionid=s.id)
2943 WHERE s.workshopid = :workshopid AND s.example=0 AND a.submissionid IS NULL';
2944 $params['workshopid'] = $workshop->id;
2945 $numnonallocated = $DB->count_records_sql($sql, $params);
2946 if ($numofsubmissions == 0) {
2947 $task->completed = null;
2948 } elseif ($numnonallocated == 0) {
2949 $task->completed = true;
2950 } elseif ($workshop->phase > workshop::PHASE_SUBMISSION) {
2951 $task->completed = false;
2952 } else {
2953 $task->completed = null; // still has a chance to allocate
2955 $a = new stdclass();
2956 $a->expected = $numofauthors;
2957 $a->submitted = $numofsubmissions;
2958 $a->allocate = $numnonallocated;
2959 $task->details = get_string('allocatedetails', 'workshop', $a);
2960 unset($a);
2961 $phase->tasks['allocate'] = $task;
2963 if ($numofsubmissions < $numofauthors and $workshop->phase >= workshop::PHASE_SUBMISSION) {
2964 $task = new stdclass();
2965 $task->title = get_string('someuserswosubmission', 'workshop');
2966 $task->completed = 'info';
2967 $phase->tasks['allocateinfo'] = $task;
2971 if ($workshop->submissionstart) {
2972 $task = new stdclass();
2973 $task->title = get_string('submissionstartdatetime', 'workshop', workshop::timestamp_formats($workshop->submissionstart));
2974 $task->completed = 'info';
2975 $phase->tasks['submissionstartdatetime'] = $task;
2977 if ($workshop->submissionend) {
2978 $task = new stdclass();
2979 $task->title = get_string('submissionenddatetime', 'workshop', workshop::timestamp_formats($workshop->submissionend));
2980 $task->completed = 'info';
2981 $phase->tasks['submissionenddatetime'] = $task;
2983 if (($workshop->submissionstart < time()) and $workshop->latesubmissions) {
2984 $task = new stdclass();
2985 $task->title = get_string('latesubmissionsallowed', 'workshop');
2986 $task->completed = 'info';
2987 $phase->tasks['latesubmissionsallowed'] = $task;
2989 if (isset($phase->tasks['submissionstartdatetime']) or isset($phase->tasks['submissionenddatetime'])) {
2990 if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
2991 $task = new stdclass();
2992 $task->title = get_string('deadlinesignored', 'workshop');
2993 $task->completed = 'info';
2994 $phase->tasks['deadlinesignored'] = $task;
2997 $this->phases[workshop::PHASE_SUBMISSION] = $phase;
2999 //---------------------------------------------------------
3000 // setup | submission | * ASSESSMENT | evaluation | closed
3001 //---------------------------------------------------------
3002 $phase = new stdclass();
3003 $phase->title = get_string('phaseassessment', 'workshop');
3004 $phase->tasks = array();
3005 $phase->isreviewer = has_capability('mod/workshop:peerassess', $workshop->context, $userid);
3006 if ($workshop->phase == workshop::PHASE_SUBMISSION and $workshop->phaseswitchassessment
3007 and has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
3008 $task = new stdClass();
3009 $task->title = get_string('switchphase30auto', 'mod_workshop', workshop::timestamp_formats($workshop->submissionend));
3010 $task->completed = 'info';
3011 $phase->tasks['autoswitchinfo'] = $task;
3013 if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_ASSESSMENT
3014 and $phase->isreviewer and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
3015 $task = new stdclass();
3016 $task->title = get_string('exampleassesstask', 'workshop');
3017 $examples = $workshop->get_examples_for_reviewer($userid);
3018 $a = new stdclass();
3019 $a->expected = count($examples);
3020 $a->assessed = 0;
3021 foreach ($examples as $exampleid => $example) {
3022 if (!is_null($example->grade)) {
3023 $a->assessed++;
3026 $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
3027 if ($a->assessed == $a->expected) {
3028 $task->completed = true;
3029 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3030 $task->completed = false;
3032 $phase->tasks['examples'] = $task;
3034 if (empty($phase->tasks['examples']) or !empty($phase->tasks['examples']->completed)) {
3035 $phase->assessments = $workshop->get_assessments_by_reviewer($userid);
3036 $numofpeers = 0; // number of allocated peer-assessments
3037 $numofpeerstodo = 0; // number of peer-assessments to do
3038 $numofself = 0; // number of allocated self-assessments - should be 0 or 1
3039 $numofselftodo = 0; // number of self-assessments to do - should be 0 or 1
3040 foreach ($phase->assessments as $a) {
3041 if ($a->authorid == $userid) {
3042 $numofself++;
3043 if (is_null($a->grade)) {
3044 $numofselftodo++;
3046 } else {
3047 $numofpeers++;
3048 if (is_null($a->grade)) {
3049 $numofpeerstodo++;
3053 unset($a);
3054 if ($numofpeers) {
3055 $task = new stdclass();
3056 if ($numofpeerstodo == 0) {
3057 $task->completed = true;
3058 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3059 $task->completed = false;
3061 $a = new stdclass();
3062 $a->total = $numofpeers;
3063 $a->todo = $numofpeerstodo;
3064 $task->title = get_string('taskassesspeers', 'workshop');
3065 $task->details = get_string('taskassesspeersdetails', 'workshop', $a);
3066 unset($a);
3067 $phase->tasks['assesspeers'] = $task;
3069 if ($workshop->useselfassessment and $numofself) {
3070 $task = new stdclass();
3071 if ($numofselftodo == 0) {
3072 $task->completed = true;
3073 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3074 $task->completed = false;
3076 $task->title = get_string('taskassessself', 'workshop');
3077 $phase->tasks['assessself'] = $task;
3080 if ($workshop->assessmentstart) {
3081 $task = new stdclass();
3082 $task->title = get_string('assessmentstartdatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentstart));
3083 $task->completed = 'info';
3084 $phase->tasks['assessmentstartdatetime'] = $task;
3086 if ($workshop->assessmentend) {
3087 $task = new stdclass();
3088 $task->title = get_string('assessmentenddatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentend));
3089 $task->completed = 'info';
3090 $phase->tasks['assessmentenddatetime'] = $task;
3092 if (isset($phase->tasks['assessmentstartdatetime']) or isset($phase->tasks['assessmentenddatetime'])) {
3093 if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
3094 $task = new stdclass();
3095 $task->title = get_string('deadlinesignored', 'workshop');
3096 $task->completed = 'info';
3097 $phase->tasks['deadlinesignored'] = $task;
3100 $this->phases[workshop::PHASE_ASSESSMENT] = $phase;
3102 //---------------------------------------------------------
3103 // setup | submission | assessment | * EVALUATION | closed
3104 //---------------------------------------------------------
3105 $phase = new stdclass();
3106 $phase->title = get_string('phaseevaluation', 'workshop');
3107 $phase->tasks = array();
3108 if (has_capability('mod/workshop:overridegrades', $workshop->context)) {
3109 $expected = $workshop->count_potential_authors(false);
3110 $calculated = $DB->count_records_select('workshop_submissions',
3111 'workshopid = ? AND (grade IS NOT NULL OR gradeover IS NOT NULL)', array($workshop->id));
3112 $task = new stdclass();
3113 $task->title = get_string('calculatesubmissiongrades', 'workshop');
3114 $a = new stdclass();
3115 $a->expected = $expected;
3116 $a->calculated = $calculated;
3117 $task->details = get_string('calculatesubmissiongradesdetails', 'workshop', $a);
3118 if ($calculated >= $expected) {
3119 $task->completed = true;
3120 } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
3121 $task->completed = false;
3123 $phase->tasks['calculatesubmissiongrade'] = $task;
3125 $expected = $workshop->count_potential_reviewers(false);
3126 $calculated = $DB->count_records_select('workshop_aggregations',
3127 'workshopid = ? AND gradinggrade IS NOT NULL', array($workshop->id));
3128 $task = new stdclass();
3129 $task->title = get_string('calculategradinggrades', 'workshop');
3130 $a = new stdclass();
3131 $a->expected = $expected;
3132 $a->calculated = $calculated;
3133 $task->details = get_string('calculategradinggradesdetails', 'workshop', $a);
3134 if ($calculated >= $expected) {
3135 $task->completed = true;
3136 } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
3137 $task->completed = false;
3139 $phase->tasks['calculategradinggrade'] = $task;
3141 } elseif ($workshop->phase == workshop::PHASE_EVALUATION) {
3142 $task = new stdclass();
3143 $task->title = get_string('evaluategradeswait', 'workshop');
3144 $task->completed = 'info';
3145 $phase->tasks['evaluateinfo'] = $task;
3148 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3149 $task = new stdclass();
3150 $task->title = get_string('taskconclusion', 'workshop');
3151 $task->link = $workshop->updatemod_url();
3152 if (trim($workshop->conclusion)) {
3153 $task->completed = true;
3154 } elseif ($workshop->phase >= workshop::PHASE_EVALUATION) {
3155 $task->completed = false;
3157 $phase->tasks['conclusion'] = $task;
3160 $this->phases[workshop::PHASE_EVALUATION] = $phase;
3162 //---------------------------------------------------------
3163 // setup | submission | assessment | evaluation | * CLOSED
3164 //---------------------------------------------------------
3165 $phase = new stdclass();
3166 $phase->title = get_string('phaseclosed', 'workshop');
3167 $phase->tasks = array();
3168 $this->phases[workshop::PHASE_CLOSED] = $phase;
3170 // Polish data, set default values if not done explicitly
3171 foreach ($this->phases as $phasecode => $phase) {
3172 $phase->title = isset($phase->title) ? $phase->title : '';
3173 $phase->tasks = isset($phase->tasks) ? $phase->tasks : array();
3174 if ($phasecode == $workshop->phase) {
3175 $phase->active = true;
3176 } else {
3177 $phase->active = false;
3179 if (!isset($phase->actions)) {
3180 $phase->actions = array();
3183 foreach ($phase->tasks as $taskcode => $task) {
3184 $task->title = isset($task->title) ? $task->title : '';
3185 $task->link = isset($task->link) ? $task->link : null;
3186 $task->details = isset($task->details) ? $task->details : '';
3187 $task->completed = isset($task->completed) ? $task->completed : null;
3191 // Add phase switching actions
3192 if (has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
3193 foreach ($this->phases as $phasecode => $phase) {
3194 if (! $phase->active) {
3195 $action = new stdclass();
3196 $action->type = 'switchphase';
3197 $action->url = $workshop->switchphase_url($phasecode);
3198 $phase->actions[] = $action;
3205 * Returns example submissions to be assessed by the owner of the planner
3207 * This is here to cache the DB query because the same list is needed later in view.php
3209 * @see workshop::get_examples_for_reviewer() for the format of returned value
3210 * @return array
3212 public function get_examples() {
3213 if (is_null($this->examples)) {
3214 $this->examples = $this->workshop->get_examples_for_reviewer($this->userid);
3216 return $this->examples;
3221 * Common base class for submissions and example submissions rendering
3223 * Subclasses of this class convert raw submission record from
3224 * workshop_submissions table (as returned by {@see workshop::get_submission_by_id()}
3225 * for example) into renderable objects.
3227 abstract class workshop_submission_base {
3229 /** @var bool is the submission anonymous (i.e. contains author information) */
3230 protected $anonymous;
3232 /* @var array of columns from workshop_submissions that are assigned as properties */
3233 protected $fields = array();
3235 /** @var workshop */
3236 protected $workshop;
3239 * Copies the properties of the given database record into properties of $this instance
3241 * @param workshop $workshop
3242 * @param stdClass $submission full record
3243 * @param bool $showauthor show the author-related information
3244 * @param array $options additional properties
3246 public function __construct(workshop $workshop, stdClass $submission, $showauthor = false) {
3248 $this->workshop = $workshop;
3250 foreach ($this->fields as $field) {
3251 if (!property_exists($submission, $field)) {
3252 throw new coding_exception('Submission record must provide public property ' . $field);
3254 if (!property_exists($this, $field)) {
3255 throw new coding_exception('Renderable component must accept public property ' . $field);
3257 $this->{$field} = $submission->{$field};
3260 if ($showauthor) {
3261 $this->anonymous = false;
3262 } else {
3263 $this->anonymize();
3268 * Unsets all author-related properties so that the renderer does not have access to them
3270 * Usually this is called by the contructor but can be called explicitely, too.
3272 public function anonymize() {
3273 $authorfields = explode(',', user_picture::fields());
3274 foreach ($authorfields as $field) {
3275 $prefixedusernamefield = 'author' . $field;
3276 unset($this->{$prefixedusernamefield});
3278 $this->anonymous = true;
3282 * Does the submission object contain author-related information?
3284 * @return null|boolean
3286 public function is_anonymous() {
3287 return $this->anonymous;
3292 * Renderable object containing a basic set of information needed to display the submission summary
3294 * @see workshop_renderer::render_workshop_submission_summary
3296 class workshop_submission_summary extends workshop_submission_base implements renderable {
3298 /** @var int */
3299 public $id;
3300 /** @var string */
3301 public $title;
3302 /** @var string graded|notgraded */
3303 public $status;
3304 /** @var int */
3305 public $timecreated;
3306 /** @var int */
3307 public $timemodified;
3308 /** @var int */
3309 public $authorid;
3310 /** @var string */
3311 public $authorfirstname;
3312 /** @var string */
3313 public $authorlastname;
3314 /** @var string */
3315 public $authorfirstnamephonetic;
3316 /** @var string */
3317 public $authorlastnamephonetic;
3318 /** @var string */
3319 public $authormiddlename;
3320 /** @var string */
3321 public $authoralternatename;
3322 /** @var int */
3323 public $authorpicture;
3324 /** @var string */
3325 public $authorimagealt;
3326 /** @var string */
3327 public $authoremail;
3328 /** @var moodle_url to display submission */
3329 public $url;
3332 * @var array of columns from workshop_submissions that are assigned as properties
3333 * of instances of this class
3335 protected $fields = array(
3336 'id', 'title', 'timecreated', 'timemodified',
3337 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
3338 'authormiddlename', 'authoralternatename', 'authorpicture',
3339 'authorimagealt', 'authoremail');
3343 * Renderable object containing all the information needed to display the submission
3345 * @see workshop_renderer::render_workshop_submission()
3347 class workshop_submission extends workshop_submission_summary implements renderable {
3349 /** @var string */
3350 public $content;
3351 /** @var int */
3352 public $contentformat;
3353 /** @var bool */
3354 public $contenttrust;
3355 /** @var array */
3356 public $attachment;
3359 * @var array of columns from workshop_submissions that are assigned as properties
3360 * of instances of this class
3362 protected $fields = array(
3363 'id', 'title', 'timecreated', 'timemodified', 'content', 'contentformat', 'contenttrust',
3364 'attachment', 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
3365 'authormiddlename', 'authoralternatename', 'authorpicture', 'authorimagealt', 'authoremail');
3369 * Renderable object containing a basic set of information needed to display the example submission summary
3371 * @see workshop::prepare_example_summary()
3372 * @see workshop_renderer::render_workshop_example_submission_summary()
3374 class workshop_example_submission_summary extends workshop_submission_base implements renderable {
3376 /** @var int */
3377 public $id;
3378 /** @var string */
3379 public $title;
3380 /** @var string graded|notgraded */
3381 public $status;
3382 /** @var stdClass */
3383 public $gradeinfo;
3384 /** @var moodle_url */
3385 public $url;
3386 /** @var moodle_url */
3387 public $editurl;
3388 /** @var string */
3389 public $assesslabel;
3390 /** @var moodle_url */
3391 public $assessurl;
3392 /** @var bool must be set explicitly by the caller */
3393 public $editable = false;
3396 * @var array of columns from workshop_submissions that are assigned as properties
3397 * of instances of this class
3399 protected $fields = array('id', 'title');
3402 * Example submissions are always anonymous
3404 * @return true
3406 public function is_anonymous() {
3407 return true;
3412 * Renderable object containing all the information needed to display the example submission
3414 * @see workshop_renderer::render_workshop_example_submission()
3416 class workshop_example_submission extends workshop_example_submission_summary implements renderable {
3418 /** @var string */
3419 public $content;
3420 /** @var int */
3421 public $contentformat;
3422 /** @var bool */
3423 public $contenttrust;
3424 /** @var array */
3425 public $attachment;
3428 * @var array of columns from workshop_submissions that are assigned as properties
3429 * of instances of this class
3431 protected $fields = array('id', 'title', 'content', 'contentformat', 'contenttrust', 'attachment');
3436 * Common base class for assessments rendering
3438 * Subclasses of this class convert raw assessment record from
3439 * workshop_assessments table (as returned by {@see workshop::get_assessment_by_id()}
3440 * for example) into renderable objects.
3442 abstract class workshop_assessment_base {
3444 /** @var string the optional title of the assessment */
3445 public $title = '';
3447 /** @var workshop_assessment_form $form as returned by {@link workshop_strategy::get_assessment_form()} */
3448 public $form;
3450 /** @var moodle_url */
3451 public $url;
3453 /** @var float|null the real received grade */
3454 public $realgrade = null;
3456 /** @var float the real maximum grade */
3457 public $maxgrade;
3459 /** @var stdClass|null reviewer user info */
3460 public $reviewer = null;
3462 /** @var stdClass|null assessed submission's author user info */
3463 public $author = null;
3465 /** @var array of actions */
3466 public $actions = array();
3468 /* @var array of columns that are assigned as properties */
3469 protected $fields = array();
3471 /** @var workshop */
3472 protected $workshop;
3475 * Copies the properties of the given database record into properties of $this instance
3477 * The $options keys are: showreviewer, showauthor
3478 * @param workshop $workshop
3479 * @param stdClass $assessment full record
3480 * @param array $options additional properties
3482 public function __construct(workshop $workshop, stdClass $record, array $options = array()) {
3484 $this->workshop = $workshop;
3485 $this->validate_raw_record($record);
3487 foreach ($this->fields as $field) {
3488 if (!property_exists($record, $field)) {
3489 throw new coding_exception('Assessment record must provide public property ' . $field);
3491 if (!property_exists($this, $field)) {
3492 throw new coding_exception('Renderable component must accept public property ' . $field);
3494 $this->{$field} = $record->{$field};
3497 if (!empty($options['showreviewer'])) {
3498 $this->reviewer = user_picture::unalias($record, null, 'revieweridx', 'reviewer');
3501 if (!empty($options['showauthor'])) {
3502 $this->author = user_picture::unalias($record, null, 'authorid', 'author');
3507 * Adds a new action
3509 * @param moodle_url $url action URL
3510 * @param string $label action label
3511 * @param string $method get|post
3513 public function add_action(moodle_url $url, $label, $method = 'get') {
3515 $action = new stdClass();
3516 $action->url = $url;
3517 $action->label = $label;
3518 $action->method = $method;
3520 $this->actions[] = $action;
3524 * Makes sure that we can cook the renderable component from the passed raw database record
3526 * @param stdClass $assessment full assessment record
3527 * @throws coding_exception if the caller passed unexpected data
3529 protected function validate_raw_record(stdClass $record) {
3530 // nothing to do here
3536 * Represents a rendarable full assessment
3538 class workshop_assessment extends workshop_assessment_base implements renderable {
3540 /** @var int */
3541 public $id;
3543 /** @var int */
3544 public $submissionid;
3546 /** @var int */
3547 public $weight;
3549 /** @var int */
3550 public $timecreated;
3552 /** @var int */
3553 public $timemodified;
3555 /** @var float */
3556 public $grade;
3558 /** @var float */
3559 public $gradinggrade;
3561 /** @var float */
3562 public $gradinggradeover;
3564 /** @var string */
3565 public $feedbackauthor;
3567 /** @var int */
3568 public $feedbackauthorformat;
3570 /** @var int */
3571 public $feedbackauthorattachment;
3573 /** @var array */
3574 protected $fields = array('id', 'submissionid', 'weight', 'timecreated',
3575 'timemodified', 'grade', 'gradinggrade', 'gradinggradeover', 'feedbackauthor',
3576 'feedbackauthorformat', 'feedbackauthorattachment');
3579 * Format the overall feedback text content
3581 * False is returned if the overall feedback feature is disabled. Null is returned
3582 * if the overall feedback content has not been found. Otherwise, string with
3583 * formatted feedback text is returned.
3585 * @return string|bool|null
3587 public function get_overall_feedback_content() {
3589 if ($this->workshop->overallfeedbackmode == 0) {
3590 return false;
3593 if (trim($this->feedbackauthor) === '') {
3594 return null;
3597 $content = file_rewrite_pluginfile_urls($this->feedbackauthor, 'pluginfile.php', $this->workshop->context->id,
3598 'mod_workshop', 'overallfeedback_content', $this->id);
3599 $content = format_text($content, $this->feedbackauthorformat,
3600 array('overflowdiv' => true, 'context' => $this->workshop->context));
3602 return $content;
3606 * Prepares the list of overall feedback attachments
3608 * Returns false if overall feedback attachments are not allowed. Otherwise returns
3609 * list of attachments (may be empty).
3611 * @return bool|array of stdClass
3613 public function get_overall_feedback_attachments() {
3615 if ($this->workshop->overallfeedbackmode == 0) {
3616 return false;
3619 if ($this->workshop->overallfeedbackfiles == 0) {
3620 return false;
3623 if (empty($this->feedbackauthorattachment)) {
3624 return array();
3627 $attachments = array();
3628 $fs = get_file_storage();
3629 $files = $fs->get_area_files($this->workshop->context->id, 'mod_workshop', 'overallfeedback_attachment', $this->id);
3630 foreach ($files as $file) {
3631 if ($file->is_directory()) {
3632 continue;
3634 $filepath = $file->get_filepath();
3635 $filename = $file->get_filename();
3636 $fileurl = moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop',
3637 'overallfeedback_attachment', $this->id, $filepath, $filename, true);
3638 $previewurl = new moodle_url(moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop',
3639 'overallfeedback_attachment', $this->id, $filepath, $filename, false), array('preview' => 'bigthumb'));
3640 $attachments[] = (object)array(
3641 'filepath' => $filepath,
3642 'filename' => $filename,
3643 'fileurl' => $fileurl,
3644 'previewurl' => $previewurl,
3645 'mimetype' => $file->get_mimetype(),
3650 return $attachments;
3656 * Represents a renderable training assessment of an example submission
3658 class workshop_example_assessment extends workshop_assessment implements renderable {
3661 * @see parent::validate_raw_record()
3663 protected function validate_raw_record(stdClass $record) {
3664 if ($record->weight != 0) {
3665 throw new coding_exception('Invalid weight of example submission assessment');
3667 parent::validate_raw_record($record);
3673 * Represents a renderable reference assessment of an example submission
3675 class workshop_example_reference_assessment extends workshop_assessment implements renderable {
3678 * @see parent::validate_raw_record()
3680 protected function validate_raw_record(stdClass $record) {
3681 if ($record->weight != 1) {
3682 throw new coding_exception('Invalid weight of the reference example submission assessment');
3684 parent::validate_raw_record($record);
3690 * Renderable message to be displayed to the user
3692 * Message can contain an optional action link with a label that is supposed to be rendered
3693 * as a button or a link.
3695 * @see workshop::renderer::render_workshop_message()
3697 class workshop_message implements renderable {
3699 const TYPE_INFO = 10;
3700 const TYPE_OK = 20;
3701 const TYPE_ERROR = 30;
3703 /** @var string */
3704 protected $text = '';
3705 /** @var int */
3706 protected $type = self::TYPE_INFO;
3707 /** @var moodle_url */
3708 protected $actionurl = null;
3709 /** @var string */
3710 protected $actionlabel = '';
3713 * @param string $text short text to be displayed
3714 * @param string $type optional message type info|ok|error
3716 public function __construct($text = null, $type = self::TYPE_INFO) {
3717 $this->set_text($text);
3718 $this->set_type($type);
3722 * Sets the message text
3724 * @param string $text short text to be displayed
3726 public function set_text($text) {
3727 $this->text = $text;
3731 * Sets the message type
3733 * @param int $type
3735 public function set_type($type = self::TYPE_INFO) {
3736 if (in_array($type, array(self::TYPE_OK, self::TYPE_ERROR, self::TYPE_INFO))) {
3737 $this->type = $type;
3738 } else {
3739 throw new coding_exception('Unknown message type.');
3744 * Sets the optional message action
3746 * @param moodle_url $url to follow on action
3747 * @param string $label action label
3749 public function set_action(moodle_url $url, $label) {
3750 $this->actionurl = $url;
3751 $this->actionlabel = $label;
3755 * Returns message text with HTML tags quoted
3757 * @return string
3759 public function get_message() {
3760 return s($this->text);
3764 * Returns message type
3766 * @return int
3768 public function get_type() {
3769 return $this->type;
3773 * Returns action URL
3775 * @return moodle_url|null
3777 public function get_action_url() {
3778 return $this->actionurl;
3782 * Returns action label
3784 * @return string
3786 public function get_action_label() {
3787 return $this->actionlabel;
3793 * Renderable component containing all the data needed to display the grading report
3795 class workshop_grading_report implements renderable {
3797 /** @var stdClass returned by {@see workshop::prepare_grading_report_data()} */
3798 protected $data;
3799 /** @var stdClass rendering options */
3800 protected $options;
3803 * Grades in $data must be already rounded to the set number of decimals or must be null
3804 * (in which later case, the [mod_workshop,nullgrade] string shall be displayed)
3806 * @param stdClass $data prepared by {@link workshop::prepare_grading_report_data()}
3807 * @param stdClass $options display options (showauthornames, showreviewernames, sortby, sorthow, showsubmissiongrade, showgradinggrade)
3809 public function __construct(stdClass $data, stdClass $options) {
3810 $this->data = $data;
3811 $this->options = $options;
3815 * @return stdClass grading report data
3817 public function get_data() {
3818 return $this->data;
3822 * @return stdClass rendering options
3824 public function get_options() {
3825 return $this->options;
3831 * Base class for renderable feedback for author and feedback for reviewer
3833 abstract class workshop_feedback {
3835 /** @var stdClass the user info */
3836 protected $provider = null;
3838 /** @var string the feedback text */
3839 protected $content = null;
3841 /** @var int format of the feedback text */
3842 protected $format = null;
3845 * @return stdClass the user info
3847 public function get_provider() {
3849 if (is_null($this->provider)) {
3850 throw new coding_exception('Feedback provider not set');
3853 return $this->provider;
3857 * @return string the feedback text
3859 public function get_content() {
3861 if (is_null($this->content)) {
3862 throw new coding_exception('Feedback content not set');
3865 return $this->content;
3869 * @return int format of the feedback text
3871 public function get_format() {
3873 if (is_null($this->format)) {
3874 throw new coding_exception('Feedback text format not set');
3877 return $this->format;
3883 * Renderable feedback for the author of submission
3885 class workshop_feedback_author extends workshop_feedback implements renderable {
3888 * Extracts feedback from the given submission record
3890 * @param stdClass $submission record as returned by {@see self::get_submission_by_id()}
3892 public function __construct(stdClass $submission) {
3894 $this->provider = user_picture::unalias($submission, null, 'gradeoverbyx', 'gradeoverby');
3895 $this->content = $submission->feedbackauthor;
3896 $this->format = $submission->feedbackauthorformat;
3902 * Renderable feedback for the reviewer
3904 class workshop_feedback_reviewer extends workshop_feedback implements renderable {
3907 * Extracts feedback from the given assessment record
3909 * @param stdClass $assessment record as returned by eg {@see self::get_assessment_by_id()}
3911 public function __construct(stdClass $assessment) {
3913 $this->provider = user_picture::unalias($assessment, null, 'gradinggradeoverbyx', 'overby');
3914 $this->content = $assessment->feedbackreviewer;
3915 $this->format = $assessment->feedbackreviewerformat;
3921 * Holds the final grades for the activity as are stored in the gradebook
3923 class workshop_final_grades implements renderable {
3925 /** @var object the info from the gradebook about the grade for submission */
3926 public $submissiongrade = null;
3928 /** @var object the infor from the gradebook about the grade for assessment */
3929 public $assessmentgrade = null;