2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of internal classes and functions for module workshop
20 * All the workshop specific functions, needed to implement the module
21 * logic, should go to here. Instead of having bunch of function named
22 * workshop_something() taking the workshop instance as the first
23 * parameter, we use a class workshop that provides all methods.
25 * @package mod_workshop
26 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 require_once(__DIR__.'/lib.php'); // we extend this library here
33 require_once($CFG->libdir . '/gradelib.php'); // we use some rounding and comparing routines here
34 require_once($CFG->libdir . '/filelib.php');
37 * Full-featured workshop API
39 * This wraps the workshop database record with a set of methods that are called
40 * from the module itself. The class should be initialized right after you get
41 * $workshop, $cm and $course records at the begining of the script.
45 /** error status of the {@link self::add_allocation()} */
46 const ALLOCATION_EXISTS = -9999;
48 /** the internal code of the workshop phases as are stored in the database */
49 const PHASE_SETUP = 10;
50 const PHASE_SUBMISSION = 20;
51 const PHASE_ASSESSMENT = 30;
52 const PHASE_EVALUATION = 40;
53 const PHASE_CLOSED = 50;
55 /** the internal code of the examples modes as are stored in the database */
56 const EXAMPLES_VOLUNTARY = 0;
57 const EXAMPLES_BEFORE_SUBMISSION = 1;
58 const EXAMPLES_BEFORE_ASSESSMENT = 2;
60 /** @var stdclass workshop record from database */
63 /** @var cm_info course module record */
66 /** @var stdclass course record */
69 /** @var stdclass context object */
72 /** @var int workshop instance identifier */
75 /** @var string workshop activity name */
78 /** @var string introduction or description of the activity */
81 /** @var int format of the {@link $intro} */
84 /** @var string instructions for the submission phase */
85 public $instructauthors;
87 /** @var int format of the {@link $instructauthors} */
88 public $instructauthorsformat;
90 /** @var string instructions for the assessment phase */
91 public $instructreviewers;
93 /** @var int format of the {@link $instructreviewers} */
94 public $instructreviewersformat;
96 /** @var int timestamp of when the module was modified */
99 /** @var int current phase of workshop, for example {@link workshop::PHASE_SETUP} */
102 /** @var bool optional feature: students practise evaluating on example submissions from teacher */
105 /** @var bool optional feature: students perform peer assessment of others' work (deprecated, consider always enabled) */
106 public $usepeerassessment;
108 /** @var bool optional feature: students perform self assessment of their own work */
109 public $useselfassessment;
111 /** @var float number (10, 5) unsigned, the maximum grade for submission */
114 /** @var float number (10, 5) unsigned, the maximum grade for assessment */
115 public $gradinggrade;
117 /** @var string type of the current grading strategy used in this workshop, for example 'accumulative' */
120 /** @var string the name of the evaluation plugin to use for grading grades calculation */
123 /** @var int number of digits that should be shown after the decimal point when displaying grades */
124 public $gradedecimals;
126 /** @var int number of allowed submission attachments and the files embedded into submission */
127 public $nattachments;
129 /** @var string list of allowed file types that are allowed to be embedded into submission */
130 public $submissionfiletypes = null;
132 /** @var bool allow submitting the work after the deadline */
133 public $latesubmissions;
135 /** @var int maximum size of the one attached file in bytes */
138 /** @var int mode of example submissions support, for example {@link workshop::EXAMPLES_VOLUNTARY} */
139 public $examplesmode;
141 /** @var int if greater than 0 then the submission is not allowed before this timestamp */
142 public $submissionstart;
144 /** @var int if greater than 0 then the submission is not allowed after this timestamp */
145 public $submissionend;
147 /** @var int if greater than 0 then the peer assessment is not allowed before this timestamp */
148 public $assessmentstart;
150 /** @var int if greater than 0 then the peer assessment is not allowed after this timestamp */
151 public $assessmentend;
153 /** @var bool automatically switch to the assessment phase after the submissions deadline */
154 public $phaseswitchassessment;
156 /** @var string conclusion text to be displayed at the end of the activity */
159 /** @var int format of the conclusion text */
160 public $conclusionformat;
162 /** @var int the mode of the overall feedback */
163 public $overallfeedbackmode;
165 /** @var int maximum number of overall feedback attachments */
166 public $overallfeedbackfiles;
168 /** @var string list of allowed file types that can be attached to the overall feedback */
169 public $overallfeedbackfiletypes = null;
171 /** @var int maximum size of one file attached to the overall feedback */
172 public $overallfeedbackmaxbytes;
175 * @var workshop_strategy grading strategy instance
176 * Do not use directly, get the instance using {@link workshop::grading_strategy_instance()}
178 protected $strategyinstance = null;
181 * @var workshop_evaluation grading evaluation instance
182 * Do not use directly, get the instance using {@link workshop::grading_evaluation_instance()}
184 protected $evaluationinstance = null;
187 * Initializes the workshop API instance using the data from DB
189 * Makes deep copy of all passed records properties.
191 * For unit testing only, $cm and $course may be set to null. This is so that
192 * you can test without having any real database objects if you like. Not all
193 * functions will work in this situation.
195 * @param stdClass $dbrecord Workshop instance data from {workshop} table
196 * @param stdClass|cm_info $cm Course module record
197 * @param stdClass $course Course record from {course} table
198 * @param stdClass $context The context of the workshop instance
200 public function __construct(stdclass $dbrecord, $cm, $course, stdclass $context=null) {
201 $this->dbrecord = $dbrecord;
202 foreach ($this->dbrecord as $field => $value) {
203 if (property_exists('workshop', $field)) {
204 $this->{$field} = $value;
207 if (is_null($cm) || is_null($course)) {
208 throw new coding_exception('Must specify $cm and $course');
210 $this->course = $course;
211 if ($cm instanceof cm_info) {
214 $modinfo = get_fast_modinfo($course);
215 $this->cm = $modinfo->get_cm($cm->id);
217 if (is_null($context)) {
218 $this->context = context_module::instance($this->cm->id);
220 $this->context = $context;
224 ////////////////////////////////////////////////////////////////////////////////
226 ////////////////////////////////////////////////////////////////////////////////
229 * Return list of available allocation methods
231 * @return array Array ['string' => 'string'] of localized allocation method names
233 public static function installed_allocators() {
234 $installed = core_component::get_plugin_list('workshopallocation');
236 foreach ($installed as $allocation => $allocationpath) {
237 if (file_exists($allocationpath . '/lib.php')) {
238 $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation);
241 // usability - make sure that manual allocation appears the first
242 if (isset($forms['manual'])) {
243 $m = array('manual' => $forms['manual']);
244 unset($forms['manual']);
245 $forms = array_merge($m, $forms);
251 * Returns an array of options for the editors that are used for submitting and assessing instructions
253 * @param stdClass $context
254 * @uses EDITOR_UNLIMITED_FILES hard-coded value for the 'maxfiles' option
257 public static function instruction_editors_options(stdclass $context) {
258 return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => -1,
259 'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0);
263 * Given the percent and the total, returns the number
265 * @param float $percent from 0 to 100
266 * @param float $total the 100% value
269 public static function percent_to_value($percent, $total) {
270 if ($percent < 0 or $percent > 100) {
271 throw new coding_exception('The percent can not be less than 0 or higher than 100');
274 return $total * $percent / 100;
278 * Returns an array of numeric values that can be used as maximum grades
280 * @return array Array of integers
282 public static function available_maxgrades_list() {
284 for ($i=100; $i>=0; $i--) {
291 * Returns the localized list of supported examples modes
295 public static function available_example_modes_list() {
297 $options[self::EXAMPLES_VOLUNTARY] = get_string('examplesvoluntary', 'workshop');
298 $options[self::EXAMPLES_BEFORE_SUBMISSION] = get_string('examplesbeforesubmission', 'workshop');
299 $options[self::EXAMPLES_BEFORE_ASSESSMENT] = get_string('examplesbeforeassessment', 'workshop');
304 * Returns the list of available grading strategy methods
306 * @return array ['string' => 'string']
308 public static function available_strategies_list() {
309 $installed = core_component::get_plugin_list('workshopform');
311 foreach ($installed as $strategy => $strategypath) {
312 if (file_exists($strategypath . '/lib.php')) {
313 $forms[$strategy] = get_string('pluginname', 'workshopform_' . $strategy);
320 * Returns the list of available grading evaluation methods
322 * @return array of (string)name => (string)localized title
324 public static function available_evaluators_list() {
326 foreach (core_component::get_plugin_list_with_file('workshopeval', 'lib.php', false) as $eval => $evalpath) {
327 $evals[$eval] = get_string('pluginname', 'workshopeval_' . $eval);
333 * Return an array of possible values of assessment dimension weight
335 * @return array of integers 0, 1, 2, ..., 16
337 public static function available_dimension_weights_list() {
339 for ($i=16; $i>=0; $i--) {
346 * Return an array of possible values of assessment weight
348 * Note there is no real reason why the maximum value here is 16. It used to be 10 in
349 * workshop 1.x and I just decided to use the same number as in the maximum weight of
350 * a single assessment dimension.
351 * The value looks reasonable, though. Teachers who would want to assign themselves
352 * higher weight probably do not want peer assessment really...
354 * @return array of integers 0, 1, 2, ..., 16
356 public static function available_assessment_weights_list() {
358 for ($i=16; $i>=0; $i--) {
365 * Helper function returning the greatest common divisor
371 public static function gcd($a, $b) {
372 return ($b == 0) ? ($a):(self::gcd($b, $a % $b));
376 * Helper function returning the least common multiple
382 public static function lcm($a, $b) {
383 return ($a / self::gcd($a,$b)) * $b;
387 * Returns an object suitable for strings containing dates/times
389 * The returned object contains properties date, datefullshort, datetime, ... containing the given
390 * timestamp formatted using strftimedate, strftimedatefullshort, strftimedatetime, ... from the
391 * current lang's langconfig.php
392 * This allows translators and administrators customize the date/time format.
394 * @param int $timestamp the timestamp in UTC
397 public static function timestamp_formats($timestamp) {
398 $formats = array('date', 'datefullshort', 'dateshort', 'datetime',
399 'datetimeshort', 'daydate', 'daydatetime', 'dayshort', 'daytime',
400 'monthyear', 'recent', 'recentfull', 'time');
402 foreach ($formats as $format) {
403 $a->{$format} = userdate($timestamp, get_string('strftime'.$format, 'langconfig'));
405 $day = userdate($timestamp, '%Y%m%d', 99, false);
406 $today = userdate(time(), '%Y%m%d', 99, false);
407 $tomorrow = userdate(time() + DAYSECS, '%Y%m%d', 99, false);
408 $yesterday = userdate(time() - DAYSECS, '%Y%m%d', 99, false);
409 $distance = (int)round(abs(time() - $timestamp) / DAYSECS);
410 if ($day == $today) {
411 $a->distanceday = get_string('daystoday', 'workshop');
412 } elseif ($day == $yesterday) {
413 $a->distanceday = get_string('daysyesterday', 'workshop');
414 } elseif ($day < $today) {
415 $a->distanceday = get_string('daysago', 'workshop', $distance);
416 } elseif ($day == $tomorrow) {
417 $a->distanceday = get_string('daystomorrow', 'workshop');
418 } elseif ($day > $today) {
419 $a->distanceday = get_string('daysleft', 'workshop', $distance);
425 * Converts the argument into an array (list) of file extensions.
427 * The list can be separated by whitespace, end of lines, commas colons and semicolons.
428 * Empty values are not returned. Values are converted to lowercase.
429 * Duplicates are removed. Glob evaluation is not supported.
431 * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
432 * @param string|array $extensions list of file extensions
433 * @return array of strings
435 public static function normalize_file_extensions($extensions) {
437 debugging('The method workshop::normalize_file_extensions() is deprecated.
438 Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
440 if ($extensions === '') {
444 if (!is_array($extensions)) {
445 $extensions = preg_split('/[\s,;:"\']+/', $extensions, null, PREG_SPLIT_NO_EMPTY);
448 foreach ($extensions as $i => $extension) {
449 $extension = str_replace('*.', '', $extension);
450 $extension = strtolower($extension);
451 $extension = ltrim($extension, '.');
452 $extension = trim($extension);
453 $extensions[$i] = $extension;
456 foreach ($extensions as $i => $extension) {
457 if (strpos($extension, '*') !== false or strpos($extension, '?') !== false) {
458 unset($extensions[$i]);
462 $extensions = array_filter($extensions, 'strlen');
463 $extensions = array_keys(array_flip($extensions));
465 foreach ($extensions as $i => $extension) {
466 $extensions[$i] = '.'.$extension;
473 * Cleans the user provided list of file extensions.
475 * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
476 * @param string $extensions
479 public static function clean_file_extensions($extensions) {
481 debugging('The method workshop::clean_file_extensions() is deprecated.
482 Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
484 $extensions = self::normalize_file_extensions($extensions);
486 foreach ($extensions as $i => $extension) {
487 $extensions[$i] = ltrim($extension, '.');
490 return implode(', ', $extensions);
494 * Check given file types and return invalid/unknown ones.
496 * Empty whitelist is interpretted as "any extension is valid".
498 * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
499 * @param string|array $extensions list of file extensions
500 * @param string|array $whitelist list of valid extensions
501 * @return array list of invalid extensions not found in the whitelist
503 public static function invalid_file_extensions($extensions, $whitelist) {
505 debugging('The method workshop::invalid_file_extensions() is deprecated.
506 Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
508 $extensions = self::normalize_file_extensions($extensions);
509 $whitelist = self::normalize_file_extensions($whitelist);
511 if (empty($extensions) or empty($whitelist)) {
515 // Return those items from $extensions that are not present in $whitelist.
516 return array_keys(array_diff_key(array_flip($extensions), array_flip($whitelist)));
520 * Is the file have allowed to be uploaded to the workshop?
522 * Empty whitelist is interpretted as "any file type is allowed" rather
523 * than "no file can be uploaded".
525 * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
526 * @param string $filename the file name
527 * @param string|array $whitelist list of allowed file extensions
530 public static function is_allowed_file_type($filename, $whitelist) {
532 debugging('The method workshop::is_allowed_file_type() is deprecated.
533 Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
535 $whitelist = self::normalize_file_extensions($whitelist);
537 if (empty($whitelist)) {
541 $haystack = strrev(trim(strtolower($filename)));
543 foreach ($whitelist as $extension) {
544 if (strpos($haystack, strrev($extension)) === 0) {
545 // The file name ends with the extension.
553 ////////////////////////////////////////////////////////////////////////////////
555 ////////////////////////////////////////////////////////////////////////////////
558 * Fetches all enrolled users with the capability mod/workshop:submit in the current workshop
560 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
561 * Only users with the active enrolment are returned.
563 * @param bool $musthavesubmission if true, return only users who have already submitted
564 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
565 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
566 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
567 * @return array array[userid] => stdClass
569 public function get_potential_authors($musthavesubmission=true, $groupid=0, $limitfrom=0, $limitnum=0) {
572 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
578 list($sort, $sortparams) = users_order_by_sql('tmp');
583 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
587 * Returns the total number of users that would be fetched by {@link self::get_potential_authors()}
589 * @param bool $musthavesubmission if true, count only users who have already submitted
590 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
593 public function count_potential_authors($musthavesubmission=true, $groupid=0) {
596 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
602 $sql = "SELECT COUNT(*)
605 return $DB->count_records_sql($sql, $params);
609 * Fetches all enrolled users with the capability mod/workshop:peerassess in the current workshop
611 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
612 * Only users with the active enrolment are returned.
614 * @param bool $musthavesubmission if true, return only users who have already submitted
615 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
616 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
617 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
618 * @return array array[userid] => stdClass
620 public function get_potential_reviewers($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
623 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
629 list($sort, $sortparams) = users_order_by_sql('tmp');
634 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
638 * Returns the total number of users that would be fetched by {@link self::get_potential_reviewers()}
640 * @param bool $musthavesubmission if true, count only users who have already submitted
641 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
644 public function count_potential_reviewers($musthavesubmission=false, $groupid=0) {
647 list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
653 $sql = "SELECT COUNT(*)
656 return $DB->count_records_sql($sql, $params);
660 * Fetches all enrolled users that are authors or reviewers (or both) in the current workshop
662 * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
663 * Only users with the active enrolment are returned.
665 * @see self::get_potential_authors()
666 * @see self::get_potential_reviewers()
667 * @param bool $musthavesubmission if true, return only users who have already submitted
668 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
669 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
670 * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
671 * @return array array[userid] => stdClass
673 public function get_participants($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
676 list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
682 list($sort, $sortparams) = users_order_by_sql('tmp');
687 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
691 * Returns the total number of records that would be returned by {@link self::get_participants()}
693 * @param bool $musthavesubmission if true, return only users who have already submitted
694 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
697 public function count_participants($musthavesubmission=false, $groupid=0) {
700 list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
706 $sql = "SELECT COUNT(*)
709 return $DB->count_records_sql($sql, $params);
713 * Checks if the given user is an actively enrolled participant in the workshop
715 * @param int $userid, defaults to the current $USER
718 public function is_participant($userid=null) {
721 if (is_null($userid)) {
725 list($sql, $params) = $this->get_participants_sql();
731 $sql = "SELECT COUNT(*)
733 JOIN ({$sql}) pxx ON uxx.id = pxx.id
734 WHERE uxx.id = :uxxid";
735 $params['uxxid'] = $userid;
737 if ($DB->count_records_sql($sql, $params)) {
745 * Groups the given users by the group membership
747 * This takes the module grouping settings into account. If a grouping is
748 * set, returns only groups withing the course module grouping. Always
749 * returns group [0] with all the given users.
751 * @param array $users array[userid] => stdclass{->id ->lastname ->firstname}
752 * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname}
754 public function get_grouped($users) {
758 $grouped = array(); // grouped users to be returned
762 if ($this->cm->groupingid) {
763 // Group workshop set to specified grouping - only consider groups
764 // within this grouping, and leave out users who aren't members of
766 $groupingid = $this->cm->groupingid;
767 // All users that are members of at least one group will be
768 // added into a virtual group id 0
769 $grouped[0] = array();
772 // there is no need to be member of a group so $grouped[0] will contain
774 $grouped[0] = $users;
776 $gmemberships = groups_get_all_groups($this->cm->course, array_keys($users), $groupingid,
777 'gm.id,gm.groupid,gm.userid');
778 foreach ($gmemberships as $gmembership) {
779 if (!isset($grouped[$gmembership->groupid])) {
780 $grouped[$gmembership->groupid] = array();
782 $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid];
783 $grouped[0][$gmembership->userid] = $users[$gmembership->userid];
789 * Returns the list of all allocations (i.e. assigned assessments) in the workshop
791 * Assessments of example submissions are ignored
795 public function get_allocations() {
798 $sql = 'SELECT a.id, a.submissionid, a.reviewerid, s.authorid
799 FROM {workshop_assessments} a
800 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
801 WHERE s.example = 0 AND s.workshopid = :workshopid';
802 $params = array('workshopid' => $this->id);
804 return $DB->get_records_sql($sql, $params);
808 * Returns the total number of records that would be returned by {@link self::get_submissions()}
810 * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
811 * @param int $groupid If non-zero, return only submissions by authors in the specified group
812 * @return int number of records
814 public function count_submissions($authorid='all', $groupid=0) {
817 $params = array('workshopid' => $this->id);
818 $sql = "SELECT COUNT(s.id)
819 FROM {workshop_submissions} s
820 JOIN {user} u ON (s.authorid = u.id)";
822 $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
823 $params['groupid'] = $groupid;
825 $sql .= " WHERE s.example = 0 AND s.workshopid = :workshopid";
827 if ('all' === $authorid) {
828 // no additional conditions
829 } elseif (!empty($authorid)) {
830 list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
831 $sql .= " AND authorid $usql";
832 $params = array_merge($params, $uparams);
834 // $authorid is empty
838 return $DB->count_records_sql($sql, $params);
843 * Returns submissions from this workshop
845 * Fetches data from {workshop_submissions} and adds some useful information from other
846 * tables. Does not return textual fields to prevent possible memory lack issues.
848 * @see self::count_submissions()
849 * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
850 * @param int $groupid If non-zero, return only submissions by authors in the specified group
851 * @param int $limitfrom Return a subset of records, starting at this point (optional)
852 * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
853 * @return array of records or an empty array
855 public function get_submissions($authorid='all', $groupid=0, $limitfrom=0, $limitnum=0) {
858 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
859 $gradeoverbyfields = user_picture::fields('t', null, 'gradeoverbyx', 'over');
860 $params = array('workshopid' => $this->id);
861 $sql = "SELECT s.id, s.workshopid, s.example, s.authorid, s.timecreated, s.timemodified,
862 s.title, s.grade, s.gradeover, s.gradeoverby, s.published,
863 $authorfields, $gradeoverbyfields
864 FROM {workshop_submissions} s
865 JOIN {user} u ON (s.authorid = u.id)";
867 $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
868 $params['groupid'] = $groupid;
870 $sql .= " LEFT JOIN {user} t ON (s.gradeoverby = t.id)
871 WHERE s.example = 0 AND s.workshopid = :workshopid";
873 if ('all' === $authorid) {
874 // no additional conditions
875 } elseif (!empty($authorid)) {
876 list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
877 $sql .= " AND authorid $usql";
878 $params = array_merge($params, $uparams);
880 // $authorid is empty
883 list($sort, $sortparams) = users_order_by_sql('u');
884 $sql .= " ORDER BY $sort";
886 return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
890 * Returns submissions from this workshop that are viewable by the current user (except example submissions).
892 * @param mixed $authorid int|array If set to [array of] integer, return submission[s] of the given user[s] only
893 * @param int $groupid If non-zero, return only submissions by authors in the specified group. 0 for all groups.
894 * @param int $limitfrom Return a subset of records, starting at this point (optional)
895 * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
896 * @return array of records and the total submissions count
899 public function get_visible_submissions($authorid = 0, $groupid = 0, $limitfrom = 0, $limitnum = 0) {
902 $submissions = array();
903 $select = "SELECT s.*";
904 $selectcount = "SELECT COUNT(s.id)";
905 $from = " FROM {workshop_submissions} s";
906 $params = array('workshopid' => $this->id);
908 // Check if the passed group (or all groups when groupid is 0) is visible by the current user.
909 if (!groups_group_visible($groupid, $this->course, $this->cm)) {
910 return array($submissions, 0);
914 $from .= " JOIN {groups_members} gm ON (gm.userid = s.authorid AND gm.groupid = :groupid)";
915 $params['groupid'] = $groupid;
917 $where = " WHERE s.workshopid = :workshopid AND s.example = 0";
919 if (!has_capability('mod/workshop:viewallsubmissions', $this->context)) {
920 // Check published submissions.
921 $workshopclosed = $this->phase == self::PHASE_CLOSED;
922 $canviewpublished = has_capability('mod/workshop:viewpublishedsubmissions', $this->context);
923 if ($workshopclosed && $canviewpublished) {
924 $published = " OR s.published = 1";
929 // Always get submissions I did or I provided feedback to.
930 $where .= " AND (s.authorid = :authorid OR s.gradeoverby = :graderid $published)";
931 $params['authorid'] = $USER->id;
932 $params['graderid'] = $USER->id;
935 // Now, user filtering.
936 if (!empty($authorid)) {
937 list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
938 $where .= " AND s.authorid $usql";
939 $params = array_merge($params, $uparams);
942 $order = " ORDER BY s.timecreated";
944 $totalcount = $DB->count_records_sql($selectcount.$from.$where, $params);
946 $submissions = $DB->get_records_sql($select.$from.$where.$order, $params, $limitfrom, $limitnum);
948 return array($submissions, $totalcount);
953 * Returns a submission record with the author's data
955 * @param int $id submission id
958 public function get_submission_by_id($id) {
961 // we intentionally check the workshopid here, too, so the workshop can't touch submissions
962 // from other instances
963 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
964 $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
965 $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
966 FROM {workshop_submissions} s
967 INNER JOIN {user} u ON (s.authorid = u.id)
968 LEFT JOIN {user} g ON (s.gradeoverby = g.id)
969 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.id = :id";
970 $params = array('workshopid' => $this->id, 'id' => $id);
971 return $DB->get_record_sql($sql, $params, MUST_EXIST);
975 * Returns a submission submitted by the given author
977 * @param int $id author id
978 * @return stdclass|false
980 public function get_submission_by_author($authorid) {
983 if (empty($authorid)) {
986 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
987 $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
988 $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
989 FROM {workshop_submissions} s
990 INNER JOIN {user} u ON (s.authorid = u.id)
991 LEFT JOIN {user} g ON (s.gradeoverby = g.id)
992 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.authorid = :authorid";
993 $params = array('workshopid' => $this->id, 'authorid' => $authorid);
994 return $DB->get_record_sql($sql, $params);
998 * Returns published submissions with their authors data
1000 * @return array of stdclass
1002 public function get_published_submissions($orderby='finalgrade DESC') {
1005 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
1006 $sql = "SELECT s.id, s.authorid, s.timecreated, s.timemodified,
1007 s.title, s.grade, s.gradeover, COALESCE(s.gradeover,s.grade) AS finalgrade,
1009 FROM {workshop_submissions} s
1010 INNER JOIN {user} u ON (s.authorid = u.id)
1011 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.published = 1
1013 $params = array('workshopid' => $this->id);
1014 return $DB->get_records_sql($sql, $params);
1018 * Returns full record of the given example submission
1020 * @param int $id example submission od
1023 public function get_example_by_id($id) {
1025 return $DB->get_record('workshop_submissions',
1026 array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST);
1030 * Returns the list of example submissions in this workshop with reference assessments attached
1032 * @return array of objects or an empty array
1033 * @see workshop::prepare_example_summary()
1035 public function get_examples_for_manager() {
1038 $sql = 'SELECT s.id, s.title,
1039 a.id AS assessmentid, a.grade, a.gradinggrade
1040 FROM {workshop_submissions} s
1041 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.weight = 1)
1042 WHERE s.example = 1 AND s.workshopid = :workshopid
1044 return $DB->get_records_sql($sql, array('workshopid' => $this->id));
1048 * Returns the list of all example submissions in this workshop with the information of assessments done by the given user
1050 * @param int $reviewerid user id
1051 * @return array of objects, indexed by example submission id
1052 * @see workshop::prepare_example_summary()
1054 public function get_examples_for_reviewer($reviewerid) {
1057 if (empty($reviewerid)) {
1060 $sql = 'SELECT s.id, s.title,
1061 a.id AS assessmentid, a.grade, a.gradinggrade
1062 FROM {workshop_submissions} s
1063 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.reviewerid = :reviewerid AND a.weight = 0)
1064 WHERE s.example = 1 AND s.workshopid = :workshopid
1066 return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid));
1070 * Prepares renderable submission component
1072 * @param stdClass $record required by {@see workshop_submission}
1073 * @param bool $showauthor show the author-related information
1074 * @return workshop_submission
1076 public function prepare_submission(stdClass $record, $showauthor = false) {
1078 $submission = new workshop_submission($this, $record, $showauthor);
1079 $submission->url = $this->submission_url($record->id);
1085 * Prepares renderable submission summary component
1087 * @param stdClass $record required by {@see workshop_submission_summary}
1088 * @param bool $showauthor show the author-related information
1089 * @return workshop_submission_summary
1091 public function prepare_submission_summary(stdClass $record, $showauthor = false) {
1093 $summary = new workshop_submission_summary($this, $record, $showauthor);
1094 $summary->url = $this->submission_url($record->id);
1100 * Prepares renderable example submission component
1102 * @param stdClass $record required by {@see workshop_example_submission}
1103 * @return workshop_example_submission
1105 public function prepare_example_submission(stdClass $record) {
1107 $example = new workshop_example_submission($this, $record);
1113 * Prepares renderable example submission summary component
1115 * If the example is editable, the caller must set the 'editable' flag explicitly.
1117 * @param stdClass $example as returned by {@link workshop::get_examples_for_manager()} or {@link workshop::get_examples_for_reviewer()}
1118 * @return workshop_example_submission_summary to be rendered
1120 public function prepare_example_summary(stdClass $example) {
1122 $summary = new workshop_example_submission_summary($this, $example);
1124 if (is_null($example->grade)) {
1125 $summary->status = 'notgraded';
1126 $summary->assesslabel = get_string('assess', 'workshop');
1128 $summary->status = 'graded';
1129 $summary->assesslabel = get_string('reassess', 'workshop');
1132 $summary->gradeinfo = new stdclass();
1133 $summary->gradeinfo->received = $this->real_grade($example->grade);
1134 $summary->gradeinfo->max = $this->real_grade(100);
1136 $summary->url = new moodle_url($this->exsubmission_url($example->id));
1137 $summary->editurl = new moodle_url($this->exsubmission_url($example->id), array('edit' => 'on'));
1138 $summary->assessurl = new moodle_url($this->exsubmission_url($example->id), array('assess' => 'on', 'sesskey' => sesskey()));
1144 * Prepares renderable assessment component
1146 * The $options array supports the following keys:
1147 * showauthor - should the author user info be available for the renderer
1148 * showreviewer - should the reviewer user info be available for the renderer
1149 * showform - show the assessment form if it is available
1150 * showweight - should the assessment weight be available for the renderer
1152 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1153 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1154 * @param array $options
1155 * @return workshop_assessment
1157 public function prepare_assessment(stdClass $record, $form, array $options = array()) {
1159 $assessment = new workshop_assessment($this, $record, $options);
1160 $assessment->url = $this->assess_url($record->id);
1161 $assessment->maxgrade = $this->real_grade(100);
1163 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1164 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1167 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1168 $assessment->form = $form;
1171 if (empty($options['showweight'])) {
1172 $assessment->weight = null;
1175 if (!is_null($record->grade)) {
1176 $assessment->realgrade = $this->real_grade($record->grade);
1183 * Prepares renderable example submission's assessment component
1185 * The $options array supports the following keys:
1186 * showauthor - should the author user info be available for the renderer
1187 * showreviewer - should the reviewer user info be available for the renderer
1188 * showform - show the assessment form if it is available
1190 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1191 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1192 * @param array $options
1193 * @return workshop_example_assessment
1195 public function prepare_example_assessment(stdClass $record, $form = null, array $options = array()) {
1197 $assessment = new workshop_example_assessment($this, $record, $options);
1198 $assessment->url = $this->exassess_url($record->id);
1199 $assessment->maxgrade = $this->real_grade(100);
1201 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1202 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1205 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1206 $assessment->form = $form;
1209 if (!is_null($record->grade)) {
1210 $assessment->realgrade = $this->real_grade($record->grade);
1213 $assessment->weight = null;
1219 * Prepares renderable example submission's reference assessment component
1221 * The $options array supports the following keys:
1222 * showauthor - should the author user info be available for the renderer
1223 * showreviewer - should the reviewer user info be available for the renderer
1224 * showform - show the assessment form if it is available
1226 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1227 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1228 * @param array $options
1229 * @return workshop_example_reference_assessment
1231 public function prepare_example_reference_assessment(stdClass $record, $form = null, array $options = array()) {
1233 $assessment = new workshop_example_reference_assessment($this, $record, $options);
1234 $assessment->maxgrade = $this->real_grade(100);
1236 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1237 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1240 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1241 $assessment->form = $form;
1244 if (!is_null($record->grade)) {
1245 $assessment->realgrade = $this->real_grade($record->grade);
1248 $assessment->weight = null;
1254 * Removes the submission and all relevant data
1256 * @param stdClass $submission record to delete
1259 public function delete_submission(stdclass $submission) {
1262 $assessments = $DB->get_records('workshop_assessments', array('submissionid' => $submission->id), '', 'id');
1263 $this->delete_assessment(array_keys($assessments));
1265 $fs = get_file_storage();
1266 $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_content', $submission->id);
1267 $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
1269 $DB->delete_records('workshop_submissions', array('id' => $submission->id));
1271 // Event information.
1273 'context' => $this->context,
1274 'courseid' => $this->course->id,
1275 'relateduserid' => $submission->authorid,
1277 'submissiontitle' => $submission->title
1280 $params['objectid'] = $submission->id;
1281 $event = \mod_workshop\event\submission_deleted::create($params);
1282 $event->add_record_snapshot('workshop', $this->dbrecord);
1287 * Returns the list of all assessments in the workshop with some data added
1289 * Fetches data from {workshop_assessments} and adds some useful information from other
1290 * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory
1293 * @return array [assessmentid] => assessment stdclass
1295 public function get_all_assessments() {
1298 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1299 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1300 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1301 list($sort, $params) = users_order_by_sql('reviewer');
1302 $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified,
1303 a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby,
1304 $reviewerfields, $authorfields, $overbyfields,
1306 FROM {workshop_assessments} a
1307 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1308 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1309 INNER JOIN {user} author ON (s.authorid = author.id)
1310 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1311 WHERE s.workshopid = :workshopid AND s.example = 0
1313 $params['workshopid'] = $this->id;
1315 return $DB->get_records_sql($sql, $params);
1319 * Get the complete information about the given assessment
1321 * @param int $id Assessment ID
1324 public function get_assessment_by_id($id) {
1327 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1328 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1329 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1330 $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1331 FROM {workshop_assessments} a
1332 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1333 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1334 INNER JOIN {user} author ON (s.authorid = author.id)
1335 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1336 WHERE a.id = :id AND s.workshopid = :workshopid";
1337 $params = array('id' => $id, 'workshopid' => $this->id);
1339 return $DB->get_record_sql($sql, $params, MUST_EXIST);
1343 * Get the complete information about the user's assessment of the given submission
1345 * @param int $sid submission ID
1346 * @param int $uid user ID of the reviewer
1347 * @return false|stdclass false if not found, stdclass otherwise
1349 public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
1352 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1353 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1354 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1355 $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1356 FROM {workshop_assessments} a
1357 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1358 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1359 INNER JOIN {user} author ON (s.authorid = author.id)
1360 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1361 WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid";
1362 $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id);
1364 return $DB->get_record_sql($sql, $params, IGNORE_MISSING);
1368 * Get the complete information about all assessments of the given submission
1370 * @param int $submissionid
1373 public function get_assessments_of_submission($submissionid) {
1376 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1377 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1378 list($sort, $params) = users_order_by_sql('reviewer');
1379 $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields
1380 FROM {workshop_assessments} a
1381 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1382 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1383 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1384 WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid
1386 $params['submissionid'] = $submissionid;
1387 $params['workshopid'] = $this->id;
1389 return $DB->get_records_sql($sql, $params);
1393 * Get the complete information about all assessments allocated to the given reviewer
1395 * @param int $reviewerid
1398 public function get_assessments_by_reviewer($reviewerid) {
1401 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1402 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
1403 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1404 $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields,
1405 s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated,
1406 s.timemodified AS submissionmodified
1407 FROM {workshop_assessments} a
1408 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1409 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1410 INNER JOIN {user} author ON (s.authorid = author.id)
1411 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1412 WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid";
1413 $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id);
1415 return $DB->get_records_sql($sql, $params);
1419 * Get allocated assessments not graded yet by the given reviewer
1421 * @see self::get_assessments_by_reviewer()
1422 * @param int $reviewerid the reviewer id
1423 * @param null|int|array $exclude optional assessment id (or list of them) to be excluded
1426 public function get_pending_assessments_by_reviewer($reviewerid, $exclude = null) {
1428 $assessments = $this->get_assessments_by_reviewer($reviewerid);
1430 foreach ($assessments as $id => $assessment) {
1431 if (!is_null($assessment->grade)) {
1432 unset($assessments[$id]);
1435 if (!empty($exclude)) {
1436 if (is_array($exclude) and in_array($id, $exclude)) {
1437 unset($assessments[$id]);
1439 } else if ($id == $exclude) {
1440 unset($assessments[$id]);
1446 return $assessments;
1450 * Allocate a submission to a user for review
1452 * @param stdClass $submission Submission object with at least id property
1453 * @param int $reviewerid User ID
1454 * @param int $weight of the new assessment, from 0 to 16
1455 * @param bool $bulk repeated inserts into DB expected
1456 * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists
1458 public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
1461 if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
1462 return self::ALLOCATION_EXISTS;
1465 $weight = (int)$weight;
1474 $assessment = new stdclass();
1475 $assessment->submissionid = $submission->id;
1476 $assessment->reviewerid = $reviewerid;
1477 $assessment->timecreated = $now; // do not set timemodified here
1478 $assessment->weight = $weight;
1479 $assessment->feedbackauthorformat = editors_get_preferred_format();
1480 $assessment->feedbackreviewerformat = editors_get_preferred_format();
1482 return $DB->insert_record('workshop_assessments', $assessment, true, $bulk);
1486 * Delete assessment record or records.
1488 * Removes associated records from the workshop_grades table, too.
1490 * @param int|array $id assessment id or array of assessments ids
1491 * @todo Give grading strategy plugins a chance to clean up their data, too.
1494 public function delete_assessment($id) {
1501 $fs = get_file_storage();
1503 if (is_array($id)) {
1504 $DB->delete_records_list('workshop_grades', 'assessmentid', $id);
1505 foreach ($id as $itemid) {
1506 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $itemid);
1507 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $itemid);
1509 $DB->delete_records_list('workshop_assessments', 'id', $id);
1512 $DB->delete_records('workshop_grades', array('assessmentid' => $id));
1513 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $id);
1514 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $id);
1515 $DB->delete_records('workshop_assessments', array('id' => $id));
1522 * Returns instance of grading strategy class
1524 * @return stdclass Instance of a grading strategy
1526 public function grading_strategy_instance() {
1527 global $CFG; // because we require other libs here
1529 if (is_null($this->strategyinstance)) {
1530 $strategylib = __DIR__ . '/form/' . $this->strategy . '/lib.php';
1531 if (is_readable($strategylib)) {
1532 require_once($strategylib);
1534 throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
1536 $classname = 'workshop_' . $this->strategy . '_strategy';
1537 $this->strategyinstance = new $classname($this);
1538 if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) {
1539 throw new coding_exception($classname . ' does not implement workshop_strategy interface');
1542 return $this->strategyinstance;
1546 * Sets the current evaluation method to the given plugin.
1548 * @param string $method the name of the workshopeval subplugin
1549 * @return bool true if successfully set
1550 * @throws coding_exception if attempting to set a non-installed evaluation method
1552 public function set_grading_evaluation_method($method) {
1555 $evaluationlib = __DIR__ . '/eval/' . $method . '/lib.php';
1557 if (is_readable($evaluationlib)) {
1558 $this->evaluationinstance = null;
1559 $this->evaluation = $method;
1560 $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id));
1564 throw new coding_exception('Attempt to set a non-existing evaluation method.');
1568 * Returns instance of grading evaluation class
1570 * @return stdclass Instance of a grading evaluation
1572 public function grading_evaluation_instance() {
1573 global $CFG; // because we require other libs here
1575 if (is_null($this->evaluationinstance)) {
1576 if (empty($this->evaluation)) {
1577 $this->evaluation = 'best';
1579 $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
1580 if (is_readable($evaluationlib)) {
1581 require_once($evaluationlib);
1583 // Fall back in case the subplugin is not available.
1584 $this->evaluation = 'best';
1585 $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
1586 if (is_readable($evaluationlib)) {
1587 require_once($evaluationlib);
1589 // Fall back in case the subplugin is not available any more.
1590 throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
1593 $classname = 'workshop_' . $this->evaluation . '_evaluation';
1594 $this->evaluationinstance = new $classname($this);
1595 if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) {
1596 throw new coding_exception($classname . ' does not extend workshop_evaluation class');
1599 return $this->evaluationinstance;
1603 * Returns instance of submissions allocator
1605 * @param string $method The name of the allocation method, must be PARAM_ALPHA
1606 * @return stdclass Instance of submissions allocator
1608 public function allocator_instance($method) {
1609 global $CFG; // because we require other libs here
1611 $allocationlib = __DIR__ . '/allocation/' . $method . '/lib.php';
1612 if (is_readable($allocationlib)) {
1613 require_once($allocationlib);
1615 throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
1617 $classname = 'workshop_' . $method . '_allocator';
1618 return new $classname($this);
1622 * @return moodle_url of this workshop's view page
1624 public function view_url() {
1626 return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
1630 * @return moodle_url of the page for editing this workshop's grading form
1632 public function editform_url() {
1634 return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
1638 * @return moodle_url of the page for previewing this workshop's grading form
1640 public function previewform_url() {
1642 return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
1646 * @param int $assessmentid The ID of assessment record
1647 * @return moodle_url of the assessment page
1649 public function assess_url($assessmentid) {
1651 $assessmentid = clean_param($assessmentid, PARAM_INT);
1652 return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
1656 * @param int $assessmentid The ID of assessment record
1657 * @return moodle_url of the example assessment page
1659 public function exassess_url($assessmentid) {
1661 $assessmentid = clean_param($assessmentid, PARAM_INT);
1662 return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
1666 * @return moodle_url of the page to view a submission, defaults to the own one
1668 public function submission_url($id=null) {
1670 return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
1674 * @param int $id example submission id
1675 * @return moodle_url of the page to view an example submission
1677 public function exsubmission_url($id) {
1679 return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
1683 * @param int $sid submission id
1684 * @param array $aid of int assessment ids
1685 * @return moodle_url of the page to compare assessments of the given submission
1687 public function compare_url($sid, array $aids) {
1690 $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
1692 foreach ($aids as $aid) {
1693 $url->param("aid{$i}", $aid);
1700 * @param int $sid submission id
1701 * @param int $aid assessment id
1702 * @return moodle_url of the page to compare the reference assessments of the given example submission
1704 public function excompare_url($sid, $aid) {
1706 return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
1710 * @return moodle_url of the mod_edit form
1712 public function updatemod_url() {
1714 return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
1718 * @param string $method allocation method
1719 * @return moodle_url to the allocation page
1721 public function allocation_url($method=null) {
1723 $params = array('cmid' => $this->cm->id);
1724 if (!empty($method)) {
1725 $params['method'] = $method;
1727 return new moodle_url('/mod/workshop/allocation.php', $params);
1731 * @param int $phasecode The internal phase code
1732 * @return moodle_url of the script to change the current phase to $phasecode
1734 public function switchphase_url($phasecode) {
1736 $phasecode = clean_param($phasecode, PARAM_INT);
1737 return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
1741 * @return moodle_url to the aggregation page
1743 public function aggregate_url() {
1745 return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
1749 * @return moodle_url of this workshop's toolbox page
1751 public function toolbox_url($tool) {
1753 return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
1757 * Workshop wrapper around {@see add_to_log()}
1758 * @deprecated since 2.7 Please use the provided event classes for logging actions.
1760 * @param string $action to be logged
1761 * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends
1762 * @param mixed $info additional info, usually id in a table
1763 * @param bool $return true to return the arguments for add_to_log.
1764 * @return void|array array of arguments for add_to_log if $return is true
1766 public function log($action, moodle_url $url = null, $info = null, $return = false) {
1767 debugging('The log method is now deprecated, please use event classes instead', DEBUG_DEVELOPER);
1769 if (is_null($url)) {
1770 $url = $this->view_url();
1773 if (is_null($info)) {
1777 $logurl = $this->log_convert_url($url);
1778 $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
1782 call_user_func_array('add_to_log', $args);
1786 * Is the given user allowed to create their submission?
1788 * @param int $userid
1791 public function creating_submission_allowed($userid) {
1794 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1796 if ($this->latesubmissions) {
1797 if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) {
1798 // late submissions are allowed in the submission and assessment phase only
1801 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1802 // late submissions are not allowed before the submission start
1808 if ($this->phase != self::PHASE_SUBMISSION) {
1809 // submissions are allowed during the submission phase only
1812 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1813 // if enabled, submitting is not allowed before the date/time defined in the mod_form
1816 if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) {
1817 // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed
1825 * Is the given user allowed to modify their existing submission?
1827 * @param int $userid
1830 public function modifying_submission_allowed($userid) {
1833 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1835 if ($this->phase != self::PHASE_SUBMISSION) {
1836 // submissions can be edited during the submission phase only
1839 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1840 // if enabled, re-submitting is not allowed before the date/time defined in the mod_form
1843 if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) {
1844 // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed
1851 * Is the given reviewer allowed to create/edit their assessments?
1853 * @param int $userid
1856 public function assessing_allowed($userid) {
1858 if ($this->phase != self::PHASE_ASSESSMENT) {
1859 // assessing is allowed in the assessment phase only, unless the user is a teacher
1860 // providing additional assessment during the evaluation phase
1861 if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) {
1867 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1869 if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) {
1870 // if enabled, assessing is not allowed before the date/time defined in the mod_form
1873 if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) {
1874 // if enabled, assessing is not allowed after the date/time defined in the mod_form
1877 // here we go, assessing is allowed
1882 * Are reviewers allowed to create/edit their assessments of the example submissions?
1884 * Returns null if example submissions are not enabled in this workshop. Otherwise returns
1885 * true or false. Note this does not check other conditions like the number of already
1886 * assessed examples, examples mode etc.
1890 public function assessing_examples_allowed() {
1891 if (empty($this->useexamples)) {
1894 if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
1897 if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
1900 if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
1907 * Are the peer-reviews available to the authors?
1911 public function assessments_available() {
1912 return $this->phase == self::PHASE_CLOSED;
1916 * Switch to a new workshop phase
1918 * Modifies the underlying database record. You should terminate the script shortly after calling this.
1920 * @param int $newphase new phase code
1921 * @return bool true if success, false otherwise
1923 public function switch_phase($newphase) {
1926 $known = $this->available_phases_list();
1927 if (!isset($known[$newphase])) {
1931 if (self::PHASE_CLOSED == $newphase) {
1932 // push the grades into the gradebook
1933 $workshop = new stdclass();
1934 foreach ($this as $property => $value) {
1935 $workshop->{$property} = $value;
1937 $workshop->course = $this->course->id;
1938 $workshop->cmidnumber = $this->cm->id;
1939 $workshop->modname = 'workshop';
1940 workshop_update_grades($workshop);
1943 $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
1944 $this->phase = $newphase;
1946 'objectid' => $this->id,
1947 'context' => $this->context,
1949 'workshopphase' => $this->phase
1952 $event = \mod_workshop\event\phase_switched::create($eventdata);
1958 * Saves a raw grade for submission as calculated from the assessment form fields
1960 * @param array $assessmentid assessment record id, must exists
1961 * @param mixed $grade raw percentual grade from 0.00000 to 100.00000
1962 * @return false|float the saved grade
1964 public function set_peer_grade($assessmentid, $grade) {
1967 if (is_null($grade)) {
1970 $data = new stdclass();
1971 $data->id = $assessmentid;
1972 $data->grade = $grade;
1973 $data->timemodified = time();
1974 $DB->update_record('workshop_assessments', $data);
1979 * Prepares data object with all workshop grades to be rendered
1981 * @param int $userid the user we are preparing the report for
1982 * @param int $groupid if non-zero, prepare the report for the given group only
1983 * @param int $page the current page (for the pagination)
1984 * @param int $perpage participants per page (for the pagination)
1985 * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
1986 * @param string $sorthow ASC|DESC
1987 * @return stdclass data for the renderer
1989 public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
1992 $canviewall = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
1993 $isparticipant = $this->is_participant($userid);
1995 if (!$canviewall and !$isparticipant) {
1996 // who the hell is this?
2000 if (!in_array($sortby, array('lastname', 'firstname', 'submissiontitle', 'submissionmodified',
2001 'submissiongrade', 'gradinggrade'))) {
2002 $sortby = 'lastname';
2005 if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
2009 // get the list of user ids to be displayed
2011 $participants = $this->get_participants(false, $groupid);
2013 // this is an ordinary workshop participant (aka student) - display the report just for him/her
2014 $participants = array($userid => (object)array('id' => $userid));
2017 // we will need to know the number of all records later for the pagination purposes
2018 $numofparticipants = count($participants);
2020 if ($numofparticipants > 0) {
2021 // load all fields which can be used for sorting and paginate the records
2022 list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
2023 $params['workshopid1'] = $this->id;
2024 $params['workshopid2'] = $this->id;
2026 $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
2027 foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
2028 $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
2030 $sqlsort = implode(',', $sqlsort);
2031 $picturefields = user_picture::fields('u', array(), 'userid');
2032 $sql = "SELECT $picturefields, s.title AS submissiontitle, s.timemodified AS submissionmodified,
2033 s.grade AS submissiongrade, ag.gradinggrade
2035 LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)
2036 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)
2037 WHERE u.id $participantids
2039 $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
2041 $participants = array();
2044 // this will hold the information needed to display user names and pictures
2045 $userinfo = array();
2047 // get the user details for all participants to display
2048 $additionalnames = get_all_user_name_fields();
2049 foreach ($participants as $participant) {
2050 if (!isset($userinfo[$participant->userid])) {
2051 $userinfo[$participant->userid] = new stdclass();
2052 $userinfo[$participant->userid]->id = $participant->userid;
2053 $userinfo[$participant->userid]->picture = $participant->picture;
2054 $userinfo[$participant->userid]->imagealt = $participant->imagealt;
2055 $userinfo[$participant->userid]->email = $participant->email;
2056 foreach ($additionalnames as $addname) {
2057 $userinfo[$participant->userid]->$addname = $participant->$addname;
2062 // load the submissions details
2063 $submissions = $this->get_submissions(array_keys($participants));
2065 // get the user details for all moderators (teachers) that have overridden a submission grade
2066 foreach ($submissions as $submission) {
2067 if (!isset($userinfo[$submission->gradeoverby])) {
2068 $userinfo[$submission->gradeoverby] = new stdclass();
2069 $userinfo[$submission->gradeoverby]->id = $submission->gradeoverby;
2070 $userinfo[$submission->gradeoverby]->picture = $submission->overpicture;
2071 $userinfo[$submission->gradeoverby]->imagealt = $submission->overimagealt;
2072 $userinfo[$submission->gradeoverby]->email = $submission->overemail;
2073 foreach ($additionalnames as $addname) {
2074 $temp = 'over' . $addname;
2075 $userinfo[$submission->gradeoverby]->$addname = $submission->$temp;
2080 // get the user details for all reviewers of the displayed participants
2081 $reviewers = array();
2084 list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
2085 list($sort, $sortparams) = users_order_by_sql('r');
2086 $picturefields = user_picture::fields('r', array(), 'reviewerid');
2087 $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,
2088 $picturefields, s.id AS submissionid, s.authorid
2089 FROM {workshop_assessments} a
2090 JOIN {user} r ON (a.reviewerid = r.id)
2091 JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
2092 WHERE a.submissionid $submissionids
2093 ORDER BY a.weight DESC, $sort";
2094 $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
2095 foreach ($reviewers as $reviewer) {
2096 if (!isset($userinfo[$reviewer->reviewerid])) {
2097 $userinfo[$reviewer->reviewerid] = new stdclass();
2098 $userinfo[$reviewer->reviewerid]->id = $reviewer->reviewerid;
2099 $userinfo[$reviewer->reviewerid]->picture = $reviewer->picture;
2100 $userinfo[$reviewer->reviewerid]->imagealt = $reviewer->imagealt;
2101 $userinfo[$reviewer->reviewerid]->email = $reviewer->email;
2102 foreach ($additionalnames as $addname) {
2103 $userinfo[$reviewer->reviewerid]->$addname = $reviewer->$addname;
2109 // get the user details for all reviewees of the displayed participants
2110 $reviewees = array();
2111 if ($participants) {
2112 list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
2113 list($sort, $sortparams) = users_order_by_sql('e');
2114 $params['workshopid'] = $this->id;
2115 $picturefields = user_picture::fields('e', array(), 'authorid');
2116 $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,
2117 s.id AS submissionid, $picturefields
2119 JOIN {workshop_assessments} a ON (a.reviewerid = u.id)
2120 JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
2121 JOIN {user} e ON (s.authorid = e.id)
2122 WHERE u.id $participantids AND s.workshopid = :workshopid
2123 ORDER BY a.weight DESC, $sort";
2124 $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
2125 foreach ($reviewees as $reviewee) {
2126 if (!isset($userinfo[$reviewee->authorid])) {
2127 $userinfo[$reviewee->authorid] = new stdclass();
2128 $userinfo[$reviewee->authorid]->id = $reviewee->authorid;
2129 $userinfo[$reviewee->authorid]->picture = $reviewee->picture;
2130 $userinfo[$reviewee->authorid]->imagealt = $reviewee->imagealt;
2131 $userinfo[$reviewee->authorid]->email = $reviewee->email;
2132 foreach ($additionalnames as $addname) {
2133 $userinfo[$reviewee->authorid]->$addname = $reviewee->$addname;
2139 // finally populate the object to be rendered
2140 $grades = $participants;
2142 foreach ($participants as $participant) {
2143 // set up default (null) values
2144 $grades[$participant->userid]->submissionid = null;
2145 $grades[$participant->userid]->submissiontitle = null;
2146 $grades[$participant->userid]->submissiongrade = null;
2147 $grades[$participant->userid]->submissiongradeover = null;
2148 $grades[$participant->userid]->submissiongradeoverby = null;
2149 $grades[$participant->userid]->submissionpublished = null;
2150 $grades[$participant->userid]->reviewedby = array();
2151 $grades[$participant->userid]->reviewerof = array();
2153 unset($participants);
2154 unset($participant);
2156 foreach ($submissions as $submission) {
2157 $grades[$submission->authorid]->submissionid = $submission->id;
2158 $grades[$submission->authorid]->submissiontitle = $submission->title;
2159 $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
2160 $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
2161 $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
2162 $grades[$submission->authorid]->submissionpublished = $submission->published;
2164 unset($submissions);
2167 foreach($reviewers as $reviewer) {
2168 $info = new stdclass();
2169 $info->userid = $reviewer->reviewerid;
2170 $info->assessmentid = $reviewer->assessmentid;
2171 $info->submissionid = $reviewer->submissionid;
2172 $info->grade = $this->real_grade($reviewer->grade);
2173 $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
2174 $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
2175 $info->weight = $reviewer->weight;
2176 $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
2181 foreach($reviewees as $reviewee) {
2182 $info = new stdclass();
2183 $info->userid = $reviewee->authorid;
2184 $info->assessmentid = $reviewee->assessmentid;
2185 $info->submissionid = $reviewee->submissionid;
2186 $info->grade = $this->real_grade($reviewee->grade);
2187 $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
2188 $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
2189 $info->weight = $reviewee->weight;
2190 $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
2195 foreach ($grades as $grade) {
2196 $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
2199 $data = new stdclass();
2200 $data->grades = $grades;
2201 $data->userinfo = $userinfo;
2202 $data->totalcount = $numofparticipants;
2203 $data->maxgrade = $this->real_grade(100);
2204 $data->maxgradinggrade = $this->real_grading_grade(100);
2209 * Calculates the real value of a grade
2211 * @param float $value percentual value from 0 to 100
2212 * @param float $max the maximal grade
2215 public function real_grade_value($value, $max) {
2217 if (is_null($value) or $value === '') {
2219 } elseif ($max == 0) {
2222 return format_float($max * $value / 100, $this->gradedecimals, $localized);
2227 * Calculates the raw (percentual) value from a real grade
2229 * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save
2230 * this value in a raw percentual form into DB
2231 * @param float $value given grade
2232 * @param float $max the maximal grade
2233 * @return float suitable to be stored as numeric(10,5)
2235 public function raw_grade_value($value, $max) {
2236 if (is_null($value) or $value === '') {
2239 if ($max == 0 or $value < 0) {
2242 $p = $value / $max * 100;
2246 return grade_floatval($p);
2250 * Calculates the real value of grade for submission
2252 * @param float $value percentual value from 0 to 100
2255 public function real_grade($value) {
2256 return $this->real_grade_value($value, $this->grade);
2260 * Calculates the real value of grade for assessment
2262 * @param float $value percentual value from 0 to 100
2265 public function real_grading_grade($value) {
2266 return $this->real_grade_value($value, $this->gradinggrade);
2270 * Sets the given grades and received grading grades to null
2272 * This does not clear the information about how the peers filled the assessment forms, but
2273 * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess
2274 * the allocated submissions.
2278 public function clear_assessments() {
2281 $submissions = $this->get_submissions();
2282 if (empty($submissions)) {
2283 // no money, no love
2286 $submissions = array_keys($submissions);
2287 list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED);
2288 $sql = "submissionid $sql";
2289 $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params);
2290 $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params);
2294 * Sets the grades for submission to null
2296 * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2299 public function clear_submission_grades($restrict=null) {
2302 $sql = "workshopid = :workshopid AND example = 0";
2303 $params = array('workshopid' => $this->id);
2305 if (is_null($restrict)) {
2306 // update all users - no more conditions
2307 } elseif (!empty($restrict)) {
2308 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2309 $sql .= " AND authorid $usql";
2310 $params = array_merge($params, $uparams);
2312 throw new coding_exception('Empty value is not a valid parameter here');
2315 $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
2319 * Calculates grades for submission for the given participant(s) and updates it in the database
2321 * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2324 public function aggregate_submission_grades($restrict=null) {
2327 // fetch a recordset with all assessments to process
2328 $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
2330 FROM {workshop_submissions} s
2331 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id)
2332 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2333 $params = array('workshopid' => $this->id);
2335 if (is_null($restrict)) {
2336 // update all users - no more conditions
2337 } elseif (!empty($restrict)) {
2338 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2339 $sql .= " AND s.authorid $usql";
2340 $params = array_merge($params, $uparams);
2342 throw new coding_exception('Empty value is not a valid parameter here');
2345 $sql .= ' ORDER BY s.id'; // this is important for bulk processing
2347 $rs = $DB->get_recordset_sql($sql, $params);
2348 $batch = array(); // will contain a set of all assessments of a single submission
2349 $previous = null; // a previous record in the recordset
2351 foreach ($rs as $current) {
2352 if (is_null($previous)) {
2353 // we are processing the very first record in the recordset
2354 $previous = $current;
2356 if ($current->submissionid == $previous->submissionid) {
2357 // we are still processing the current submission
2358 $batch[] = $current;
2360 // process all the assessments of a sigle submission
2361 $this->aggregate_submission_grades_process($batch);
2362 // and then start to process another submission
2363 $batch = array($current);
2364 $previous = $current;
2367 // do not forget to process the last batch!
2368 $this->aggregate_submission_grades_process($batch);
2373 * Sets the aggregated grades for assessment to null
2375 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2378 public function clear_grading_grades($restrict=null) {
2381 $sql = "workshopid = :workshopid";
2382 $params = array('workshopid' => $this->id);
2384 if (is_null($restrict)) {
2385 // update all users - no more conditions
2386 } elseif (!empty($restrict)) {
2387 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2388 $sql .= " AND userid $usql";
2389 $params = array_merge($params, $uparams);
2391 throw new coding_exception('Empty value is not a valid parameter here');
2394 $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
2398 * Calculates grades for assessment for the given participant(s)
2400 * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator.
2401 * The assessment weight is not taken into account here.
2403 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2406 public function aggregate_grading_grades($restrict=null) {
2409 // fetch a recordset with all assessments to process
2410 $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover,
2411 ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade
2412 FROM {workshop_assessments} a
2413 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
2414 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid)
2415 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2416 $params = array('workshopid' => $this->id);
2418 if (is_null($restrict)) {
2419 // update all users - no more conditions
2420 } elseif (!empty($restrict)) {
2421 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2422 $sql .= " AND a.reviewerid $usql";
2423 $params = array_merge($params, $uparams);
2425 throw new coding_exception('Empty value is not a valid parameter here');
2428 $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing
2430 $rs = $DB->get_recordset_sql($sql, $params);
2431 $batch = array(); // will contain a set of all assessments of a single submission
2432 $previous = null; // a previous record in the recordset
2434 foreach ($rs as $current) {
2435 if (is_null($previous)) {
2436 // we are processing the very first record in the recordset
2437 $previous = $current;
2439 if ($current->reviewerid == $previous->reviewerid) {
2440 // we are still processing the current reviewer
2441 $batch[] = $current;
2443 // process all the assessments of a sigle submission
2444 $this->aggregate_grading_grades_process($batch);
2445 // and then start to process another reviewer
2446 $batch = array($current);
2447 $previous = $current;
2450 // do not forget to process the last batch!
2451 $this->aggregate_grading_grades_process($batch);
2456 * Returns the mform the teachers use to put a feedback for the reviewer
2458 * @param moodle_url $actionurl
2459 * @param stdClass $assessment
2460 * @param array $options editable, editableweight, overridablegradinggrade
2461 * @return workshop_feedbackreviewer_form
2463 public function get_feedbackreviewer_form(moodle_url $actionurl, stdclass $assessment, $options=array()) {
2465 require_once(__DIR__ . '/feedbackreviewer_form.php');
2467 $current = new stdclass();
2468 $current->asid = $assessment->id;
2469 $current->weight = $assessment->weight;
2470 $current->gradinggrade = $this->real_grading_grade($assessment->gradinggrade);
2471 $current->gradinggradeover = $this->real_grading_grade($assessment->gradinggradeover);
2472 $current->feedbackreviewer = $assessment->feedbackreviewer;
2473 $current->feedbackreviewerformat = $assessment->feedbackreviewerformat;
2474 if (is_null($current->gradinggrade)) {
2475 $current->gradinggrade = get_string('nullgrade', 'workshop');
2477 if (!isset($options['editable'])) {
2478 $editable = true; // by default
2480 $editable = (bool)$options['editable'];
2483 // prepare wysiwyg editor
2484 $current = file_prepare_standard_editor($current, 'feedbackreviewer', array());
2486 return new workshop_feedbackreviewer_form($actionurl,
2487 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2488 'post', '', null, $editable);
2492 * Returns the mform the teachers use to put a feedback for the author on their submission
2494 * @param moodle_url $actionurl
2495 * @param stdClass $submission
2496 * @param array $options editable
2497 * @return workshop_feedbackauthor_form
2499 public function get_feedbackauthor_form(moodle_url $actionurl, stdclass $submission, $options=array()) {
2501 require_once(__DIR__ . '/feedbackauthor_form.php');
2503 $current = new stdclass();
2504 $current->submissionid = $submission->id;
2505 $current->published = $submission->published;
2506 $current->grade = $this->real_grade($submission->grade);
2507 $current->gradeover = $this->real_grade($submission->gradeover);
2508 $current->feedbackauthor = $submission->feedbackauthor;
2509 $current->feedbackauthorformat = $submission->feedbackauthorformat;
2510 if (is_null($current->grade)) {
2511 $current->grade = get_string('nullgrade', 'workshop');
2513 if (!isset($options['editable'])) {
2514 $editable = true; // by default
2516 $editable = (bool)$options['editable'];
2519 // prepare wysiwyg editor
2520 $current = file_prepare_standard_editor($current, 'feedbackauthor', array());
2522 return new workshop_feedbackauthor_form($actionurl,
2523 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2524 'post', '', null, $editable);
2528 * Returns the information about the user's grades as they are stored in the gradebook
2530 * The submission grade is returned for users with the capability mod/workshop:submit and the
2531 * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
2532 * user has the capability to view hidden grades, grades must be visible to be returned. Null
2533 * grades are not returned. If none grade is to be returned, this method returns false.
2535 * @param int $userid the user's id
2536 * @return workshop_final_grades|false
2538 public function get_gradebook_grades($userid) {
2540 require_once($CFG->libdir.'/gradelib.php');
2542 if (empty($userid)) {
2543 throw new coding_exception('User id expected, empty value given.');
2546 // Read data via the Gradebook API
2547 $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
2549 $grades = new workshop_final_grades();
2551 if (has_capability('mod/workshop:submit', $this->context, $userid)) {
2552 if (!empty($gradebook->items[0]->grades)) {
2553 $submissiongrade = reset($gradebook->items[0]->grades);
2554 if (!is_null($submissiongrade->grade)) {
2555 if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2556 $grades->submissiongrade = $submissiongrade;
2562 if (has_capability('mod/workshop:peerassess', $this->context, $userid)) {
2563 if (!empty($gradebook->items[1]->grades)) {
2564 $assessmentgrade = reset($gradebook->items[1]->grades);
2565 if (!is_null($assessmentgrade->grade)) {
2566 if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2567 $grades->assessmentgrade = $assessmentgrade;
2573 if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
2581 * Return the editor options for the submission content field.
2585 public function submission_content_options() {
2587 require_once($CFG->dirroot.'/repository/lib.php');
2590 'trusttext' => true,
2592 'maxfiles' => $this->nattachments,
2593 'maxbytes' => $this->maxbytes,
2594 'context' => $this->context,
2595 'return_types' => FILE_INTERNAL | FILE_EXTERNAL,
2600 * Return the filemanager options for the submission attachments field.
2604 public function submission_attachment_options() {
2606 require_once($CFG->dirroot.'/repository/lib.php');
2610 'maxfiles' => $this->nattachments,
2611 'maxbytes' => $this->maxbytes,
2612 'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
2615 $filetypesutil = new \core_form\filetypes_util();
2616 $options['accepted_types'] = $filetypesutil->normalize_file_types($this->submissionfiletypes);
2622 * Return the editor options for the overall feedback for the author.
2626 public function overall_feedback_content_options() {
2628 require_once($CFG->dirroot.'/repository/lib.php');
2632 'maxbytes' => $this->overallfeedbackmaxbytes,
2633 'maxfiles' => $this->overallfeedbackfiles,
2634 'changeformat' => 1,
2635 'context' => $this->context,
2636 'return_types' => FILE_INTERNAL,
2641 * Return the filemanager options for the overall feedback for the author.
2645 public function overall_feedback_attachment_options() {
2647 require_once($CFG->dirroot.'/repository/lib.php');
2651 'maxbytes' => $this->overallfeedbackmaxbytes,
2652 'maxfiles' => $this->overallfeedbackfiles,
2653 'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
2656 $filetypesutil = new \core_form\filetypes_util();
2657 $options['accepted_types'] = $filetypesutil->normalize_file_types($this->overallfeedbackfiletypes);
2663 * Performs the reset of this workshop instance.
2665 * @param stdClass $data The actual course reset settings.
2666 * @return array List of results, each being array[(string)component, (string)item, (string)error]
2668 public function reset_userdata(stdClass $data) {
2670 $componentstr = get_string('pluginname', 'workshop').': '.format_string($this->name);
2673 if (!empty($data->reset_workshop_assessments) or !empty($data->reset_workshop_submissions)) {
2674 // Reset all data related to assessments, including assessments of
2675 // example submissions.
2676 $result = $this->reset_userdata_assessments($data);
2677 if ($result === true) {
2679 'component' => $componentstr,
2680 'item' => get_string('resetassessments', 'mod_workshop'),
2685 'component' => $componentstr,
2686 'item' => get_string('resetassessments', 'mod_workshop'),
2692 if (!empty($data->reset_workshop_submissions)) {
2693 // Reset all remaining data related to submissions.
2694 $result = $this->reset_userdata_submissions($data);
2695 if ($result === true) {
2697 'component' => $componentstr,
2698 'item' => get_string('resetsubmissions', 'mod_workshop'),
2703 'component' => $componentstr,
2704 'item' => get_string('resetsubmissions', 'mod_workshop'),
2710 if (!empty($data->reset_workshop_phase)) {
2711 // Do not use the {@link workshop::switch_phase()} here, we do not
2712 // want to trigger events.
2713 $this->reset_phase();
2715 'component' => $componentstr,
2716 'item' => get_string('resetsubmissions', 'mod_workshop'),
2725 * Check if the current user can access the other user's group.
2727 * This is typically used for teacher roles that have permissions like
2728 * 'view all submissions'. Even with such a permission granted, we have to
2729 * check the workshop activity group mode.
2731 * If the workshop is not in a group mode, or if it is in the visible group
2732 * mode, this method returns true. This is consistent with how the
2733 * {@link groups_get_activity_allowed_groups()} behaves.
2735 * If the workshop is in a separate group mode, the current user has to
2736 * have the 'access all groups' permission, or share at least one
2737 * accessible group with the other user.
2739 * @param int $otheruserid The ID of the other user, e.g. the author of a submission.
2740 * @return bool False if the current user cannot access the other user's group.
2742 public function check_group_membership($otheruserid) {
2745 if (groups_get_activity_groupmode($this->cm) != SEPARATEGROUPS) {
2746 // The workshop is not in a group mode, or it is in a visible group mode.
2749 } else if (has_capability('moodle/site:accessallgroups', $this->context)) {
2750 // The current user can access all groups.
2754 $thisusersgroups = groups_get_all_groups($this->course->id, $USER->id, $this->cm->groupingid, 'g.id');
2755 $otherusersgroups = groups_get_all_groups($this->course->id, $otheruserid, $this->cm->groupingid, 'g.id');
2756 $commongroups = array_intersect_key($thisusersgroups, $otherusersgroups);
2758 if (empty($commongroups)) {
2759 // The current user has no group common with the other user.
2763 // The current user has a group common with the other user.
2770 * Check whether the given user has assessed all his required examples before submission.
2772 * @param int $userid the user to check
2773 * @return bool false if there are examples missing assessment, true otherwise.
2776 public function check_examples_assessed_before_submission($userid) {
2778 if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_SUBMISSION
2779 and !has_capability('mod/workshop:manageexamples', $this->context)) {
2781 // Check that all required examples have been assessed by the user.
2782 $examples = $this->get_examples_for_reviewer($userid);
2783 foreach ($examples as $exampleid => $example) {
2784 if (is_null($example->assessmentid)) {
2785 $examples[$exampleid]->assessmentid = $this->add_allocation($example, $userid, 0);
2787 if (is_null($example->grade)) {
2796 * Check that all required examples have been assessed by the given user.
2798 * @param stdClass $userid the user (reviewer) to check
2799 * @return mixed bool|state false and notice code if there are examples missing assessment, true otherwise.
2802 public function check_examples_assessed_before_assessment($userid) {
2804 if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_ASSESSMENT
2805 and !has_capability('mod/workshop:manageexamples', $this->context)) {
2807 // The reviewer must have submitted their own submission.
2808 $reviewersubmission = $this->get_submission_by_author($userid);
2809 if (!$reviewersubmission) {
2810 // No money, no love.
2811 return array(false, 'exampleneedsubmission');
2813 $examples = $this->get_examples_for_reviewer($userid);
2814 foreach ($examples as $exampleid => $example) {
2815 if (is_null($example->grade)) {
2816 return array(false, 'exampleneedassessed');
2821 return array(true, null);
2825 * Trigger module viewed event and set the module viewed for completion.
2829 public function set_module_viewed() {
2831 require_once($CFG->libdir . '/completionlib.php');
2834 $completion = new completion_info($this->course);
2835 $completion->set_module_viewed($this->cm);
2837 $eventdata = array();
2838 $eventdata['objectid'] = $this->id;
2839 $eventdata['context'] = $this->context;
2841 // Trigger module viewed event.
2842 $event = \mod_workshop\event\course_module_viewed::create($eventdata);
2843 $event->add_record_snapshot('course', $this->course);
2844 $event->add_record_snapshot('workshop', $this->dbrecord);
2845 $event->add_record_snapshot('course_modules', $this->cm);
2850 * Validates the submission form or WS data.
2852 * @param array $data the data to be validated
2853 * @return array the validation errors (if any)
2856 public function validate_submission_data($data) {
2860 if (empty($data['id']) and empty($data['example'])) {
2861 // Make sure there is no submission saved meanwhile from another browser window.
2862 $sql = "SELECT COUNT(s.id)
2863 FROM {workshop_submissions} s
2864 JOIN {workshop} w ON (s.workshopid = w.id)
2865 JOIN {course_modules} cm ON (w.id = cm.instance)
2866 JOIN {modules} m ON (m.name = 'workshop' AND m.id = cm.module)
2867 WHERE cm.id = ? AND s.authorid = ? AND s.example = 0";
2869 if ($DB->count_records_sql($sql, array($data['cmid'], $USER->id))) {
2870 $errors['title'] = get_string('err_multiplesubmissions', 'mod_workshop');
2874 $getfiles = file_get_drafarea_files($data['attachment_filemanager']);
2875 if (empty($getfiles->list) and html_is_blank($data['content_editor']['text'])) {
2876 $errors['content_editor'] = get_string('submissionrequiredcontent', 'mod_workshop');
2877 $errors['attachment_filemanager'] = get_string('submissionrequiredfile', 'mod_workshop');
2884 * Adds or updates a submission.
2886 * @param stdClass $submission The submissin data (via form or via WS).
2887 * @return the new or updated submission id.
2890 public function edit_submission($submission) {
2893 if ($submission->example == 0) {
2894 // This was used just for validation, it must be set to zero when dealing with normal submissions.
2895 unset($submission->example);
2897 throw new coding_exception('Invalid submission form data value: example');
2900 if (is_null($submission->id)) {
2901 $submission->workshopid = $this->id;
2902 $submission->example = 0;
2903 $submission->authorid = $USER->id;
2904 $submission->timecreated = $timenow;
2905 $submission->feedbackauthorformat = editors_get_preferred_format();
2907 $submission->timemodified = $timenow;
2908 $submission->title = trim($submission->title);
2909 $submission->content = ''; // Updated later.
2910 $submission->contentformat = FORMAT_HTML; // Updated later.
2911 $submission->contenttrust = 0; // Updated later.
2912 $submission->late = 0x0; // Bit mask.
2913 if (!empty($this->submissionend) and ($this->submissionend < time())) {
2914 $submission->late = $submission->late | 0x1;
2916 if ($this->phase == self::PHASE_ASSESSMENT) {
2917 $submission->late = $submission->late | 0x2;
2920 // Event information.
2922 'context' => $this->context,
2923 'courseid' => $this->course->id,
2925 'submissiontitle' => $submission->title
2929 if (is_null($submission->id)) {
2930 $submission->id = $DB->insert_record('workshop_submissions', $submission);
2931 $params['objectid'] = $submission->id;
2932 $event = \mod_workshop\event\submission_created::create($params);
2935 if (empty($submission->id) or empty($submission->id) or ($submission->id != $submission->id)) {
2936 throw new moodle_exception('err_submissionid', 'workshop');
2939 $params['objectid'] = $submission->id;
2941 // Save and relink embedded images and save attachments.
2942 $submission = file_postupdate_standard_editor($submission, 'content', $this->submission_content_options(),
2943 $this->context, 'mod_workshop', 'submission_content', $submission->id);
2945 $submission = file_postupdate_standard_filemanager($submission, 'attachment', $this->submission_attachment_options(),
2946 $this->context, 'mod_workshop', 'submission_attachment', $submission->id);
2948 if (empty($submission->attachment)) {
2949 // Explicit cast to zero integer.
2950 $submission->attachment = 0;
2952 // Store the updated values or re-save the new submission (re-saving needed because URLs are now rewritten).
2953 $DB->update_record('workshop_submissions', $submission);
2954 $event = \mod_workshop\event\submission_updated::create($params);
2955 $event->add_record_snapshot('workshop', $this->dbrecord);
2958 // Send submitted content for plagiarism detection.
2959 $fs = get_file_storage();
2960 $files = $fs->get_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
2962 $params['other']['content'] = $submission->content;
2963 $params['other']['pathnamehashes'] = array_keys($files);
2965 $event = \mod_workshop\event\assessable_uploaded::create($params);
2966 $event->set_legacy_logdata($logdata);
2969 return $submission->id;
2973 * Helper method for validating if the current user can view the given assessment.
2975 * @param stdClass $assessment assessment object
2976 * @param stdClass $submission submission object
2978 * @throws moodle_exception
2981 public function check_view_assessment($assessment, $submission) {
2984 $isauthor = $submission->authorid == $USER->id;
2985 $isreviewer = $assessment->reviewerid == $USER->id;
2986 $canviewallassessments = has_capability('mod/workshop:viewallassessments', $this->context);
2987 $canviewallsubmissions = has_capability('mod/workshop:viewallsubmissions', $this->context);
2989 $canviewallsubmissions = $canviewallsubmissions && $this->check_group_membership($submission->authorid);
2991 if (!$isreviewer and !$isauthor and !($canviewallassessments and $canviewallsubmissions)) {
2992 print_error('nopermissions', 'error', $this->view_url(), 'view this assessment');
2995 if ($isauthor and !$isreviewer and !$canviewallassessments and $this->phase != self::PHASE_CLOSED) {
2996 // Authors can see assessments of their work at the end of workshop only.
2997 print_error('nopermissions', 'error', $this->view_url(), 'view assessment of own work before workshop is closed');
3001 ////////////////////////////////////////////////////////////////////////////////
3002 // Internal methods (implementation details) //
3003 ////////////////////////////////////////////////////////////////////////////////
3006 * Given an array of all assessments of a single submission, calculates the final grade for this submission
3008 * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade
3009 * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored.
3011 * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
3014 protected function aggregate_submission_grades_process(array $assessments) {
3017 $submissionid = null; // the id of the submission being processed
3018 $current = null; // the grade currently saved in database
3019 $finalgrade = null; // the new grade to be calculated
3023 foreach ($assessments as $assessment) {
3024 if (is_null($submissionid)) {
3025 // the id is the same in all records, fetch it during the first loop cycle
3026 $submissionid = $assessment->submissionid;
3028 if (is_null($current)) {
3029 // the currently saved grade is the same in all records, fetch it during the first loop cycle
3030 $current = $assessment->submissiongrade;
3032 if (is_null($assessment->grade)) {
3033 // this was not assessed yet
3036 if ($assessment->weight == 0) {
3037 // this does not influence the calculation
3040 $sumgrades += $assessment->grade * $assessment->weight;
3041 $sumweights += $assessment->weight;
3043 if ($sumweights > 0 and is_null($finalgrade)) {
3044 $finalgrade = grade_floatval($sumgrades / $sumweights);
3046 // check if the new final grade differs from the one stored in the database
3047 if (grade_floats_different($finalgrade, $current)) {
3048 // we need to save new calculation into the database
3049 $record = new stdclass();
3050 $record->id = $submissionid;
3051 $record->grade = $finalgrade;
3052 $record->timegraded = time();
3053 $DB->update_record('workshop_submissions', $record);
3058 * Given an array of all assessments done by a single reviewer, calculates the final grading grade
3060 * This calculates the simple mean of the passed grading grades. If, however, the grading grade
3061 * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored.
3063 * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade)
3064 * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time
3067 protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
3070 $reviewerid = null; // the id of the reviewer being processed
3071 $current = null; // the gradinggrade currently saved in database
3072 $finalgrade = null; // the new grade to be calculated
3073 $agid = null; // aggregation id
3077 if (is_null($timegraded)) {
3078 $timegraded = time();
3081 foreach ($assessments as $assessment) {
3082 if (is_null($reviewerid)) {
3083 // the id is the same in all records, fetch it during the first loop cycle
3084 $reviewerid = $assessment->reviewerid;
3086 if (is_null($agid)) {
3087 // the id is the same in all records, fetch it during the first loop cycle
3088 $agid = $assessment->aggregationid;
3090 if (is_null($current)) {
3091 // the currently saved grade is the same in all records, fetch it during the first loop cycle
3092 $current = $assessment->aggregatedgrade;
3094 if (!is_null($assessment->gradinggradeover)) {
3095 // the grading grade for this assessment is overridden by a teacher
3096 $sumgrades += $assessment->gradinggradeover;
3099 if (!is_null($assessment->gradinggrade)) {
3100 $sumgrades += $assessment->gradinggrade;
3106 $finalgrade = grade_floatval($sumgrades / $count);
3109 // Event information.
3111 'context' => $this->context,
3112 'courseid' => $this->course->id,
3113 'relateduserid' => $reviewerid
3116 // check if the new final grade differs from the one stored in the database
3117 if (grade_floats_different($finalgrade, $current)) {
3118 $params['other'] = array(
3119 'currentgrade' => $current,
3120 'finalgrade' => $finalgrade
3123 // we need to save new calculation into the database
3124 if (is_null($agid)) {
3125 // no aggregation record yet
3126 $record = new stdclass();
3127 $record->workshopid = $this->id;
3128 $record->userid = $reviewerid;
3129 $record->gradinggrade = $finalgrade;
3130 $record->timegraded = $timegraded;
3131 $record->id = $DB->insert_record('workshop_aggregations', $record);
3132 $params['objectid'] = $record->id;
3133 $event = \mod_workshop\event\assessment_evaluated::create($params);
3136 $record = new stdclass();
3137 $record->id = $agid;
3138 $record->gradinggrade = $finalgrade;
3139 $record->timegraded = $timegraded;
3140 $DB->update_record('workshop_aggregations', $record);
3141 $params['objectid'] = $agid;
3142 $event = \mod_workshop\event\assessment_reevaluated::create($params);
3149 * Returns SQL to fetch all enrolled users with the given capability in the current workshop
3151 * The returned array consists of string $sql and the $params array. Note that the $sql can be
3152 * empty if a grouping is selected and it has no groups.
3154 * The list is automatically restricted according to any availability restrictions
3155 * that apply to user lists (e.g. group, grouping restrictions).
3157 * @param string $capability the name of the capability
3158 * @param bool $musthavesubmission ff true, return only users who have already submitted
3159 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3160 * @return array of (string)sql, (array)params
3162 protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) {
3164 /** @var int static counter used to generate unique parameter holders */
3168 // If the caller requests all groups and we are using a selected grouping,
3169 // recursively call this function for each group in the grouping (this is
3170 // needed because get_enrolled_sql only supports a single group).
3171 if (empty($groupid) and $this->cm->groupingid) {
3172 $groupingid = $this->cm->groupingid;
3173 $groupinggroupids = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
3176 foreach ($groupinggroupids as $groupinggroupid) {
3177 if ($groupinggroupid > 0) { // just in case in order not to fall into the endless loop
3178 list($gsql, $gparams) = $this->get_users_with_capability_sql($capability, $musthavesubmission, $groupinggroupid);
3180 $params = array_merge($params, $gparams);
3183 $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql);
3184 return array($sql, $params);
3187 list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true);
3189 $userfields = user_picture::fields('u');
3191 $sql = "SELECT $userfields
3193 JOIN ($esql) je ON (je.id = u.id AND u.deleted = 0) ";
3195 if ($musthavesubmission) {
3196 $sql .= " JOIN {workshop_submissions} ws ON (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid{$inc}) ";
3197 $params['workshopid'.$inc] = $this->id;
3200 // If the activity is restricted so that only certain users should appear
3201 // in user lists, integrate this into the same SQL.
3202 $info = new \core_availability\info_module($this->cm);
3203 list ($listsql, $listparams) = $info->get_user_list_sql(false);
3205 $sql .= " JOIN ($listsql) restricted ON restricted.id = u.id ";
3206 $params = array_merge($params, $listparams);
3209 return array($sql, $params);
3213 * Returns SQL statement that can be used to fetch all actively enrolled participants in the workshop
3215 * @param bool $musthavesubmission if true, return only users who have already submitted
3216 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3217 * @return array of (string)sql, (array)params
3219 protected function get_participants_sql($musthavesubmission=false, $groupid=0) {
3221 list($sql1, $params1) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
3222 list($sql2, $params2) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
3224 if (empty($sql1) or empty($sql2)) {
3225 if (empty($sql1) and empty($sql2)) {
3226 return array('', array());
3227 } else if (empty($sql1)) {
3235 $sql = $sql1.PHP_EOL." UNION ".PHP_EOL.$sql2;
3236 $params = array_merge($params1, $params2);
3239 return array($sql, $params);
3243 * @return array of available workshop phases
3245 protected function available_phases_list() {
3247 self::PHASE_SETUP => true,
3248 self::PHASE_SUBMISSION => true,
3249 self::PHASE_ASSESSMENT => true,
3250 self::PHASE_EVALUATION => true,
3251 self::PHASE_CLOSED => true,
3256 * Converts absolute URL to relative URL needed by {@see add_to_log()}
3258 * @param moodle_url $url absolute URL
3261 protected function log_convert_url(moodle_url $fullurl) {
3264 if (!isset($baseurl)) {
3265 $baseurl = new moodle_url('/mod/workshop/');
3266 $baseurl = $baseurl->out();
3269 return substr($fullurl->out(), strlen($baseurl));
3273 * Removes all user data related to assessments (including allocations).
3275 * This includes assessments of example submissions as long as they are not
3276 * referential assessments.
3278 * @param stdClass $data The actual course reset settings.
3279 * @return bool|string True on success, error message otherwise.
3281 protected function reset_userdata_assessments(stdClass $data) {
3285 FROM {workshop_assessments} a
3286 JOIN {workshop_submissions} s ON (a.submissionid = s.id)
3287 WHERE s.workshopid = :workshopid
3288 AND (s.example = 0 OR (s.example = 1 AND a.weight = 0))";
3290 $assessments = $DB->get_records_sql($sql, array('workshopid' => $this->id));
3291 $this->delete_assessment(array_keys($assessments));
3293 $DB->delete_records('workshop_aggregations', array('workshopid' => $this->id));
3299 * Removes all user data related to participants' submissions.
3301 * @param stdClass $data The actual course reset settings.
3302 * @return bool|string True on success, error message otherwise.
3304 protected function reset_userdata_submissions(stdClass $data) {
3307 $submissions = $this->get_submissions();
3308 foreach ($submissions as $submission) {
3309 $this->delete_submission($submission);
3316 * Hard set the workshop phase to the setup one.
3318 protected function reset_phase() {
3321 $DB->set_field('workshop', 'phase', self::PHASE_SETUP, array('id' => $this->id));
3322 $this->phase = self::PHASE_SETUP;
3326 ////////////////////////////////////////////////////////////////////////////////
3327 // Renderable components
3328 ////////////////////////////////////////////////////////////////////////////////
3331 * Represents the user planner tool
3333 * Planner contains list of phases. Each phase contains list of tasks. Task is a simple object with
3334 * title, link and completed (true/false/null logic).
3336 class workshop_user_plan implements renderable {
3338 /** @var int id of the user this plan is for */
3340 /** @var workshop */
3342 /** @var array of (stdclass)tasks */
3343 public $phases = array();
3344 /** @var null|array of example submissions to be assessed by the planner owner */
3345 protected $examples = null;
3348 * Prepare an individual workshop plan for the given user.
3350 * @param workshop $workshop instance
3351 * @param int $userid whom the plan is prepared for
3353 public function __construct(workshop $workshop, $userid) {
3356 $this->workshop = $workshop;
3357 $this->userid = $userid;
3359 //---------------------------------------------------------
3360 // * SETUP | submission | assessment | evaluation | closed
3361 //---------------------------------------------------------
3362 $phase = new stdclass();
3363 $phase->title = get_string('phasesetup', 'workshop');
3364 $phase->tasks = array();
3365 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3366 $task = new stdclass();
3367 $task->title = get_string('taskintro', 'workshop');
3368 $task->link = $workshop->updatemod_url();
3369 $task->completed = !(trim($workshop->intro) == '');
3370 $phase->tasks['intro'] = $task;
3372 if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3373 $task = new stdclass();
3374 $task->title = get_string('taskinstructauthors', 'workshop');
3375 $task->link = $workshop->updatemod_url();
3376 $task->completed = !(trim($workshop->instructauthors) == '');
3377 $phase->tasks['instructauthors'] = $task;