Merge branch 'MDL-34774_m24' of git://github.com/rwijaya/moodle into MOODLE_24_STABLE
[moodle.git] / mod / workshop / locallib.php
bloba534f4c5cd4a1d05def457c72fee1ddec14899cb
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
27 * @subpackage workshop
28 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') || die();
34 require_once(dirname(__FILE__).'/lib.php'); // we extend this library here
35 require_once($CFG->libdir . '/gradelib.php'); // we use some rounding and comparing routines here
36 require_once($CFG->libdir . '/filelib.php');
38 /**
39 * Full-featured workshop API
41 * This wraps the workshop database record with a set of methods that are called
42 * from the module itself. The class should be initialized right after you get
43 * $workshop, $cm and $course records at the begining of the script.
45 class workshop {
47 /** error status of the {@link self::add_allocation()} */
48 const ALLOCATION_EXISTS = -9999;
50 /** the internal code of the workshop phases as are stored in the database */
51 const PHASE_SETUP = 10;
52 const PHASE_SUBMISSION = 20;
53 const PHASE_ASSESSMENT = 30;
54 const PHASE_EVALUATION = 40;
55 const PHASE_CLOSED = 50;
57 /** the internal code of the examples modes as are stored in the database */
58 const EXAMPLES_VOLUNTARY = 0;
59 const EXAMPLES_BEFORE_SUBMISSION = 1;
60 const EXAMPLES_BEFORE_ASSESSMENT = 2;
62 /** @var stdclass course module record */
63 public $cm;
65 /** @var stdclass course record */
66 public $course;
68 /** @var stdclass context object */
69 public $context;
71 /** @var int workshop instance identifier */
72 public $id;
74 /** @var string workshop activity name */
75 public $name;
77 /** @var string introduction or description of the activity */
78 public $intro;
80 /** @var int format of the {@link $intro} */
81 public $introformat;
83 /** @var string instructions for the submission phase */
84 public $instructauthors;
86 /** @var int format of the {@link $instructauthors} */
87 public $instructauthorsformat;
89 /** @var string instructions for the assessment phase */
90 public $instructreviewers;
92 /** @var int format of the {@link $instructreviewers} */
93 public $instructreviewersformat;
95 /** @var int timestamp of when the module was modified */
96 public $timemodified;
98 /** @var int current phase of workshop, for example {@link workshop::PHASE_SETUP} */
99 public $phase;
101 /** @var bool optional feature: students practise evaluating on example submissions from teacher */
102 public $useexamples;
104 /** @var bool optional feature: students perform peer assessment of others' work */
105 public $usepeerassessment;
107 /** @var bool optional feature: students perform self assessment of their own work */
108 public $useselfassessment;
110 /** @var float number (10, 5) unsigned, the maximum grade for submission */
111 public $grade;
113 /** @var float number (10, 5) unsigned, the maximum grade for assessment */
114 public $gradinggrade;
116 /** @var string type of the current grading strategy used in this workshop, for example 'accumulative' */
117 public $strategy;
119 /** @var string the name of the evaluation plugin to use for grading grades calculation */
120 public $evaluation;
122 /** @var int number of digits that should be shown after the decimal point when displaying grades */
123 public $gradedecimals;
125 /** @var int number of allowed submission attachments and the files embedded into submission */
126 public $nattachments;
128 /** @var bool allow submitting the work after the deadline */
129 public $latesubmissions;
131 /** @var int maximum size of the one attached file in bytes */
132 public $maxbytes;
134 /** @var int mode of example submissions support, for example {@link workshop::EXAMPLES_VOLUNTARY} */
135 public $examplesmode;
137 /** @var int if greater than 0 then the submission is not allowed before this timestamp */
138 public $submissionstart;
140 /** @var int if greater than 0 then the submission is not allowed after this timestamp */
141 public $submissionend;
143 /** @var int if greater than 0 then the peer assessment is not allowed before this timestamp */
144 public $assessmentstart;
146 /** @var int if greater than 0 then the peer assessment is not allowed after this timestamp */
147 public $assessmentend;
149 /** @var bool automatically switch to the assessment phase after the submissions deadline */
150 public $phaseswitchassessment;
152 /** @var string conclusion text to be displayed at the end of the activity */
153 public $conclusion;
155 /** @var int format of the conclusion text */
156 public $conclusionformat;
159 * @var workshop_strategy grading strategy instance
160 * Do not use directly, get the instance using {@link workshop::grading_strategy_instance()}
162 protected $strategyinstance = null;
165 * @var workshop_evaluation grading evaluation instance
166 * Do not use directly, get the instance using {@link workshop::grading_evaluation_instance()}
168 protected $evaluationinstance = null;
171 * Initializes the workshop API instance using the data from DB
173 * Makes deep copy of all passed records properties. Replaces integer $course attribute
174 * with a full database record (course should not be stored in instances table anyway).
176 * @param stdClass $dbrecord Workshop instance data from {workshop} table
177 * @param stdClass $cm Course module record as returned by {@link get_coursemodule_from_id()}
178 * @param stdClass $course Course record from {course} table
179 * @param stdClass $context The context of the workshop instance
181 public function __construct(stdclass $dbrecord, stdclass $cm, stdclass $course, stdclass $context=null) {
182 foreach ($dbrecord as $field => $value) {
183 if (property_exists('workshop', $field)) {
184 $this->{$field} = $value;
187 $this->cm = $cm;
188 $this->course = $course;
189 if (is_null($context)) {
190 $this->context = context_module::instance($this->cm->id);
191 } else {
192 $this->context = $context;
196 ////////////////////////////////////////////////////////////////////////////////
197 // Static methods //
198 ////////////////////////////////////////////////////////////////////////////////
201 * Return list of available allocation methods
203 * @return array Array ['string' => 'string'] of localized allocation method names
205 public static function installed_allocators() {
206 $installed = get_plugin_list('workshopallocation');
207 $forms = array();
208 foreach ($installed as $allocation => $allocationpath) {
209 if (file_exists($allocationpath . '/lib.php')) {
210 $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation);
213 // usability - make sure that manual allocation appears the first
214 if (isset($forms['manual'])) {
215 $m = array('manual' => $forms['manual']);
216 unset($forms['manual']);
217 $forms = array_merge($m, $forms);
219 return $forms;
223 * Returns an array of options for the editors that are used for submitting and assessing instructions
225 * @param stdClass $context
226 * @uses EDITOR_UNLIMITED_FILES hard-coded value for the 'maxfiles' option
227 * @return array
229 public static function instruction_editors_options(stdclass $context) {
230 return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => -1,
231 'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0);
235 * Given the percent and the total, returns the number
237 * @param float $percent from 0 to 100
238 * @param float $total the 100% value
239 * @return float
241 public static function percent_to_value($percent, $total) {
242 if ($percent < 0 or $percent > 100) {
243 throw new coding_exception('The percent can not be less than 0 or higher than 100');
246 return $total * $percent / 100;
250 * Returns an array of numeric values that can be used as maximum grades
252 * @return array Array of integers
254 public static function available_maxgrades_list() {
255 $grades = array();
256 for ($i=100; $i>=0; $i--) {
257 $grades[$i] = $i;
259 return $grades;
263 * Returns the localized list of supported examples modes
265 * @return array
267 public static function available_example_modes_list() {
268 $options = array();
269 $options[self::EXAMPLES_VOLUNTARY] = get_string('examplesvoluntary', 'workshop');
270 $options[self::EXAMPLES_BEFORE_SUBMISSION] = get_string('examplesbeforesubmission', 'workshop');
271 $options[self::EXAMPLES_BEFORE_ASSESSMENT] = get_string('examplesbeforeassessment', 'workshop');
272 return $options;
276 * Returns the list of available grading strategy methods
278 * @return array ['string' => 'string']
280 public static function available_strategies_list() {
281 $installed = get_plugin_list('workshopform');
282 $forms = array();
283 foreach ($installed as $strategy => $strategypath) {
284 if (file_exists($strategypath . '/lib.php')) {
285 $forms[$strategy] = get_string('pluginname', 'workshopform_' . $strategy);
288 return $forms;
292 * Returns the list of available grading evaluation methods
294 * @return array of (string)name => (string)localized title
296 public static function available_evaluators_list() {
297 $evals = array();
298 foreach (get_plugin_list_with_file('workshopeval', 'lib.php', false) as $eval => $evalpath) {
299 $evals[$eval] = get_string('pluginname', 'workshopeval_' . $eval);
301 return $evals;
305 * Return an array of possible values of assessment dimension weight
307 * @return array of integers 0, 1, 2, ..., 16
309 public static function available_dimension_weights_list() {
310 $weights = array();
311 for ($i=16; $i>=0; $i--) {
312 $weights[$i] = $i;
314 return $weights;
318 * Return an array of possible values of assessment weight
320 * Note there is no real reason why the maximum value here is 16. It used to be 10 in
321 * workshop 1.x and I just decided to use the same number as in the maximum weight of
322 * a single assessment dimension.
323 * The value looks reasonable, though. Teachers who would want to assign themselves
324 * higher weight probably do not want peer assessment really...
326 * @return array of integers 0, 1, 2, ..., 16
328 public static function available_assessment_weights_list() {
329 $weights = array();
330 for ($i=16; $i>=0; $i--) {
331 $weights[$i] = $i;
333 return $weights;
337 * Helper function returning the greatest common divisor
339 * @param int $a
340 * @param int $b
341 * @return int
343 public static function gcd($a, $b) {
344 return ($b == 0) ? ($a):(self::gcd($b, $a % $b));
348 * Helper function returning the least common multiple
350 * @param int $a
351 * @param int $b
352 * @return int
354 public static function lcm($a, $b) {
355 return ($a / self::gcd($a,$b)) * $b;
359 * Returns an object suitable for strings containing dates/times
361 * The returned object contains properties date, datefullshort, datetime, ... containing the given
362 * timestamp formatted using strftimedate, strftimedatefullshort, strftimedatetime, ... from the
363 * current lang's langconfig.php
364 * This allows translators and administrators customize the date/time format.
366 * @param int $timestamp the timestamp in UTC
367 * @return stdclass
369 public static function timestamp_formats($timestamp) {
370 $formats = array('date', 'datefullshort', 'dateshort', 'datetime',
371 'datetimeshort', 'daydate', 'daydatetime', 'dayshort', 'daytime',
372 'monthyear', 'recent', 'recentfull', 'time');
373 $a = new stdclass();
374 foreach ($formats as $format) {
375 $a->{$format} = userdate($timestamp, get_string('strftime'.$format, 'langconfig'));
377 $day = userdate($timestamp, '%Y%m%d', 99, false);
378 $today = userdate(time(), '%Y%m%d', 99, false);
379 $tomorrow = userdate(time() + DAYSECS, '%Y%m%d', 99, false);
380 $yesterday = userdate(time() - DAYSECS, '%Y%m%d', 99, false);
381 $distance = (int)round(abs(time() - $timestamp) / DAYSECS);
382 if ($day == $today) {
383 $a->distanceday = get_string('daystoday', 'workshop');
384 } elseif ($day == $yesterday) {
385 $a->distanceday = get_string('daysyesterday', 'workshop');
386 } elseif ($day < $today) {
387 $a->distanceday = get_string('daysago', 'workshop', $distance);
388 } elseif ($day == $tomorrow) {
389 $a->distanceday = get_string('daystomorrow', 'workshop');
390 } elseif ($day > $today) {
391 $a->distanceday = get_string('daysleft', 'workshop', $distance);
393 return $a;
396 ////////////////////////////////////////////////////////////////////////////////
397 // Workshop API //
398 ////////////////////////////////////////////////////////////////////////////////
401 * Fetches all enrolled users with the capability mod/workshop:submit in the current workshop
403 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
404 * Only users with the active enrolment are returned.
406 * @param bool $musthavesubmission if true, return only users who have already submitted
407 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
408 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
409 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
410 * @return array array[userid] => stdClass
412 public function get_potential_authors($musthavesubmission=true, $groupid=0, $limitfrom=0, $limitnum=0) {
413 global $DB;
415 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
417 if (empty($sql)) {
418 return array();
421 list($sort, $sortparams) = users_order_by_sql('u');
422 $sql .= " ORDER BY $sort";
424 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
428 * Returns the total number of users that would be fetched by {@link self::get_potential_authors()}
430 * @param bool $musthavesubmission if true, count only users who have already submitted
431 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
432 * @return int
434 public function count_potential_authors($musthavesubmission=true, $groupid=0) {
435 global $DB;
437 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
439 if (empty($sql)) {
440 return 0;
443 $sql = "SELECT COUNT(*)
444 FROM ($sql) tmp";
446 return $DB->count_records_sql($sql, $params);
450 * Fetches all enrolled users with the capability mod/workshop:peerassess in the current workshop
452 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
453 * Only users with the active enrolment are returned.
455 * @param bool $musthavesubmission if true, return only users who have already submitted
456 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
457 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
458 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
459 * @return array array[userid] => stdClass
461 public function get_potential_reviewers($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
462 global $DB;
464 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
466 if (empty($sql)) {
467 return array();
470 list($sort, $sortparams) = users_order_by_sql('u');
471 $sql .= " ORDER BY $sort";
473 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
477 * Returns the total number of users that would be fetched by {@link self::get_potential_reviewers()}
479 * @param bool $musthavesubmission if true, count only users who have already submitted
480 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
481 * @return int
483 public function count_potential_reviewers($musthavesubmission=false, $groupid=0) {
484 global $DB;
486 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
488 if (empty($sql)) {
489 return 0;
492 $sql = "SELECT COUNT(*)
493 FROM ($sql) tmp";
495 return $DB->count_records_sql($sql, $params);
499 * Fetches all enrolled users that are authors or reviewers (or both) in the current workshop
501 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
502 * Only users with the active enrolment are returned.
504 * @see self::get_potential_authors()
505 * @see self::get_potential_reviewers()
506 * @param bool $musthavesubmission if true, return only users who have already submitted
507 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
508 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
509 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
510 * @return array array[userid] => stdClass
512 public function get_participants($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
513 global $DB;
515 list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
517 if (empty($sql)) {
518 return array();
521 list($sort, $sortparams) = users_order_by_sql();
522 $sql .= " ORDER BY $sort";
524 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
528 * Returns the total number of records that would be returned by {@link self::get_participants()}
530 * @param bool $musthavesubmission if true, return only users who have already submitted
531 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
532 * @return int
534 public function count_participants($musthavesubmission=false, $groupid=0) {
535 global $DB;
537 list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
539 if (empty($sql)) {
540 return 0;
543 $sql = "SELECT COUNT(*)
544 FROM ($sql) tmp";
546 return $DB->count_records_sql($sql, $params);
550 * Checks if the given user is an actively enrolled participant in the workshop
552 * @param int $userid, defaults to the current $USER
553 * @return boolean
555 public function is_participant($userid=null) {
556 global $USER, $DB;
558 if (is_null($userid)) {
559 $userid = $USER->id;
562 list($sql, $params) = $this->get_participants_sql();
564 if (empty($sql)) {
565 return false;
568 $sql = "SELECT COUNT(*)
569 FROM {user} uxx
570 JOIN ({$sql}) pxx ON uxx.id = pxx.id
571 WHERE uxx.id = :uxxid";
572 $params['uxxid'] = $userid;
574 if ($DB->count_records_sql($sql, $params)) {
575 return true;
578 return false;
582 * Groups the given users by the group membership
584 * This takes the module grouping settings into account. If "Available for group members only"
585 * is set, returns only groups withing the course module grouping. Always returns group [0] with
586 * all the given users.
588 * @param array $users array[userid] => stdclass{->id ->lastname ->firstname}
589 * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname}
591 public function get_grouped($users) {
592 global $DB;
593 global $CFG;
595 $grouped = array(); // grouped users to be returned
596 if (empty($users)) {
597 return $grouped;
599 if (!empty($CFG->enablegroupmembersonly) and $this->cm->groupmembersonly) {
600 // Available for group members only - the workshop is available only
601 // to users assigned to groups within the selected grouping, or to
602 // any group if no grouping is selected.
603 $groupingid = $this->cm->groupingid;
604 // All users that are members of at least one group will be
605 // added into a virtual group id 0
606 $grouped[0] = array();
607 } else {
608 $groupingid = 0;
609 // there is no need to be member of a group so $grouped[0] will contain
610 // all users
611 $grouped[0] = $users;
613 $gmemberships = groups_get_all_groups($this->cm->course, array_keys($users), $groupingid,
614 'gm.id,gm.groupid,gm.userid');
615 foreach ($gmemberships as $gmembership) {
616 if (!isset($grouped[$gmembership->groupid])) {
617 $grouped[$gmembership->groupid] = array();
619 $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid];
620 $grouped[0][$gmembership->userid] = $users[$gmembership->userid];
622 return $grouped;
626 * Returns the list of all allocations (i.e. assigned assessments) in the workshop
628 * Assessments of example submissions are ignored
630 * @return array
632 public function get_allocations() {
633 global $DB;
635 $sql = 'SELECT a.id, a.submissionid, a.reviewerid, s.authorid
636 FROM {workshop_assessments} a
637 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
638 WHERE s.example = 0 AND s.workshopid = :workshopid';
639 $params = array('workshopid' => $this->id);
641 return $DB->get_records_sql($sql, $params);
645 * Returns the total number of records that would be returned by {@link self::get_submissions()}
647 * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
648 * @param int $groupid If non-zero, return only submissions by authors in the specified group
649 * @return int number of records
651 public function count_submissions($authorid='all', $groupid=0) {
652 global $DB;
654 $params = array('workshopid' => $this->id);
655 $sql = "SELECT COUNT(s.id)
656 FROM {workshop_submissions} s
657 JOIN {user} u ON (s.authorid = u.id)";
658 if ($groupid) {
659 $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
660 $params['groupid'] = $groupid;
662 $sql .= " WHERE s.example = 0 AND s.workshopid = :workshopid";
664 if ('all' === $authorid) {
665 // no additional conditions
666 } elseif (!empty($authorid)) {
667 list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
668 $sql .= " AND authorid $usql";
669 $params = array_merge($params, $uparams);
670 } else {
671 // $authorid is empty
672 return 0;
675 return $DB->count_records_sql($sql, $params);
680 * Returns submissions from this workshop
682 * Fetches data from {workshop_submissions} and adds some useful information from other
683 * tables. Does not return textual fields to prevent possible memory lack issues.
685 * @see self::count_submissions()
686 * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
687 * @param int $groupid If non-zero, return only submissions by authors in the specified group
688 * @param int $limitfrom Return a subset of records, starting at this point (optional)
689 * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
690 * @return array of records or an empty array
692 public function get_submissions($authorid='all', $groupid=0, $limitfrom=0, $limitnum=0) {
693 global $DB;
695 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
696 $gradeoverbyfields = user_picture::fields('t', null, 'gradeoverbyx', 'over');
697 $params = array('workshopid' => $this->id);
698 $sql = "SELECT s.id, s.workshopid, s.example, s.authorid, s.timecreated, s.timemodified,
699 s.title, s.grade, s.gradeover, s.gradeoverby, s.published,
700 $authorfields, $gradeoverbyfields
701 FROM {workshop_submissions} s
702 JOIN {user} u ON (s.authorid = u.id)";
703 if ($groupid) {
704 $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
705 $params['groupid'] = $groupid;
707 $sql .= " LEFT JOIN {user} t ON (s.gradeoverby = t.id)
708 WHERE s.example = 0 AND s.workshopid = :workshopid";
710 if ('all' === $authorid) {
711 // no additional conditions
712 } elseif (!empty($authorid)) {
713 list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
714 $sql .= " AND authorid $usql";
715 $params = array_merge($params, $uparams);
716 } else {
717 // $authorid is empty
718 return array();
720 list($sort, $sortparams) = users_order_by_sql('u');
721 $sql .= " ORDER BY $sort";
723 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
727 * Returns a submission record with the author's data
729 * @param int $id submission id
730 * @return stdclass
732 public function get_submission_by_id($id) {
733 global $DB;
735 // we intentionally check the workshopid here, too, so the workshop can't touch submissions
736 // from other instances
737 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
738 $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
739 $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
740 FROM {workshop_submissions} s
741 INNER JOIN {user} u ON (s.authorid = u.id)
742 LEFT JOIN {user} g ON (s.gradeoverby = g.id)
743 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.id = :id";
744 $params = array('workshopid' => $this->id, 'id' => $id);
745 return $DB->get_record_sql($sql, $params, MUST_EXIST);
749 * Returns a submission submitted by the given author
751 * @param int $id author id
752 * @return stdclass|false
754 public function get_submission_by_author($authorid) {
755 global $DB;
757 if (empty($authorid)) {
758 return false;
760 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
761 $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
762 $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
763 FROM {workshop_submissions} s
764 INNER JOIN {user} u ON (s.authorid = u.id)
765 LEFT JOIN {user} g ON (s.gradeoverby = g.id)
766 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.authorid = :authorid";
767 $params = array('workshopid' => $this->id, 'authorid' => $authorid);
768 return $DB->get_record_sql($sql, $params);
772 * Returns published submissions with their authors data
774 * @return array of stdclass
776 public function get_published_submissions($orderby='finalgrade DESC') {
777 global $DB;
779 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
780 $sql = "SELECT s.id, s.authorid, s.timecreated, s.timemodified,
781 s.title, s.grade, s.gradeover, COALESCE(s.gradeover,s.grade) AS finalgrade,
782 $authorfields
783 FROM {workshop_submissions} s
784 INNER JOIN {user} u ON (s.authorid = u.id)
785 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.published = 1
786 ORDER BY $orderby";
787 $params = array('workshopid' => $this->id);
788 return $DB->get_records_sql($sql, $params);
792 * Returns full record of the given example submission
794 * @param int $id example submission od
795 * @return object
797 public function get_example_by_id($id) {
798 global $DB;
799 return $DB->get_record('workshop_submissions',
800 array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST);
804 * Returns the list of example submissions in this workshop with reference assessments attached
806 * @return array of objects or an empty array
807 * @see workshop::prepare_example_summary()
809 public function get_examples_for_manager() {
810 global $DB;
812 $sql = 'SELECT s.id, s.title,
813 a.id AS assessmentid, a.grade, a.gradinggrade
814 FROM {workshop_submissions} s
815 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.weight = 1)
816 WHERE s.example = 1 AND s.workshopid = :workshopid
817 ORDER BY s.title';
818 return $DB->get_records_sql($sql, array('workshopid' => $this->id));
822 * Returns the list of all example submissions in this workshop with the information of assessments done by the given user
824 * @param int $reviewerid user id
825 * @return array of objects, indexed by example submission id
826 * @see workshop::prepare_example_summary()
828 public function get_examples_for_reviewer($reviewerid) {
829 global $DB;
831 if (empty($reviewerid)) {
832 return false;
834 $sql = 'SELECT s.id, s.title,
835 a.id AS assessmentid, a.grade, a.gradinggrade
836 FROM {workshop_submissions} s
837 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.reviewerid = :reviewerid AND a.weight = 0)
838 WHERE s.example = 1 AND s.workshopid = :workshopid
839 ORDER BY s.title';
840 return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid));
844 * Prepares renderable submission component
846 * @param stdClass $record required by {@see workshop_submission}
847 * @param bool $showauthor show the author-related information
848 * @return workshop_submission
850 public function prepare_submission(stdClass $record, $showauthor = false) {
852 $submission = new workshop_submission($record, $showauthor);
853 $submission->url = $this->submission_url($record->id);
855 return $submission;
859 * Prepares renderable submission summary component
861 * @param stdClass $record required by {@see workshop_submission_summary}
862 * @param bool $showauthor show the author-related information
863 * @return workshop_submission_summary
865 public function prepare_submission_summary(stdClass $record, $showauthor = false) {
867 $summary = new workshop_submission_summary($record, $showauthor);
868 $summary->url = $this->submission_url($record->id);
870 return $summary;
874 * Prepares renderable example submission component
876 * @param stdClass $record required by {@see workshop_example_submission}
877 * @return workshop_example_submission
879 public function prepare_example_submission(stdClass $record) {
881 $example = new workshop_example_submission($record);
883 return $example;
887 * Prepares renderable example submission summary component
889 * If the example is editable, the caller must set the 'editable' flag explicitly.
891 * @param stdClass $example as returned by {@link workshop::get_examples_for_manager()} or {@link workshop::get_examples_for_reviewer()}
892 * @return workshop_example_submission_summary to be rendered
894 public function prepare_example_summary(stdClass $example) {
896 $summary = new workshop_example_submission_summary($example);
898 if (is_null($example->grade)) {
899 $summary->status = 'notgraded';
900 $summary->assesslabel = get_string('assess', 'workshop');
901 } else {
902 $summary->status = 'graded';
903 $summary->assesslabel = get_string('reassess', 'workshop');
906 $summary->gradeinfo = new stdclass();
907 $summary->gradeinfo->received = $this->real_grade($example->grade);
908 $summary->gradeinfo->max = $this->real_grade(100);
910 $summary->url = new moodle_url($this->exsubmission_url($example->id));
911 $summary->editurl = new moodle_url($this->exsubmission_url($example->id), array('edit' => 'on'));
912 $summary->assessurl = new moodle_url($this->exsubmission_url($example->id), array('assess' => 'on', 'sesskey' => sesskey()));
914 return $summary;
918 * Prepares renderable assessment component
920 * The $options array supports the following keys:
921 * showauthor - should the author user info be available for the renderer
922 * showreviewer - should the reviewer user info be available for the renderer
923 * showform - show the assessment form if it is available
924 * showweight - should the assessment weight be available for the renderer
926 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
927 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
928 * @param array $options
929 * @return workshop_assessment
931 public function prepare_assessment(stdClass $record, $form, array $options = array()) {
933 $assessment = new workshop_assessment($record, $options);
934 $assessment->url = $this->assess_url($record->id);
935 $assessment->maxgrade = $this->real_grade(100);
937 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
938 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
941 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
942 $assessment->form = $form;
945 if (empty($options['showweight'])) {
946 $assessment->weight = null;
949 if (!is_null($record->grade)) {
950 $assessment->realgrade = $this->real_grade($record->grade);
953 return $assessment;
957 * Prepares renderable example submission's assessment component
959 * The $options array supports the following keys:
960 * showauthor - should the author user info be available for the renderer
961 * showreviewer - should the reviewer user info be available for the renderer
962 * showform - show the assessment form if it is available
964 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
965 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
966 * @param array $options
967 * @return workshop_example_assessment
969 public function prepare_example_assessment(stdClass $record, $form = null, array $options = array()) {
971 $assessment = new workshop_example_assessment($record, $options);
972 $assessment->url = $this->exassess_url($record->id);
973 $assessment->maxgrade = $this->real_grade(100);
975 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
976 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
979 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
980 $assessment->form = $form;
983 if (!is_null($record->grade)) {
984 $assessment->realgrade = $this->real_grade($record->grade);
987 $assessment->weight = null;
989 return $assessment;
993 * Prepares renderable example submission's reference assessment component
995 * The $options array supports the following keys:
996 * showauthor - should the author user info be available for the renderer
997 * showreviewer - should the reviewer user info be available for the renderer
998 * showform - show the assessment form if it is available
1000 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1001 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1002 * @param array $options
1003 * @return workshop_example_reference_assessment
1005 public function prepare_example_reference_assessment(stdClass $record, $form = null, array $options = array()) {
1007 $assessment = new workshop_example_reference_assessment($record, $options);
1008 $assessment->maxgrade = $this->real_grade(100);
1010 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1011 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1014 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1015 $assessment->form = $form;
1018 if (!is_null($record->grade)) {
1019 $assessment->realgrade = $this->real_grade($record->grade);
1022 $assessment->weight = null;
1024 return $assessment;
1028 * Removes the submission and all relevant data
1030 * @param stdClass $submission record to delete
1031 * @return void
1033 public function delete_submission(stdclass $submission) {
1034 global $DB;
1035 $assessments = $DB->get_records('workshop_assessments', array('submissionid' => $submission->id), '', 'id');
1036 $this->delete_assessment(array_keys($assessments));
1037 $DB->delete_records('workshop_submissions', array('id' => $submission->id));
1041 * Returns the list of all assessments in the workshop with some data added
1043 * Fetches data from {workshop_assessments} and adds some useful information from other
1044 * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory
1045 * lack issues.
1047 * @return array [assessmentid] => assessment stdclass
1049 public function get_all_assessments() {
1050 global $DB;
1052 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1053 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1054 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1055 list($sort, $params) = users_order_by_sql('reviewer');
1056 $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified,
1057 a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby,
1058 $reviewerfields, $authorfields, $overbyfields,
1059 s.title
1060 FROM {workshop_assessments} a
1061 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1062 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1063 INNER JOIN {user} author ON (s.authorid = author.id)
1064 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1065 WHERE s.workshopid = :workshopid AND s.example = 0
1066 ORDER BY $sort";
1067 $params['workshopid'] = $this->id;
1069 return $DB->get_records_sql($sql, $params);
1073 * Get the complete information about the given assessment
1075 * @param int $id Assessment ID
1076 * @return stdclass
1078 public function get_assessment_by_id($id) {
1079 global $DB;
1081 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1082 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1083 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1084 $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1085 FROM {workshop_assessments} a
1086 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1087 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1088 INNER JOIN {user} author ON (s.authorid = author.id)
1089 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1090 WHERE a.id = :id AND s.workshopid = :workshopid";
1091 $params = array('id' => $id, 'workshopid' => $this->id);
1093 return $DB->get_record_sql($sql, $params, MUST_EXIST);
1097 * Get the complete information about the user's assessment of the given submission
1099 * @param int $sid submission ID
1100 * @param int $uid user ID of the reviewer
1101 * @return false|stdclass false if not found, stdclass otherwise
1103 public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
1104 global $DB;
1106 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1107 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1108 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1109 $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1110 FROM {workshop_assessments} a
1111 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1112 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1113 INNER JOIN {user} author ON (s.authorid = author.id)
1114 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1115 WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid";
1116 $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id);
1118 return $DB->get_record_sql($sql, $params, IGNORE_MISSING);
1122 * Get the complete information about all assessments of the given submission
1124 * @param int $submissionid
1125 * @return array
1127 public function get_assessments_of_submission($submissionid) {
1128 global $DB;
1130 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1131 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1132 list($sort, $params) = users_order_by_sql('reviewer');
1133 $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields
1134 FROM {workshop_assessments} a
1135 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1136 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1137 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1138 WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid
1139 ORDER BY $sort";
1140 $params['submissionid'] = $submissionid;
1141 $params['workshopid'] = $this->id;
1143 return $DB->get_records_sql($sql, $params);
1147 * Get the complete information about all assessments allocated to the given reviewer
1149 * @param int $reviewerid
1150 * @return array
1152 public function get_assessments_by_reviewer($reviewerid) {
1153 global $DB;
1155 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1156 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1157 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1158 $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields,
1159 s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated,
1160 s.timemodified AS submissionmodified
1161 FROM {workshop_assessments} a
1162 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1163 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1164 INNER JOIN {user} author ON (s.authorid = author.id)
1165 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1166 WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid";
1167 $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id);
1169 return $DB->get_records_sql($sql, $params);
1173 * Allocate a submission to a user for review
1175 * @param stdClass $submission Submission object with at least id property
1176 * @param int $reviewerid User ID
1177 * @param int $weight of the new assessment, from 0 to 16
1178 * @param bool $bulk repeated inserts into DB expected
1179 * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists
1181 public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
1182 global $DB;
1184 if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
1185 return self::ALLOCATION_EXISTS;
1188 $weight = (int)$weight;
1189 if ($weight < 0) {
1190 $weight = 0;
1192 if ($weight > 16) {
1193 $weight = 16;
1196 $now = time();
1197 $assessment = new stdclass();
1198 $assessment->submissionid = $submission->id;
1199 $assessment->reviewerid = $reviewerid;
1200 $assessment->timecreated = $now; // do not set timemodified here
1201 $assessment->weight = $weight;
1202 $assessment->generalcommentformat = editors_get_preferred_format();
1203 $assessment->feedbackreviewerformat = editors_get_preferred_format();
1205 return $DB->insert_record('workshop_assessments', $assessment, true, $bulk);
1209 * Delete assessment record or records
1211 * @param mixed $id int|array assessment id or array of assessments ids
1212 * @return bool false if $id not a valid parameter, true otherwise
1214 public function delete_assessment($id) {
1215 global $DB;
1217 // todo remove all given grades from workshop_grades;
1219 if (is_array($id)) {
1220 return $DB->delete_records_list('workshop_assessments', 'id', $id);
1221 } else {
1222 return $DB->delete_records('workshop_assessments', array('id' => $id));
1227 * Returns instance of grading strategy class
1229 * @return stdclass Instance of a grading strategy
1231 public function grading_strategy_instance() {
1232 global $CFG; // because we require other libs here
1234 if (is_null($this->strategyinstance)) {
1235 $strategylib = dirname(__FILE__) . '/form/' . $this->strategy . '/lib.php';
1236 if (is_readable($strategylib)) {
1237 require_once($strategylib);
1238 } else {
1239 throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
1241 $classname = 'workshop_' . $this->strategy . '_strategy';
1242 $this->strategyinstance = new $classname($this);
1243 if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) {
1244 throw new coding_exception($classname . ' does not implement workshop_strategy interface');
1247 return $this->strategyinstance;
1251 * Sets the current evaluation method to the given plugin.
1253 * @param string $method the name of the workshopeval subplugin
1254 * @return bool true if successfully set
1255 * @throws coding_exception if attempting to set a non-installed evaluation method
1257 public function set_grading_evaluation_method($method) {
1258 global $DB;
1260 $evaluationlib = dirname(__FILE__) . '/eval/' . $method . '/lib.php';
1262 if (is_readable($evaluationlib)) {
1263 $this->evaluationinstance = null;
1264 $this->evaluation = $method;
1265 $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id));
1266 return true;
1269 throw new coding_exception('Attempt to set a non-existing evaluation method.');
1273 * Returns instance of grading evaluation class
1275 * @return stdclass Instance of a grading evaluation
1277 public function grading_evaluation_instance() {
1278 global $CFG; // because we require other libs here
1280 if (is_null($this->evaluationinstance)) {
1281 if (empty($this->evaluation)) {
1282 $this->evaluation = 'best';
1284 $evaluationlib = dirname(__FILE__) . '/eval/' . $this->evaluation . '/lib.php';
1285 if (is_readable($evaluationlib)) {
1286 require_once($evaluationlib);
1287 } else {
1288 // Fall back in case the subplugin is not available.
1289 $this->evaluation = 'best';
1290 $evaluationlib = dirname(__FILE__) . '/eval/' . $this->evaluation . '/lib.php';
1291 if (is_readable($evaluationlib)) {
1292 require_once($evaluationlib);
1293 } else {
1294 // Fall back in case the subplugin is not available any more.
1295 throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
1298 $classname = 'workshop_' . $this->evaluation . '_evaluation';
1299 $this->evaluationinstance = new $classname($this);
1300 if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) {
1301 throw new coding_exception($classname . ' does not extend workshop_evaluation class');
1304 return $this->evaluationinstance;
1308 * Returns instance of submissions allocator
1310 * @param string $method The name of the allocation method, must be PARAM_ALPHA
1311 * @return stdclass Instance of submissions allocator
1313 public function allocator_instance($method) {
1314 global $CFG; // because we require other libs here
1316 $allocationlib = dirname(__FILE__) . '/allocation/' . $method . '/lib.php';
1317 if (is_readable($allocationlib)) {
1318 require_once($allocationlib);
1319 } else {
1320 throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
1322 $classname = 'workshop_' . $method . '_allocator';
1323 return new $classname($this);
1327 * @return moodle_url of this workshop's view page
1329 public function view_url() {
1330 global $CFG;
1331 return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
1335 * @return moodle_url of the page for editing this workshop's grading form
1337 public function editform_url() {
1338 global $CFG;
1339 return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
1343 * @return moodle_url of the page for previewing this workshop's grading form
1345 public function previewform_url() {
1346 global $CFG;
1347 return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
1351 * @param int $assessmentid The ID of assessment record
1352 * @return moodle_url of the assessment page
1354 public function assess_url($assessmentid) {
1355 global $CFG;
1356 $assessmentid = clean_param($assessmentid, PARAM_INT);
1357 return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
1361 * @param int $assessmentid The ID of assessment record
1362 * @return moodle_url of the example assessment page
1364 public function exassess_url($assessmentid) {
1365 global $CFG;
1366 $assessmentid = clean_param($assessmentid, PARAM_INT);
1367 return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
1371 * @return moodle_url of the page to view a submission, defaults to the own one
1373 public function submission_url($id=null) {
1374 global $CFG;
1375 return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
1379 * @param int $id example submission id
1380 * @return moodle_url of the page to view an example submission
1382 public function exsubmission_url($id) {
1383 global $CFG;
1384 return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
1388 * @param int $sid submission id
1389 * @param array $aid of int assessment ids
1390 * @return moodle_url of the page to compare assessments of the given submission
1392 public function compare_url($sid, array $aids) {
1393 global $CFG;
1395 $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
1396 $i = 0;
1397 foreach ($aids as $aid) {
1398 $url->param("aid{$i}", $aid);
1399 $i++;
1401 return $url;
1405 * @param int $sid submission id
1406 * @param int $aid assessment id
1407 * @return moodle_url of the page to compare the reference assessments of the given example submission
1409 public function excompare_url($sid, $aid) {
1410 global $CFG;
1411 return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
1415 * @return moodle_url of the mod_edit form
1417 public function updatemod_url() {
1418 global $CFG;
1419 return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
1423 * @param string $method allocation method
1424 * @return moodle_url to the allocation page
1426 public function allocation_url($method=null) {
1427 global $CFG;
1428 $params = array('cmid' => $this->cm->id);
1429 if (!empty($method)) {
1430 $params['method'] = $method;
1432 return new moodle_url('/mod/workshop/allocation.php', $params);
1436 * @param int $phasecode The internal phase code
1437 * @return moodle_url of the script to change the current phase to $phasecode
1439 public function switchphase_url($phasecode) {
1440 global $CFG;
1441 $phasecode = clean_param($phasecode, PARAM_INT);
1442 return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
1446 * @return moodle_url to the aggregation page
1448 public function aggregate_url() {
1449 global $CFG;
1450 return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
1454 * @return moodle_url of this workshop's toolbox page
1456 public function toolbox_url($tool) {
1457 global $CFG;
1458 return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
1462 * Workshop wrapper around {@see add_to_log()}
1464 * @param string $action to be logged
1465 * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends
1466 * @param mixed $info additional info, usually id in a table
1468 public function log($action, moodle_url $url = null, $info = null) {
1470 if (is_null($url)) {
1471 $url = $this->view_url();
1474 if (is_null($info)) {
1475 $info = $this->id;
1478 $logurl = $this->log_convert_url($url);
1479 add_to_log($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
1483 * Is the given user allowed to create their submission?
1485 * @param int $userid
1486 * @return bool
1488 public function creating_submission_allowed($userid) {
1490 $now = time();
1491 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1493 if ($this->latesubmissions) {
1494 if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) {
1495 // late submissions are allowed in the submission and assessment phase only
1496 return false;
1498 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1499 // late submissions are not allowed before the submission start
1500 return false;
1502 return true;
1504 } else {
1505 if ($this->phase != self::PHASE_SUBMISSION) {
1506 // submissions are allowed during the submission phase only
1507 return false;
1509 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1510 // if enabled, submitting is not allowed before the date/time defined in the mod_form
1511 return false;
1513 if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) {
1514 // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed
1515 return false;
1517 return true;
1522 * Is the given user allowed to modify their existing submission?
1524 * @param int $userid
1525 * @return bool
1527 public function modifying_submission_allowed($userid) {
1529 $now = time();
1530 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1532 if ($this->phase != self::PHASE_SUBMISSION) {
1533 // submissions can be edited during the submission phase only
1534 return false;
1536 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1537 // if enabled, re-submitting is not allowed before the date/time defined in the mod_form
1538 return false;
1540 if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) {
1541 // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed
1542 return false;
1544 return true;
1548 * Is the given reviewer allowed to create/edit their assessments?
1550 * @param int $userid
1551 * @return bool
1553 public function assessing_allowed($userid) {
1555 if ($this->phase != self::PHASE_ASSESSMENT) {
1556 // assessing is allowed in the assessment phase only, unless the user is a teacher
1557 // providing additional assessment during the evaluation phase
1558 if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) {
1559 return false;
1563 $now = time();
1564 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1566 if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) {
1567 // if enabled, assessing is not allowed before the date/time defined in the mod_form
1568 return false;
1570 if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) {
1571 // if enabled, assessing is not allowed after the date/time defined in the mod_form
1572 return false;
1574 // here we go, assessing is allowed
1575 return true;
1579 * Are reviewers allowed to create/edit their assessments of the example submissions?
1581 * Returns null if example submissions are not enabled in this workshop. Otherwise returns
1582 * true or false. Note this does not check other conditions like the number of already
1583 * assessed examples, examples mode etc.
1585 * @return null|bool
1587 public function assessing_examples_allowed() {
1588 if (empty($this->useexamples)) {
1589 return null;
1591 if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
1592 return true;
1594 if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
1595 return true;
1597 if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
1598 return true;
1600 return false;
1604 * Are the peer-reviews available to the authors?
1606 * @return bool
1608 public function assessments_available() {
1609 return $this->phase == self::PHASE_CLOSED;
1613 * Switch to a new workshop phase
1615 * Modifies the underlying database record. You should terminate the script shortly after calling this.
1617 * @param int $newphase new phase code
1618 * @return bool true if success, false otherwise
1620 public function switch_phase($newphase) {
1621 global $DB;
1623 $known = $this->available_phases_list();
1624 if (!isset($known[$newphase])) {
1625 return false;
1628 if (self::PHASE_CLOSED == $newphase) {
1629 // push the grades into the gradebook
1630 $workshop = new stdclass();
1631 foreach ($this as $property => $value) {
1632 $workshop->{$property} = $value;
1634 $workshop->course = $this->course->id;
1635 $workshop->cmidnumber = $this->cm->id;
1636 $workshop->modname = 'workshop';
1637 workshop_update_grades($workshop);
1640 $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
1641 $this->phase = $newphase;
1642 return true;
1646 * Saves a raw grade for submission as calculated from the assessment form fields
1648 * @param array $assessmentid assessment record id, must exists
1649 * @param mixed $grade raw percentual grade from 0.00000 to 100.00000
1650 * @return false|float the saved grade
1652 public function set_peer_grade($assessmentid, $grade) {
1653 global $DB;
1655 if (is_null($grade)) {
1656 return false;
1658 $data = new stdclass();
1659 $data->id = $assessmentid;
1660 $data->grade = $grade;
1661 $data->timemodified = time();
1662 $DB->update_record('workshop_assessments', $data);
1663 return $grade;
1667 * Prepares data object with all workshop grades to be rendered
1669 * @param int $userid the user we are preparing the report for
1670 * @param int $groupid if non-zero, prepare the report for the given group only
1671 * @param int $page the current page (for the pagination)
1672 * @param int $perpage participants per page (for the pagination)
1673 * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
1674 * @param string $sorthow ASC|DESC
1675 * @return stdclass data for the renderer
1677 public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
1678 global $DB;
1680 $canviewall = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
1681 $isparticipant = $this->is_participant($userid);
1683 if (!$canviewall and !$isparticipant) {
1684 // who the hell is this?
1685 return array();
1688 if (!in_array($sortby, array('lastname','firstname','submissiontitle','submissiongrade','gradinggrade'))) {
1689 $sortby = 'lastname';
1692 if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
1693 $sorthow = 'ASC';
1696 // get the list of user ids to be displayed
1697 if ($canviewall) {
1698 $participants = $this->get_participants(false, $groupid);
1699 } else {
1700 // this is an ordinary workshop participant (aka student) - display the report just for him/her
1701 $participants = array($userid => (object)array('id' => $userid));
1704 // we will need to know the number of all records later for the pagination purposes
1705 $numofparticipants = count($participants);
1707 if ($numofparticipants > 0) {
1708 // load all fields which can be used for sorting and paginate the records
1709 list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1710 $params['workshopid1'] = $this->id;
1711 $params['workshopid2'] = $this->id;
1712 $sqlsort = array();
1713 $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
1714 foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
1715 $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
1717 $sqlsort = implode(',', $sqlsort);
1718 $sql = "SELECT u.id AS userid,u.firstname,u.lastname,u.picture,u.imagealt,u.email,
1719 s.title AS submissiontitle, s.grade AS submissiongrade, ag.gradinggrade
1720 FROM {user} u
1721 LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)
1722 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)
1723 WHERE u.id $participantids
1724 ORDER BY $sqlsort";
1725 $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1726 } else {
1727 $participants = array();
1730 // this will hold the information needed to display user names and pictures
1731 $userinfo = array();
1733 // get the user details for all participants to display
1734 foreach ($participants as $participant) {
1735 if (!isset($userinfo[$participant->userid])) {
1736 $userinfo[$participant->userid] = new stdclass();
1737 $userinfo[$participant->userid]->id = $participant->userid;
1738 $userinfo[$participant->userid]->firstname = $participant->firstname;
1739 $userinfo[$participant->userid]->lastname = $participant->lastname;
1740 $userinfo[$participant->userid]->picture = $participant->picture;
1741 $userinfo[$participant->userid]->imagealt = $participant->imagealt;
1742 $userinfo[$participant->userid]->email = $participant->email;
1746 // load the submissions details
1747 $submissions = $this->get_submissions(array_keys($participants));
1749 // get the user details for all moderators (teachers) that have overridden a submission grade
1750 foreach ($submissions as $submission) {
1751 if (!isset($userinfo[$submission->gradeoverby])) {
1752 $userinfo[$submission->gradeoverby] = new stdclass();
1753 $userinfo[$submission->gradeoverby]->id = $submission->gradeoverby;
1754 $userinfo[$submission->gradeoverby]->firstname = $submission->overfirstname;
1755 $userinfo[$submission->gradeoverby]->lastname = $submission->overlastname;
1756 $userinfo[$submission->gradeoverby]->picture = $submission->overpicture;
1757 $userinfo[$submission->gradeoverby]->imagealt = $submission->overimagealt;
1758 $userinfo[$submission->gradeoverby]->email = $submission->overemail;
1762 // get the user details for all reviewers of the displayed participants
1763 $reviewers = array();
1764 if ($submissions) {
1765 list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
1766 list($sort, $sortparams) = users_order_by_sql('r');
1767 $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,
1768 r.id AS reviewerid, r.lastname, r.firstname, r.picture, r.imagealt, r.email,
1769 s.id AS submissionid, s.authorid
1770 FROM {workshop_assessments} a
1771 JOIN {user} r ON (a.reviewerid = r.id)
1772 JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1773 WHERE a.submissionid $submissionids
1774 ORDER BY a.weight DESC, $sort";
1775 $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
1776 foreach ($reviewers as $reviewer) {
1777 if (!isset($userinfo[$reviewer->reviewerid])) {
1778 $userinfo[$reviewer->reviewerid] = new stdclass();
1779 $userinfo[$reviewer->reviewerid]->id = $reviewer->reviewerid;
1780 $userinfo[$reviewer->reviewerid]->firstname = $reviewer->firstname;
1781 $userinfo[$reviewer->reviewerid]->lastname = $reviewer->lastname;
1782 $userinfo[$reviewer->reviewerid]->picture = $reviewer->picture;
1783 $userinfo[$reviewer->reviewerid]->imagealt = $reviewer->imagealt;
1784 $userinfo[$reviewer->reviewerid]->email = $reviewer->email;
1789 // get the user details for all reviewees of the displayed participants
1790 $reviewees = array();
1791 if ($participants) {
1792 list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1793 list($sort, $sortparams) = users_order_by_sql('e');
1794 $params['workshopid'] = $this->id;
1795 $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,
1796 s.id AS submissionid,
1797 e.id AS authorid, e.lastname, e.firstname, e.picture, e.imagealt, e.email
1798 FROM {user} u
1799 JOIN {workshop_assessments} a ON (a.reviewerid = u.id)
1800 JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1801 JOIN {user} e ON (s.authorid = e.id)
1802 WHERE u.id $participantids AND s.workshopid = :workshopid
1803 ORDER BY a.weight DESC, $sort";
1804 $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
1805 foreach ($reviewees as $reviewee) {
1806 if (!isset($userinfo[$reviewee->authorid])) {
1807 $userinfo[$reviewee->authorid] = new stdclass();
1808 $userinfo[$reviewee->authorid]->id = $reviewee->authorid;
1809 $userinfo[$reviewee->authorid]->firstname = $reviewee->firstname;
1810 $userinfo[$reviewee->authorid]->lastname = $reviewee->lastname;
1811 $userinfo[$reviewee->authorid]->picture = $reviewee->picture;
1812 $userinfo[$reviewee->authorid]->imagealt = $reviewee->imagealt;
1813 $userinfo[$reviewee->authorid]->email = $reviewee->email;
1818 // finally populate the object to be rendered
1819 $grades = $participants;
1821 foreach ($participants as $participant) {
1822 // set up default (null) values
1823 $grades[$participant->userid]->submissionid = null;
1824 $grades[$participant->userid]->submissiontitle = null;
1825 $grades[$participant->userid]->submissiongrade = null;
1826 $grades[$participant->userid]->submissiongradeover = null;
1827 $grades[$participant->userid]->submissiongradeoverby = null;
1828 $grades[$participant->userid]->submissionpublished = null;
1829 $grades[$participant->userid]->reviewedby = array();
1830 $grades[$participant->userid]->reviewerof = array();
1832 unset($participants);
1833 unset($participant);
1835 foreach ($submissions as $submission) {
1836 $grades[$submission->authorid]->submissionid = $submission->id;
1837 $grades[$submission->authorid]->submissiontitle = $submission->title;
1838 $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
1839 $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
1840 $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
1841 $grades[$submission->authorid]->submissionpublished = $submission->published;
1843 unset($submissions);
1844 unset($submission);
1846 foreach($reviewers as $reviewer) {
1847 $info = new stdclass();
1848 $info->userid = $reviewer->reviewerid;
1849 $info->assessmentid = $reviewer->assessmentid;
1850 $info->submissionid = $reviewer->submissionid;
1851 $info->grade = $this->real_grade($reviewer->grade);
1852 $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
1853 $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
1854 $info->weight = $reviewer->weight;
1855 $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
1857 unset($reviewers);
1858 unset($reviewer);
1860 foreach($reviewees as $reviewee) {
1861 $info = new stdclass();
1862 $info->userid = $reviewee->authorid;
1863 $info->assessmentid = $reviewee->assessmentid;
1864 $info->submissionid = $reviewee->submissionid;
1865 $info->grade = $this->real_grade($reviewee->grade);
1866 $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
1867 $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
1868 $info->weight = $reviewee->weight;
1869 $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
1871 unset($reviewees);
1872 unset($reviewee);
1874 foreach ($grades as $grade) {
1875 $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
1878 $data = new stdclass();
1879 $data->grades = $grades;
1880 $data->userinfo = $userinfo;
1881 $data->totalcount = $numofparticipants;
1882 $data->maxgrade = $this->real_grade(100);
1883 $data->maxgradinggrade = $this->real_grading_grade(100);
1884 return $data;
1888 * Calculates the real value of a grade
1890 * @param float $value percentual value from 0 to 100
1891 * @param float $max the maximal grade
1892 * @return string
1894 public function real_grade_value($value, $max) {
1895 $localized = true;
1896 if (is_null($value) or $value === '') {
1897 return null;
1898 } elseif ($max == 0) {
1899 return 0;
1900 } else {
1901 return format_float($max * $value / 100, $this->gradedecimals, $localized);
1906 * Calculates the raw (percentual) value from a real grade
1908 * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save
1909 * this value in a raw percentual form into DB
1910 * @param float $value given grade
1911 * @param float $max the maximal grade
1912 * @return float suitable to be stored as numeric(10,5)
1914 public function raw_grade_value($value, $max) {
1915 if (is_null($value) or $value === '') {
1916 return null;
1918 if ($max == 0 or $value < 0) {
1919 return 0;
1921 $p = $value / $max * 100;
1922 if ($p > 100) {
1923 return $max;
1925 return grade_floatval($p);
1929 * Calculates the real value of grade for submission
1931 * @param float $value percentual value from 0 to 100
1932 * @return string
1934 public function real_grade($value) {
1935 return $this->real_grade_value($value, $this->grade);
1939 * Calculates the real value of grade for assessment
1941 * @param float $value percentual value from 0 to 100
1942 * @return string
1944 public function real_grading_grade($value) {
1945 return $this->real_grade_value($value, $this->gradinggrade);
1949 * Sets the given grades and received grading grades to null
1951 * This does not clear the information about how the peers filled the assessment forms, but
1952 * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess
1953 * the allocated submissions.
1955 * @return void
1957 public function clear_assessments() {
1958 global $DB;
1960 $submissions = $this->get_submissions();
1961 if (empty($submissions)) {
1962 // no money, no love
1963 return;
1965 $submissions = array_keys($submissions);
1966 list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED);
1967 $sql = "submissionid $sql";
1968 $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params);
1969 $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params);
1973 * Sets the grades for submission to null
1975 * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
1976 * @return void
1978 public function clear_submission_grades($restrict=null) {
1979 global $DB;
1981 $sql = "workshopid = :workshopid AND example = 0";
1982 $params = array('workshopid' => $this->id);
1984 if (is_null($restrict)) {
1985 // update all users - no more conditions
1986 } elseif (!empty($restrict)) {
1987 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
1988 $sql .= " AND authorid $usql";
1989 $params = array_merge($params, $uparams);
1990 } else {
1991 throw new coding_exception('Empty value is not a valid parameter here');
1994 $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
1998 * Calculates grades for submission for the given participant(s) and updates it in the database
2000 * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2001 * @return void
2003 public function aggregate_submission_grades($restrict=null) {
2004 global $DB;
2006 // fetch a recordset with all assessments to process
2007 $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
2008 a.weight, a.grade
2009 FROM {workshop_submissions} s
2010 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id)
2011 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2012 $params = array('workshopid' => $this->id);
2014 if (is_null($restrict)) {
2015 // update all users - no more conditions
2016 } elseif (!empty($restrict)) {
2017 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2018 $sql .= " AND s.authorid $usql";
2019 $params = array_merge($params, $uparams);
2020 } else {
2021 throw new coding_exception('Empty value is not a valid parameter here');
2024 $sql .= ' ORDER BY s.id'; // this is important for bulk processing
2026 $rs = $DB->get_recordset_sql($sql, $params);
2027 $batch = array(); // will contain a set of all assessments of a single submission
2028 $previous = null; // a previous record in the recordset
2030 foreach ($rs as $current) {
2031 if (is_null($previous)) {
2032 // we are processing the very first record in the recordset
2033 $previous = $current;
2035 if ($current->submissionid == $previous->submissionid) {
2036 // we are still processing the current submission
2037 $batch[] = $current;
2038 } else {
2039 // process all the assessments of a sigle submission
2040 $this->aggregate_submission_grades_process($batch);
2041 // and then start to process another submission
2042 $batch = array($current);
2043 $previous = $current;
2046 // do not forget to process the last batch!
2047 $this->aggregate_submission_grades_process($batch);
2048 $rs->close();
2052 * Sets the aggregated grades for assessment to null
2054 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2055 * @return void
2057 public function clear_grading_grades($restrict=null) {
2058 global $DB;
2060 $sql = "workshopid = :workshopid";
2061 $params = array('workshopid' => $this->id);
2063 if (is_null($restrict)) {
2064 // update all users - no more conditions
2065 } elseif (!empty($restrict)) {
2066 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2067 $sql .= " AND userid $usql";
2068 $params = array_merge($params, $uparams);
2069 } else {
2070 throw new coding_exception('Empty value is not a valid parameter here');
2073 $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
2077 * Calculates grades for assessment for the given participant(s)
2079 * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator.
2080 * The assessment weight is not taken into account here.
2082 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2083 * @return void
2085 public function aggregate_grading_grades($restrict=null) {
2086 global $DB;
2088 // fetch a recordset with all assessments to process
2089 $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover,
2090 ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade
2091 FROM {workshop_assessments} a
2092 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
2093 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid)
2094 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2095 $params = array('workshopid' => $this->id);
2097 if (is_null($restrict)) {
2098 // update all users - no more conditions
2099 } elseif (!empty($restrict)) {
2100 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2101 $sql .= " AND a.reviewerid $usql";
2102 $params = array_merge($params, $uparams);
2103 } else {
2104 throw new coding_exception('Empty value is not a valid parameter here');
2107 $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing
2109 $rs = $DB->get_recordset_sql($sql, $params);
2110 $batch = array(); // will contain a set of all assessments of a single submission
2111 $previous = null; // a previous record in the recordset
2113 foreach ($rs as $current) {
2114 if (is_null($previous)) {
2115 // we are processing the very first record in the recordset
2116 $previous = $current;
2118 if ($current->reviewerid == $previous->reviewerid) {
2119 // we are still processing the current reviewer
2120 $batch[] = $current;
2121 } else {
2122 // process all the assessments of a sigle submission
2123 $this->aggregate_grading_grades_process($batch);
2124 // and then start to process another reviewer
2125 $batch = array($current);
2126 $previous = $current;
2129 // do not forget to process the last batch!
2130 $this->aggregate_grading_grades_process($batch);
2131 $rs->close();
2135 * Returns the mform the teachers use to put a feedback for the reviewer
2137 * @param moodle_url $actionurl
2138 * @param stdClass $assessment
2139 * @param array $options editable, editableweight, overridablegradinggrade
2140 * @return workshop_feedbackreviewer_form
2142 public function get_feedbackreviewer_form(moodle_url $actionurl, stdclass $assessment, $options=array()) {
2143 global $CFG;
2144 require_once(dirname(__FILE__) . '/feedbackreviewer_form.php');
2146 $current = new stdclass();
2147 $current->asid = $assessment->id;
2148 $current->weight = $assessment->weight;
2149 $current->gradinggrade = $this->real_grading_grade($assessment->gradinggrade);
2150 $current->gradinggradeover = $this->real_grading_grade($assessment->gradinggradeover);
2151 $current->feedbackreviewer = $assessment->feedbackreviewer;
2152 $current->feedbackreviewerformat = $assessment->feedbackreviewerformat;
2153 if (is_null($current->gradinggrade)) {
2154 $current->gradinggrade = get_string('nullgrade', 'workshop');
2156 if (!isset($options['editable'])) {
2157 $editable = true; // by default
2158 } else {
2159 $editable = (bool)$options['editable'];
2162 // prepare wysiwyg editor
2163 $current = file_prepare_standard_editor($current, 'feedbackreviewer', array());
2165 return new workshop_feedbackreviewer_form($actionurl,
2166 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2167 'post', '', null, $editable);
2171 * Returns the mform the teachers use to put a feedback for the author on their submission
2173 * @param moodle_url $actionurl
2174 * @param stdClass $submission
2175 * @param array $options editable
2176 * @return workshop_feedbackauthor_form
2178 public function get_feedbackauthor_form(moodle_url $actionurl, stdclass $submission, $options=array()) {
2179 global $CFG;
2180 require_once(dirname(__FILE__) . '/feedbackauthor_form.php');
2182 $current = new stdclass();
2183 $current->submissionid = $submission->id;
2184 $current->published = $submission->published;
2185 $current->grade = $this->real_grade($submission->grade);
2186 $current->gradeover = $this->real_grade($submission->gradeover);
2187 $current->feedbackauthor = $submission->feedbackauthor;
2188 $current->feedbackauthorformat = $submission->feedbackauthorformat;
2189 if (is_null($current->grade)) {
2190 $current->grade = get_string('nullgrade', 'workshop');
2192 if (!isset($options['editable'])) {
2193 $editable = true; // by default
2194 } else {
2195 $editable = (bool)$options['editable'];
2198 // prepare wysiwyg editor
2199 $current = file_prepare_standard_editor($current, 'feedbackauthor', array());
2201 return new workshop_feedbackauthor_form($actionurl,
2202 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2203 'post', '', null, $editable);
2207 * Returns the information about the user's grades as they are stored in the gradebook
2209 * The submission grade is returned for users with the capability mod/workshop:submit and the
2210 * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
2211 * user has the capability to view hidden grades, grades must be visible to be returned. Null
2212 * grades are not returned. If none grade is to be returned, this method returns false.
2214 * @param int $userid the user's id
2215 * @return workshop_final_grades|false
2217 public function get_gradebook_grades($userid) {
2218 global $CFG;
2219 require_once($CFG->libdir.'/gradelib.php');
2221 if (empty($userid)) {
2222 throw new coding_exception('User id expected, empty value given.');
2225 // Read data via the Gradebook API
2226 $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
2228 $grades = new workshop_final_grades();
2230 if (has_capability('mod/workshop:submit', $this->context, $userid)) {
2231 if (!empty($gradebook->items[0]->grades)) {
2232 $submissiongrade = reset($gradebook->items[0]->grades);
2233 if (!is_null($submissiongrade->grade)) {
2234 if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2235 $grades->submissiongrade = $submissiongrade;
2241 if ($this->usepeerassessment and has_capability('mod/workshop:peerassess', $this->context, $userid)) {
2242 if (!empty($gradebook->items[1]->grades)) {
2243 $assessmentgrade = reset($gradebook->items[1]->grades);
2244 if (!is_null($assessmentgrade->grade)) {
2245 if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2246 $grades->assessmentgrade = $assessmentgrade;
2252 if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
2253 return $grades;
2256 return false;
2259 ////////////////////////////////////////////////////////////////////////////////
2260 // Internal methods (implementation details) //
2261 ////////////////////////////////////////////////////////////////////////////////
2264 * Given an array of all assessments of a single submission, calculates the final grade for this submission
2266 * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade
2267 * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored.
2269 * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
2270 * @return void
2272 protected function aggregate_submission_grades_process(array $assessments) {
2273 global $DB;
2275 $submissionid = null; // the id of the submission being processed
2276 $current = null; // the grade currently saved in database
2277 $finalgrade = null; // the new grade to be calculated
2278 $sumgrades = 0;
2279 $sumweights = 0;
2281 foreach ($assessments as $assessment) {
2282 if (is_null($submissionid)) {
2283 // the id is the same in all records, fetch it during the first loop cycle
2284 $submissionid = $assessment->submissionid;
2286 if (is_null($current)) {
2287 // the currently saved grade is the same in all records, fetch it during the first loop cycle
2288 $current = $assessment->submissiongrade;
2290 if (is_null($assessment->grade)) {
2291 // this was not assessed yet
2292 continue;
2294 if ($assessment->weight == 0) {
2295 // this does not influence the calculation
2296 continue;
2298 $sumgrades += $assessment->grade * $assessment->weight;
2299 $sumweights += $assessment->weight;
2301 if ($sumweights > 0 and is_null($finalgrade)) {
2302 $finalgrade = grade_floatval($sumgrades / $sumweights);
2304 // check if the new final grade differs from the one stored in the database
2305 if (grade_floats_different($finalgrade, $current)) {
2306 // we need to save new calculation into the database
2307 $record = new stdclass();
2308 $record->id = $submissionid;
2309 $record->grade = $finalgrade;
2310 $record->timegraded = time();
2311 $DB->update_record('workshop_submissions', $record);
2316 * Given an array of all assessments done by a single reviewer, calculates the final grading grade
2318 * This calculates the simple mean of the passed grading grades. If, however, the grading grade
2319 * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored.
2321 * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade)
2322 * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time
2323 * @return void
2325 protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
2326 global $DB;
2328 $reviewerid = null; // the id of the reviewer being processed
2329 $current = null; // the gradinggrade currently saved in database
2330 $finalgrade = null; // the new grade to be calculated
2331 $agid = null; // aggregation id
2332 $sumgrades = 0;
2333 $count = 0;
2335 if (is_null($timegraded)) {
2336 $timegraded = time();
2339 foreach ($assessments as $assessment) {
2340 if (is_null($reviewerid)) {
2341 // the id is the same in all records, fetch it during the first loop cycle
2342 $reviewerid = $assessment->reviewerid;
2344 if (is_null($agid)) {
2345 // the id is the same in all records, fetch it during the first loop cycle
2346 $agid = $assessment->aggregationid;
2348 if (is_null($current)) {
2349 // the currently saved grade is the same in all records, fetch it during the first loop cycle
2350 $current = $assessment->aggregatedgrade;
2352 if (!is_null($assessment->gradinggradeover)) {
2353 // the grading grade for this assessment is overridden by a teacher
2354 $sumgrades += $assessment->gradinggradeover;
2355 $count++;
2356 } else {
2357 if (!is_null($assessment->gradinggrade)) {
2358 $sumgrades += $assessment->gradinggrade;
2359 $count++;
2363 if ($count > 0) {
2364 $finalgrade = grade_floatval($sumgrades / $count);
2366 // check if the new final grade differs from the one stored in the database
2367 if (grade_floats_different($finalgrade, $current)) {
2368 // we need to save new calculation into the database
2369 if (is_null($agid)) {
2370 // no aggregation record yet
2371 $record = new stdclass();
2372 $record->workshopid = $this->id;
2373 $record->userid = $reviewerid;
2374 $record->gradinggrade = $finalgrade;
2375 $record->timegraded = $timegraded;
2376 $DB->insert_record('workshop_aggregations', $record);
2377 } else {
2378 $record = new stdclass();
2379 $record->id = $agid;
2380 $record->gradinggrade = $finalgrade;
2381 $record->timegraded = $timegraded;
2382 $DB->update_record('workshop_aggregations', $record);
2388 * Returns SQL to fetch all enrolled users with the given capability in the current workshop
2390 * The returned array consists of string $sql and the $params array. Note that the $sql can be
2391 * empty if groupmembersonly is enabled and the associated grouping is empty.
2393 * @param string $capability the name of the capability
2394 * @param bool $musthavesubmission ff true, return only users who have already submitted
2395 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2396 * @return array of (string)sql, (array)params
2398 protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) {
2399 global $CFG;
2400 /** @var int static counter used to generate unique parameter holders */
2401 static $inc = 0;
2402 $inc++;
2404 // if the caller requests all groups and we are in groupmembersonly mode, use the
2405 // recursive call of itself to get users from all groups in the grouping
2406 if (empty($groupid) and !empty($CFG->enablegroupmembersonly) and $this->cm->groupmembersonly) {
2407 $groupingid = $this->cm->groupingid;
2408 $groupinggroupids = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
2409 $sql = array();
2410 $params = array();
2411 foreach ($groupinggroupids as $groupinggroupid) {
2412 if ($groupinggroupid > 0) { // just in case in order not to fall into the endless loop
2413 list($gsql, $gparams) = $this->get_users_with_capability_sql($capability, $musthavesubmission, $groupinggroupid);
2414 $sql[] = $gsql;
2415 $params = array_merge($params, $gparams);
2418 $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql);
2419 return array($sql, $params);
2422 list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true);
2424 $userfields = user_picture::fields('u');
2426 $sql = "SELECT $userfields
2427 FROM {user} u
2428 JOIN ($esql) je ON (je.id = u.id AND u.deleted = 0) ";
2430 if ($musthavesubmission) {
2431 $sql .= " JOIN {workshop_submissions} ws ON (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid{$inc}) ";
2432 $params['workshopid'.$inc] = $this->id;
2435 return array($sql, $params);
2439 * Returns SQL statement that can be used to fetch all actively enrolled participants in the workshop
2441 * @param bool $musthavesubmission if true, return only users who have already submitted
2442 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2443 * @return array of (string)sql, (array)params
2445 protected function get_participants_sql($musthavesubmission=false, $groupid=0) {
2447 list($sql1, $params1) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
2448 list($sql2, $params2) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
2450 if (empty($sql1) or empty($sql2)) {
2451 if (empty($sql1) and empty($sql2)) {
2452 return array('', array());
2453 } else if (empty($sql1)) {
2454 $sql = $sql2;
2455 $params = $params2;
2456 } else {
2457 $sql = $sql1;
2458 $params = $params1;
2460 } else {
2461 $sql = $sql1.PHP_EOL." UNION ".PHP_EOL.$sql2;
2462 $params = array_merge($params1, $params2);
2465 return array($sql, $params);
2469 * @return array of available workshop phases
2471 protected function available_phases_list() {
2472 return array(
2473 self::PHASE_SETUP => true,
2474 self::PHASE_SUBMISSION => true,
2475 self::PHASE_ASSESSMENT => true,
2476 self::PHASE_EVALUATION => true,
2477 self::PHASE_CLOSED => true,
2482 * Converts absolute URL to relative URL needed by {@see add_to_log()}
2484 * @param moodle_url $url absolute URL
2485 * @return string
2487 protected function log_convert_url(moodle_url $fullurl) {
2488 static $baseurl;
2490 if (!isset($baseurl)) {
2491 $baseurl = new moodle_url('/mod/workshop/');
2492 $baseurl = $baseurl->out();
2495 return substr($fullurl->out(), strlen($baseurl));
2499 ////////////////////////////////////////////////////////////////////////////////
2500 // Renderable components
2501 ////////////////////////////////////////////////////////////////////////////////
2504 * Represents the user planner tool
2506 * Planner contains list of phases. Each phase contains list of tasks. Task is a simple object with
2507 * title, link and completed (true/false/null logic).
2509 class workshop_user_plan implements renderable {
2511 /** @var int id of the user this plan is for */
2512 public $userid;
2513 /** @var workshop */
2514 public $workshop;
2515 /** @var array of (stdclass)tasks */
2516 public $phases = array();
2517 /** @var null|array of example submissions to be assessed by the planner owner */
2518 protected $examples = null;
2521 * Prepare an individual workshop plan for the given user.
2523 * @param workshop $workshop instance
2524 * @param int $userid whom the plan is prepared for
2526 public function __construct(workshop $workshop, $userid) {
2527 global $DB;
2529 $this->workshop = $workshop;
2530 $this->userid = $userid;
2532 //---------------------------------------------------------
2533 // * SETUP | submission | assessment | evaluation | closed
2534 //---------------------------------------------------------
2535 $phase = new stdclass();
2536 $phase->title = get_string('phasesetup', 'workshop');
2537 $phase->tasks = array();
2538 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2539 $task = new stdclass();
2540 $task->title = get_string('taskintro', 'workshop');
2541 $task->link = $workshop->updatemod_url();
2542 $task->completed = !(trim($workshop->intro) == '');
2543 $phase->tasks['intro'] = $task;
2545 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2546 $task = new stdclass();
2547 $task->title = get_string('taskinstructauthors', 'workshop');
2548 $task->link = $workshop->updatemod_url();
2549 $task->completed = !(trim($workshop->instructauthors) == '');
2550 $phase->tasks['instructauthors'] = $task;
2552 if (has_capability('mod/workshop:editdimensions', $workshop->context, $userid)) {
2553 $task = new stdclass();
2554 $task->title = get_string('editassessmentform', 'workshop');
2555 $task->link = $workshop->editform_url();
2556 if ($workshop->grading_strategy_instance()->form_ready()) {
2557 $task->completed = true;
2558 } elseif ($workshop->phase > workshop::PHASE_SETUP) {
2559 $task->completed = false;
2561 $phase->tasks['editform'] = $task;
2563 if ($workshop->useexamples and has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2564 $task = new stdclass();
2565 $task->title = get_string('prepareexamples', 'workshop');
2566 if ($DB->count_records('workshop_submissions', array('example' => 1, 'workshopid' => $workshop->id)) > 0) {
2567 $task->completed = true;
2568 } elseif ($workshop->phase > workshop::PHASE_SETUP) {
2569 $task->completed = false;
2571 $phase->tasks['prepareexamples'] = $task;
2573 if (empty($phase->tasks) and $workshop->phase == workshop::PHASE_SETUP) {
2574 // if we are in the setup phase and there is no task (typical for students), let us
2575 // display some explanation what is going on
2576 $task = new stdclass();
2577 $task->title = get_string('undersetup', 'workshop');
2578 $task->completed = 'info';
2579 $phase->tasks['setupinfo'] = $task;
2581 $this->phases[workshop::PHASE_SETUP] = $phase;
2583 //---------------------------------------------------------
2584 // setup | * SUBMISSION | assessment | evaluation | closed
2585 //---------------------------------------------------------
2586 $phase = new stdclass();
2587 $phase->title = get_string('phasesubmission', 'workshop');
2588 $phase->tasks = array();
2589 if (($workshop->usepeerassessment or $workshop->useselfassessment)
2590 and has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2591 $task = new stdclass();
2592 $task->title = get_string('taskinstructreviewers', 'workshop');
2593 $task->link = $workshop->updatemod_url();
2594 if (trim($workshop->instructreviewers)) {
2595 $task->completed = true;
2596 } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2597 $task->completed = false;
2599 $phase->tasks['instructreviewers'] = $task;
2601 if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION
2602 and has_capability('mod/workshop:submit', $workshop->context, $userid, false)
2603 and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2604 $task = new stdclass();
2605 $task->title = get_string('exampleassesstask', 'workshop');
2606 $examples = $this->get_examples();
2607 $a = new stdclass();
2608 $a->expected = count($examples);
2609 $a->assessed = 0;
2610 foreach ($examples as $exampleid => $example) {
2611 if (!is_null($example->grade)) {
2612 $a->assessed++;
2615 $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
2616 if ($a->assessed == $a->expected) {
2617 $task->completed = true;
2618 } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2619 $task->completed = false;
2621 $phase->tasks['examples'] = $task;
2623 if (has_capability('mod/workshop:submit', $workshop->context, $userid, false)) {
2624 $task = new stdclass();
2625 $task->title = get_string('tasksubmit', 'workshop');
2626 $task->link = $workshop->submission_url();
2627 if ($DB->record_exists('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0, 'authorid'=>$userid))) {
2628 $task->completed = true;
2629 } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2630 $task->completed = false;
2631 } else {
2632 $task->completed = null; // still has a chance to submit
2634 $phase->tasks['submit'] = $task;
2636 if (has_capability('mod/workshop:allocate', $workshop->context, $userid)) {
2637 if ($workshop->phaseswitchassessment) {
2638 $task = new stdClass();
2639 $allocator = $DB->get_record('workshopallocation_scheduled', array('workshopid' => $workshop->id));
2640 if (empty($allocator)) {
2641 $task->completed = false;
2642 } else if ($allocator->enabled and is_null($allocator->resultstatus)) {
2643 $task->completed = true;
2644 } else if ($workshop->submissionend > time()) {
2645 $task->completed = null;
2646 } else {
2647 $task->completed = false;
2649 $task->title = get_string('setup', 'workshopallocation_scheduled');
2650 $task->link = $workshop->allocation_url('scheduled');
2651 $phase->tasks['allocatescheduled'] = $task;
2653 $task = new stdclass();
2654 $task->title = get_string('allocate', 'workshop');
2655 $task->link = $workshop->allocation_url();
2656 $numofauthors = $workshop->count_potential_authors(false);
2657 $numofsubmissions = $DB->count_records('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0));
2658 $sql = 'SELECT COUNT(s.id) AS nonallocated
2659 FROM {workshop_submissions} s
2660 LEFT JOIN {workshop_assessments} a ON (a.submissionid=s.id)
2661 WHERE s.workshopid = :workshopid AND s.example=0 AND a.submissionid IS NULL';
2662 $params['workshopid'] = $workshop->id;
2663 $numnonallocated = $DB->count_records_sql($sql, $params);
2664 if ($numofsubmissions == 0) {
2665 $task->completed = null;
2666 } elseif ($numnonallocated == 0) {
2667 $task->completed = true;
2668 } elseif ($workshop->phase > workshop::PHASE_SUBMISSION) {
2669 $task->completed = false;
2670 } else {
2671 $task->completed = null; // still has a chance to allocate
2673 $a = new stdclass();
2674 $a->expected = $numofauthors;
2675 $a->submitted = $numofsubmissions;
2676 $a->allocate = $numnonallocated;
2677 $task->details = get_string('allocatedetails', 'workshop', $a);
2678 unset($a);
2679 $phase->tasks['allocate'] = $task;
2681 if ($numofsubmissions < $numofauthors and $workshop->phase >= workshop::PHASE_SUBMISSION) {
2682 $task = new stdclass();
2683 $task->title = get_string('someuserswosubmission', 'workshop');
2684 $task->completed = 'info';
2685 $phase->tasks['allocateinfo'] = $task;
2689 if ($workshop->submissionstart) {
2690 $task = new stdclass();
2691 $task->title = get_string('submissionstartdatetime', 'workshop', workshop::timestamp_formats($workshop->submissionstart));
2692 $task->completed = 'info';
2693 $phase->tasks['submissionstartdatetime'] = $task;
2695 if ($workshop->submissionend) {
2696 $task = new stdclass();
2697 $task->title = get_string('submissionenddatetime', 'workshop', workshop::timestamp_formats($workshop->submissionend));
2698 $task->completed = 'info';
2699 $phase->tasks['submissionenddatetime'] = $task;
2701 if (($workshop->submissionstart < time()) and $workshop->latesubmissions) {
2702 $task = new stdclass();
2703 $task->title = get_string('latesubmissionsallowed', 'workshop');
2704 $task->completed = 'info';
2705 $phase->tasks['latesubmissionsallowed'] = $task;
2707 if (isset($phase->tasks['submissionstartdatetime']) or isset($phase->tasks['submissionenddatetime'])) {
2708 if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
2709 $task = new stdclass();
2710 $task->title = get_string('deadlinesignored', 'workshop');
2711 $task->completed = 'info';
2712 $phase->tasks['deadlinesignored'] = $task;
2715 $this->phases[workshop::PHASE_SUBMISSION] = $phase;
2717 //---------------------------------------------------------
2718 // setup | submission | * ASSESSMENT | evaluation | closed
2719 //---------------------------------------------------------
2720 $phase = new stdclass();
2721 $phase->title = get_string('phaseassessment', 'workshop');
2722 $phase->tasks = array();
2723 $phase->isreviewer = has_capability('mod/workshop:peerassess', $workshop->context, $userid);
2724 if ($workshop->phase == workshop::PHASE_SUBMISSION and $workshop->phaseswitchassessment
2725 and has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
2726 $task = new stdClass();
2727 $task->title = get_string('switchphase30auto', 'mod_workshop', workshop::timestamp_formats($workshop->submissionend));
2728 $task->completed = 'info';
2729 $phase->tasks['autoswitchinfo'] = $task;
2731 if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_ASSESSMENT
2732 and $phase->isreviewer and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2733 $task = new stdclass();
2734 $task->title = get_string('exampleassesstask', 'workshop');
2735 $examples = $workshop->get_examples_for_reviewer($userid);
2736 $a = new stdclass();
2737 $a->expected = count($examples);
2738 $a->assessed = 0;
2739 foreach ($examples as $exampleid => $example) {
2740 if (!is_null($example->grade)) {
2741 $a->assessed++;
2744 $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
2745 if ($a->assessed == $a->expected) {
2746 $task->completed = true;
2747 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
2748 $task->completed = false;
2750 $phase->tasks['examples'] = $task;
2752 if (empty($phase->tasks['examples']) or !empty($phase->tasks['examples']->completed)) {
2753 $phase->assessments = $workshop->get_assessments_by_reviewer($userid);
2754 $numofpeers = 0; // number of allocated peer-assessments
2755 $numofpeerstodo = 0; // number of peer-assessments to do
2756 $numofself = 0; // number of allocated self-assessments - should be 0 or 1
2757 $numofselftodo = 0; // number of self-assessments to do - should be 0 or 1
2758 foreach ($phase->assessments as $a) {
2759 if ($a->authorid == $userid) {
2760 $numofself++;
2761 if (is_null($a->grade)) {
2762 $numofselftodo++;
2764 } else {
2765 $numofpeers++;
2766 if (is_null($a->grade)) {
2767 $numofpeerstodo++;
2771 unset($a);
2772 if ($workshop->usepeerassessment and $numofpeers) {
2773 $task = new stdclass();
2774 if ($numofpeerstodo == 0) {
2775 $task->completed = true;
2776 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
2777 $task->completed = false;
2779 $a = new stdclass();
2780 $a->total = $numofpeers;
2781 $a->todo = $numofpeerstodo;
2782 $task->title = get_string('taskassesspeers', 'workshop');
2783 $task->details = get_string('taskassesspeersdetails', 'workshop', $a);
2784 unset($a);
2785 $phase->tasks['assesspeers'] = $task;
2787 if ($workshop->useselfassessment and $numofself) {
2788 $task = new stdclass();
2789 if ($numofselftodo == 0) {
2790 $task->completed = true;
2791 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
2792 $task->completed = false;
2794 $task->title = get_string('taskassessself', 'workshop');
2795 $phase->tasks['assessself'] = $task;
2798 if ($workshop->assessmentstart) {
2799 $task = new stdclass();
2800 $task->title = get_string('assessmentstartdatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentstart));
2801 $task->completed = 'info';
2802 $phase->tasks['assessmentstartdatetime'] = $task;
2804 if ($workshop->assessmentend) {
2805 $task = new stdclass();
2806 $task->title = get_string('assessmentenddatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentend));
2807 $task->completed = 'info';
2808 $phase->tasks['assessmentenddatetime'] = $task;
2810 if (isset($phase->tasks['assessmentstartdatetime']) or isset($phase->tasks['assessmentenddatetime'])) {
2811 if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
2812 $task = new stdclass();
2813 $task->title = get_string('deadlinesignored', 'workshop');
2814 $task->completed = 'info';
2815 $phase->tasks['deadlinesignored'] = $task;
2818 $this->phases[workshop::PHASE_ASSESSMENT] = $phase;
2820 //---------------------------------------------------------
2821 // setup | submission | assessment | * EVALUATION | closed
2822 //---------------------------------------------------------
2823 $phase = new stdclass();
2824 $phase->title = get_string('phaseevaluation', 'workshop');
2825 $phase->tasks = array();
2826 if (has_capability('mod/workshop:overridegrades', $workshop->context)) {
2827 $expected = $workshop->count_potential_authors(false);
2828 $calculated = $DB->count_records_select('workshop_submissions',
2829 'workshopid = ? AND (grade IS NOT NULL OR gradeover IS NOT NULL)', array($workshop->id));
2830 $task = new stdclass();
2831 $task->title = get_string('calculatesubmissiongrades', 'workshop');
2832 $a = new stdclass();
2833 $a->expected = $expected;
2834 $a->calculated = $calculated;
2835 $task->details = get_string('calculatesubmissiongradesdetails', 'workshop', $a);
2836 if ($calculated >= $expected) {
2837 $task->completed = true;
2838 } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
2839 $task->completed = false;
2841 $phase->tasks['calculatesubmissiongrade'] = $task;
2843 $expected = $workshop->count_potential_reviewers(false);
2844 $calculated = $DB->count_records_select('workshop_aggregations',
2845 'workshopid = ? AND gradinggrade IS NOT NULL', array($workshop->id));
2846 $task = new stdclass();
2847 $task->title = get_string('calculategradinggrades', 'workshop');
2848 $a = new stdclass();
2849 $a->expected = $expected;
2850 $a->calculated = $calculated;
2851 $task->details = get_string('calculategradinggradesdetails', 'workshop', $a);
2852 if ($calculated >= $expected) {
2853 $task->completed = true;
2854 } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
2855 $task->completed = false;
2857 $phase->tasks['calculategradinggrade'] = $task;
2859 } elseif ($workshop->phase == workshop::PHASE_EVALUATION) {
2860 $task = new stdclass();
2861 $task->title = get_string('evaluategradeswait', 'workshop');
2862 $task->completed = 'info';
2863 $phase->tasks['evaluateinfo'] = $task;
2866 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2867 $task = new stdclass();
2868 $task->title = get_string('taskconclusion', 'workshop');
2869 $task->link = $workshop->updatemod_url();
2870 if (trim($workshop->conclusion)) {
2871 $task->completed = true;
2872 } elseif ($workshop->phase >= workshop::PHASE_EVALUATION) {
2873 $task->completed = false;
2875 $phase->tasks['conclusion'] = $task;
2878 $this->phases[workshop::PHASE_EVALUATION] = $phase;
2880 //---------------------------------------------------------
2881 // setup | submission | assessment | evaluation | * CLOSED
2882 //---------------------------------------------------------
2883 $phase = new stdclass();
2884 $phase->title = get_string('phaseclosed', 'workshop');
2885 $phase->tasks = array();
2886 $this->phases[workshop::PHASE_CLOSED] = $phase;
2888 // Polish data, set default values if not done explicitly
2889 foreach ($this->phases as $phasecode => $phase) {
2890 $phase->title = isset($phase->title) ? $phase->title : '';
2891 $phase->tasks = isset($phase->tasks) ? $phase->tasks : array();
2892 if ($phasecode == $workshop->phase) {
2893 $phase->active = true;
2894 } else {
2895 $phase->active = false;
2897 if (!isset($phase->actions)) {
2898 $phase->actions = array();
2901 foreach ($phase->tasks as $taskcode => $task) {
2902 $task->title = isset($task->title) ? $task->title : '';
2903 $task->link = isset($task->link) ? $task->link : null;
2904 $task->details = isset($task->details) ? $task->details : '';
2905 $task->completed = isset($task->completed) ? $task->completed : null;
2909 // Add phase switching actions
2910 if (has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
2911 foreach ($this->phases as $phasecode => $phase) {
2912 if (! $phase->active) {
2913 $action = new stdclass();
2914 $action->type = 'switchphase';
2915 $action->url = $workshop->switchphase_url($phasecode);
2916 $phase->actions[] = $action;
2923 * Returns example submissions to be assessed by the owner of the planner
2925 * This is here to cache the DB query because the same list is needed later in view.php
2927 * @see workshop::get_examples_for_reviewer() for the format of returned value
2928 * @return array
2930 public function get_examples() {
2931 if (is_null($this->examples)) {
2932 $this->examples = $this->workshop->get_examples_for_reviewer($this->userid);
2934 return $this->examples;
2939 * Common base class for submissions and example submissions rendering
2941 * Subclasses of this class convert raw submission record from
2942 * workshop_submissions table (as returned by {@see workshop::get_submission_by_id()}
2943 * for example) into renderable objects.
2945 abstract class workshop_submission_base {
2947 /** @var bool is the submission anonymous (i.e. contains author information) */
2948 protected $anonymous;
2950 /* @var array of columns from workshop_submissions that are assigned as properties */
2951 protected $fields = array();
2954 * Copies the properties of the given database record into properties of $this instance
2956 * @param stdClass $submission full record
2957 * @param bool $showauthor show the author-related information
2958 * @param array $options additional properties
2960 public function __construct(stdClass $submission, $showauthor = false) {
2962 foreach ($this->fields as $field) {
2963 if (!property_exists($submission, $field)) {
2964 throw new coding_exception('Submission record must provide public property ' . $field);
2966 if (!property_exists($this, $field)) {
2967 throw new coding_exception('Renderable component must accept public property ' . $field);
2969 $this->{$field} = $submission->{$field};
2972 if ($showauthor) {
2973 $this->anonymous = false;
2974 } else {
2975 $this->anonymize();
2980 * Unsets all author-related properties so that the renderer does not have access to them
2982 * Usually this is called by the contructor but can be called explicitely, too.
2984 public function anonymize() {
2985 foreach (array('authorid', 'authorfirstname', 'authorlastname',
2986 'authorpicture', 'authorimagealt', 'authoremail') as $field) {
2987 unset($this->{$field});
2989 $this->anonymous = true;
2993 * Does the submission object contain author-related information?
2995 * @return null|boolean
2997 public function is_anonymous() {
2998 return $this->anonymous;
3003 * Renderable object containing a basic set of information needed to display the submission summary
3005 * @see workshop_renderer::render_workshop_submission_summary
3007 class workshop_submission_summary extends workshop_submission_base implements renderable {
3009 /** @var int */
3010 public $id;
3011 /** @var string */
3012 public $title;
3013 /** @var string graded|notgraded */
3014 public $status;
3015 /** @var int */
3016 public $timecreated;
3017 /** @var int */
3018 public $timemodified;
3019 /** @var int */
3020 public $authorid;
3021 /** @var string */
3022 public $authorfirstname;
3023 /** @var string */
3024 public $authorlastname;
3025 /** @var int */
3026 public $authorpicture;
3027 /** @var string */
3028 public $authorimagealt;
3029 /** @var string */
3030 public $authoremail;
3031 /** @var moodle_url to display submission */
3032 public $url;
3035 * @var array of columns from workshop_submissions that are assigned as properties
3036 * of instances of this class
3038 protected $fields = array(
3039 'id', 'title', 'timecreated', 'timemodified',
3040 'authorid', 'authorfirstname', 'authorlastname', 'authorpicture',
3041 'authorimagealt', 'authoremail');
3045 * Renderable object containing all the information needed to display the submission
3047 * @see workshop_renderer::render_workshop_submission()
3049 class workshop_submission extends workshop_submission_summary implements renderable {
3051 /** @var string */
3052 public $content;
3053 /** @var int */
3054 public $contentformat;
3055 /** @var bool */
3056 public $contenttrust;
3057 /** @var array */
3058 public $attachment;
3061 * @var array of columns from workshop_submissions that are assigned as properties
3062 * of instances of this class
3064 protected $fields = array(
3065 'id', 'title', 'timecreated', 'timemodified', 'content', 'contentformat', 'contenttrust',
3066 'attachment', 'authorid', 'authorfirstname', 'authorlastname', 'authorpicture',
3067 'authorimagealt', 'authoremail');
3071 * Renderable object containing a basic set of information needed to display the example submission summary
3073 * @see workshop::prepare_example_summary()
3074 * @see workshop_renderer::render_workshop_example_submission_summary()
3076 class workshop_example_submission_summary extends workshop_submission_base implements renderable {
3078 /** @var int */
3079 public $id;
3080 /** @var string */
3081 public $title;
3082 /** @var string graded|notgraded */
3083 public $status;
3084 /** @var stdClass */
3085 public $gradeinfo;
3086 /** @var moodle_url */
3087 public $url;
3088 /** @var moodle_url */
3089 public $editurl;
3090 /** @var string */
3091 public $assesslabel;
3092 /** @var moodle_url */
3093 public $assessurl;
3094 /** @var bool must be set explicitly by the caller */
3095 public $editable = false;
3098 * @var array of columns from workshop_submissions that are assigned as properties
3099 * of instances of this class
3101 protected $fields = array('id', 'title');
3104 * Example submissions are always anonymous
3106 * @return true
3108 public function is_anonymous() {
3109 return true;
3114 * Renderable object containing all the information needed to display the example submission
3116 * @see workshop_renderer::render_workshop_example_submission()
3118 class workshop_example_submission extends workshop_example_submission_summary implements renderable {
3120 /** @var string */
3121 public $content;
3122 /** @var int */
3123 public $contentformat;
3124 /** @var bool */
3125 public $contenttrust;
3126 /** @var array */
3127 public $attachment;
3130 * @var array of columns from workshop_submissions that are assigned as properties
3131 * of instances of this class
3133 protected $fields = array('id', 'title', 'content', 'contentformat', 'contenttrust', 'attachment');
3138 * Common base class for assessments rendering
3140 * Subclasses of this class convert raw assessment record from
3141 * workshop_assessments table (as returned by {@see workshop::get_assessment_by_id()}
3142 * for example) into renderable objects.
3144 abstract class workshop_assessment_base {
3146 /** @var string the optional title of the assessment */
3147 public $title = '';
3149 /** @var workshop_assessment_form $form as returned by {@link workshop_strategy::get_assessment_form()} */
3150 public $form;
3152 /** @var moodle_url */
3153 public $url;
3155 /** @var float|null the real received grade */
3156 public $realgrade = null;
3158 /** @var float the real maximum grade */
3159 public $maxgrade;
3161 /** @var stdClass|null reviewer user info */
3162 public $reviewer = null;
3164 /** @var stdClass|null assessed submission's author user info */
3165 public $author = null;
3167 /** @var array of actions */
3168 public $actions = array();
3170 /* @var array of columns that are assigned as properties */
3171 protected $fields = array();
3174 * Copies the properties of the given database record into properties of $this instance
3176 * The $options keys are: showreviewer, showauthor
3177 * @param stdClass $assessment full record
3178 * @param array $options additional properties
3180 public function __construct(stdClass $record, array $options = array()) {
3182 $this->validate_raw_record($record);
3184 foreach ($this->fields as $field) {
3185 if (!property_exists($record, $field)) {
3186 throw new coding_exception('Assessment record must provide public property ' . $field);
3188 if (!property_exists($this, $field)) {
3189 throw new coding_exception('Renderable component must accept public property ' . $field);
3191 $this->{$field} = $record->{$field};
3194 if (!empty($options['showreviewer'])) {
3195 $this->reviewer = user_picture::unalias($record, null, 'revieweridx', 'reviewer');
3198 if (!empty($options['showauthor'])) {
3199 $this->author = user_picture::unalias($record, null, 'authorid', 'author');
3204 * Adds a new action
3206 * @param moodle_url $url action URL
3207 * @param string $label action label
3208 * @param string $method get|post
3210 public function add_action(moodle_url $url, $label, $method = 'get') {
3212 $action = new stdClass();
3213 $action->url = $url;
3214 $action->label = $label;
3215 $action->method = $method;
3217 $this->actions[] = $action;
3221 * Makes sure that we can cook the renderable component from the passed raw database record
3223 * @param stdClass $assessment full assessment record
3224 * @throws coding_exception if the caller passed unexpected data
3226 protected function validate_raw_record(stdClass $record) {
3227 // nothing to do here
3233 * Represents a rendarable full assessment
3235 class workshop_assessment extends workshop_assessment_base implements renderable {
3237 /** @var int */
3238 public $id;
3240 /** @var int */
3241 public $submissionid;
3243 /** @var int */
3244 public $weight;
3246 /** @var int */
3247 public $timecreated;
3249 /** @var int */
3250 public $timemodified;
3252 /** @var float */
3253 public $grade;
3255 /** @var float */
3256 public $gradinggrade;
3258 /** @var float */
3259 public $gradinggradeover;
3261 /** @var array */
3262 protected $fields = array('id', 'submissionid', 'weight', 'timecreated',
3263 'timemodified', 'grade', 'gradinggrade', 'gradinggradeover');
3268 * Represents a renderable training assessment of an example submission
3270 class workshop_example_assessment extends workshop_assessment implements renderable {
3273 * @see parent::validate_raw_record()
3275 protected function validate_raw_record(stdClass $record) {
3276 if ($record->weight != 0) {
3277 throw new coding_exception('Invalid weight of example submission assessment');
3279 parent::validate_raw_record($record);
3285 * Represents a renderable reference assessment of an example submission
3287 class workshop_example_reference_assessment extends workshop_assessment implements renderable {
3290 * @see parent::validate_raw_record()
3292 protected function validate_raw_record(stdClass $record) {
3293 if ($record->weight != 1) {
3294 throw new coding_exception('Invalid weight of the reference example submission assessment');
3296 parent::validate_raw_record($record);
3302 * Renderable message to be displayed to the user
3304 * Message can contain an optional action link with a label that is supposed to be rendered
3305 * as a button or a link.
3307 * @see workshop::renderer::render_workshop_message()
3309 class workshop_message implements renderable {
3311 const TYPE_INFO = 10;
3312 const TYPE_OK = 20;
3313 const TYPE_ERROR = 30;
3315 /** @var string */
3316 protected $text = '';
3317 /** @var int */
3318 protected $type = self::TYPE_INFO;
3319 /** @var moodle_url */
3320 protected $actionurl = null;
3321 /** @var string */
3322 protected $actionlabel = '';
3325 * @param string $text short text to be displayed
3326 * @param string $type optional message type info|ok|error
3328 public function __construct($text = null, $type = self::TYPE_INFO) {
3329 $this->set_text($text);
3330 $this->set_type($type);
3334 * Sets the message text
3336 * @param string $text short text to be displayed
3338 public function set_text($text) {
3339 $this->text = $text;
3343 * Sets the message type
3345 * @param int $type
3347 public function set_type($type = self::TYPE_INFO) {
3348 if (in_array($type, array(self::TYPE_OK, self::TYPE_ERROR, self::TYPE_INFO))) {
3349 $this->type = $type;
3350 } else {
3351 throw new coding_exception('Unknown message type.');
3356 * Sets the optional message action
3358 * @param moodle_url $url to follow on action
3359 * @param string $label action label
3361 public function set_action(moodle_url $url, $label) {
3362 $this->actionurl = $url;
3363 $this->actionlabel = $label;
3367 * Returns message text with HTML tags quoted
3369 * @return string
3371 public function get_message() {
3372 return s($this->text);
3376 * Returns message type
3378 * @return int
3380 public function get_type() {
3381 return $this->type;
3385 * Returns action URL
3387 * @return moodle_url|null
3389 public function get_action_url() {
3390 return $this->actionurl;
3394 * Returns action label
3396 * @return string
3398 public function get_action_label() {
3399 return $this->actionlabel;
3405 * Renderable component containing all the data needed to display the grading report
3407 class workshop_grading_report implements renderable {
3409 /** @var stdClass returned by {@see workshop::prepare_grading_report_data()} */
3410 protected $data;
3411 /** @var stdClass rendering options */
3412 protected $options;
3415 * Grades in $data must be already rounded to the set number of decimals or must be null
3416 * (in which later case, the [mod_workshop,nullgrade] string shall be displayed)
3418 * @param stdClass $data prepared by {@link workshop::prepare_grading_report_data()}
3419 * @param stdClass $options display options (showauthornames, showreviewernames, sortby, sorthow, showsubmissiongrade, showgradinggrade)
3421 public function __construct(stdClass $data, stdClass $options) {
3422 $this->data = $data;
3423 $this->options = $options;
3427 * @return stdClass grading report data
3429 public function get_data() {
3430 return $this->data;
3434 * @return stdClass rendering options
3436 public function get_options() {
3437 return $this->options;
3443 * Base class for renderable feedback for author and feedback for reviewer
3445 abstract class workshop_feedback {
3447 /** @var stdClass the user info */
3448 protected $provider = null;
3450 /** @var string the feedback text */
3451 protected $content = null;
3453 /** @var int format of the feedback text */
3454 protected $format = null;
3457 * @return stdClass the user info
3459 public function get_provider() {
3461 if (is_null($this->provider)) {
3462 throw new coding_exception('Feedback provider not set');
3465 return $this->provider;
3469 * @return string the feedback text
3471 public function get_content() {
3473 if (is_null($this->content)) {
3474 throw new coding_exception('Feedback content not set');
3477 return $this->content;
3481 * @return int format of the feedback text
3483 public function get_format() {
3485 if (is_null($this->format)) {
3486 throw new coding_exception('Feedback text format not set');
3489 return $this->format;
3495 * Renderable feedback for the author of submission
3497 class workshop_feedback_author extends workshop_feedback implements renderable {
3500 * Extracts feedback from the given submission record
3502 * @param stdClass $submission record as returned by {@see self::get_submission_by_id()}
3504 public function __construct(stdClass $submission) {
3506 $this->provider = user_picture::unalias($submission, null, 'gradeoverbyx', 'gradeoverby');
3507 $this->content = $submission->feedbackauthor;
3508 $this->format = $submission->feedbackauthorformat;
3514 * Renderable feedback for the reviewer
3516 class workshop_feedback_reviewer extends workshop_feedback implements renderable {
3519 * Extracts feedback from the given assessment record
3521 * @param stdClass $assessment record as returned by eg {@see self::get_assessment_by_id()}
3523 public function __construct(stdClass $assessment) {
3525 $this->provider = user_picture::unalias($assessment, null, 'gradinggradeoverbyx', 'overby');
3526 $this->content = $assessment->feedbackreviewer;
3527 $this->format = $assessment->feedbackreviewerformat;
3533 * Holds the final grades for the activity as are stored in the gradebook
3535 class workshop_final_grades implements renderable {
3537 /** @var object the info from the gradebook about the grade for submission */
3538 public $submissiongrade = null;
3540 /** @var object the infor from the gradebook about the grade for assessment */
3541 public $assessmentgrade = null;