383ce6104ed3fe2965641fd3e2cfdc9672c40ca6
[moodle.git] / mod / workshop / locallib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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.
13 //
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/>.
17 /**
18  * Library of internal classes and functions for module workshop
19  *
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.
24  *
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
28  */
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');
36 /**
37  * Full-featured workshop API
38  *
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.
42  */
43 class workshop {
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 */
61     public $dbrecord;
63     /** @var cm_info course module record */
64     public $cm;
66     /** @var stdclass course record */
67     public $course;
69     /** @var stdclass context object */
70     public $context;
72     /** @var int workshop instance identifier */
73     public $id;
75     /** @var string workshop activity name */
76     public $name;
78     /** @var string introduction or description of the activity */
79     public $intro;
81     /** @var int format of the {@link $intro} */
82     public $introformat;
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 */
97     public $timemodified;
99     /** @var int current phase of workshop, for example {@link workshop::PHASE_SETUP} */
100     public $phase;
102     /** @var bool optional feature: students practise evaluating on example submissions from teacher */
103     public $useexamples;
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 */
112     public $grade;
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' */
118     public $strategy;
120     /** @var string the name of the evaluation plugin to use for grading grades calculation */
121     public $evaluation;
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 */
136     public $maxbytes;
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 */
157     public $conclusion;
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;
174     /**
175      * @var workshop_strategy grading strategy instance
176      * Do not use directly, get the instance using {@link workshop::grading_strategy_instance()}
177      */
178     protected $strategyinstance = null;
180     /**
181      * @var workshop_evaluation grading evaluation instance
182      * Do not use directly, get the instance using {@link workshop::grading_evaluation_instance()}
183      */
184     protected $evaluationinstance = null;
186     /**
187      * Initializes the workshop API instance using the data from DB
188      *
189      * Makes deep copy of all passed records properties.
190      *
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.
194      *
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
199      */
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;
205             }
206         }
207         if (is_null($cm) || is_null($course)) {
208             throw new coding_exception('Must specify $cm and $course');
209         }
210         $this->course = $course;
211         if ($cm instanceof cm_info) {
212             $this->cm = $cm;
213         } else {
214             $modinfo = get_fast_modinfo($course);
215             $this->cm = $modinfo->get_cm($cm->id);
216         }
217         if (is_null($context)) {
218             $this->context = context_module::instance($this->cm->id);
219         } else {
220             $this->context = $context;
221         }
222     }
224     ////////////////////////////////////////////////////////////////////////////////
225     // Static methods                                                             //
226     ////////////////////////////////////////////////////////////////////////////////
228     /**
229      * Return list of available allocation methods
230      *
231      * @return array Array ['string' => 'string'] of localized allocation method names
232      */
233     public static function installed_allocators() {
234         $installed = core_component::get_plugin_list('workshopallocation');
235         $forms = array();
236         foreach ($installed as $allocation => $allocationpath) {
237             if (file_exists($allocationpath . '/lib.php')) {
238                 $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation);
239             }
240         }
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);
246         }
247         return $forms;
248     }
250     /**
251      * Returns an array of options for the editors that are used for submitting and assessing instructions
252      *
253      * @param stdClass $context
254      * @uses EDITOR_UNLIMITED_FILES hard-coded value for the 'maxfiles' option
255      * @return array
256      */
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);
260     }
262     /**
263      * Given the percent and the total, returns the number
264      *
265      * @param float $percent from 0 to 100
266      * @param float $total   the 100% value
267      * @return float
268      */
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');
272         }
274         return $total * $percent / 100;
275     }
277     /**
278      * Returns an array of numeric values that can be used as maximum grades
279      *
280      * @return array Array of integers
281      */
282     public static function available_maxgrades_list() {
283         $grades = array();
284         for ($i=100; $i>=0; $i--) {
285             $grades[$i] = $i;
286         }
287         return $grades;
288     }
290     /**
291      * Returns the localized list of supported examples modes
292      *
293      * @return array
294      */
295     public static function available_example_modes_list() {
296         $options = array();
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');
300         return $options;
301     }
303     /**
304      * Returns the list of available grading strategy methods
305      *
306      * @return array ['string' => 'string']
307      */
308     public static function available_strategies_list() {
309         $installed = core_component::get_plugin_list('workshopform');
310         $forms = array();
311         foreach ($installed as $strategy => $strategypath) {
312             if (file_exists($strategypath . '/lib.php')) {
313                 $forms[$strategy] = get_string('pluginname', 'workshopform_' . $strategy);
314             }
315         }
316         return $forms;
317     }
319     /**
320      * Returns the list of available grading evaluation methods
321      *
322      * @return array of (string)name => (string)localized title
323      */
324     public static function available_evaluators_list() {
325         $evals = array();
326         foreach (core_component::get_plugin_list_with_file('workshopeval', 'lib.php', false) as $eval => $evalpath) {
327             $evals[$eval] = get_string('pluginname', 'workshopeval_' . $eval);
328         }
329         return $evals;
330     }
332     /**
333      * Return an array of possible values of assessment dimension weight
334      *
335      * @return array of integers 0, 1, 2, ..., 16
336      */
337     public static function available_dimension_weights_list() {
338         $weights = array();
339         for ($i=16; $i>=0; $i--) {
340             $weights[$i] = $i;
341         }
342         return $weights;
343     }
345     /**
346      * Return an array of possible values of assessment weight
347      *
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...
353      *
354      * @return array of integers 0, 1, 2, ..., 16
355      */
356     public static function available_assessment_weights_list() {
357         $weights = array();
358         for ($i=16; $i>=0; $i--) {
359             $weights[$i] = $i;
360         }
361         return $weights;
362     }
364     /**
365      * Helper function returning the greatest common divisor
366      *
367      * @param int $a
368      * @param int $b
369      * @return int
370      */
371     public static function gcd($a, $b) {
372         return ($b == 0) ? ($a):(self::gcd($b, $a % $b));
373     }
375     /**
376      * Helper function returning the least common multiple
377      *
378      * @param int $a
379      * @param int $b
380      * @return int
381      */
382     public static function lcm($a, $b) {
383         return ($a / self::gcd($a,$b)) * $b;
384     }
386     /**
387      * Returns an object suitable for strings containing dates/times
388      *
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.
393      *
394      * @param int $timestamp the timestamp in UTC
395      * @return stdclass
396      */
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');
401         $a = new stdclass();
402         foreach ($formats as $format) {
403             $a->{$format} = userdate($timestamp, get_string('strftime'.$format, 'langconfig'));
404         }
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);
420         }
421         return $a;
422     }
424     /**
425      * Converts the argument into an array (list) of file extensions.
426      *
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.
430      *
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
434      */
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 === '') {
441             return array();
442         }
444         if (!is_array($extensions)) {
445             $extensions = preg_split('/[\s,;:"\']+/', $extensions, null, PREG_SPLIT_NO_EMPTY);
446         }
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;
454         }
456         foreach ($extensions as $i => $extension) {
457             if (strpos($extension, '*') !== false or strpos($extension, '?') !== false) {
458                 unset($extensions[$i]);
459             }
460         }
462         $extensions = array_filter($extensions, 'strlen');
463         $extensions = array_keys(array_flip($extensions));
465         foreach ($extensions as $i => $extension) {
466             $extensions[$i] = '.'.$extension;
467         }
469         return $extensions;
470     }
472     /**
473      * Cleans the user provided list of file extensions.
474      *
475      * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
476      * @param string $extensions
477      * @return string
478      */
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, '.');
488         }
490         return implode(', ', $extensions);
491     }
493     /**
494      * Check given file types and return invalid/unknown ones.
495      *
496      * Empty whitelist is interpretted as "any extension is valid".
497      *
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
502      */
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)) {
512             return array();
513         }
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)));
517     }
519     /**
520      * Is the file have allowed to be uploaded to the workshop?
521      *
522      * Empty whitelist is interpretted as "any file type is allowed" rather
523      * than "no file can be uploaded".
524      *
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
528      * @return false
529      */
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)) {
538             return true;
539         }
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.
546                 return true;
547             }
548         }
550         return false;
551     }
553     ////////////////////////////////////////////////////////////////////////////////
554     // Workshop API                                                               //
555     ////////////////////////////////////////////////////////////////////////////////
557     /**
558      * Fetches all enrolled users with the capability mod/workshop:submit in the current workshop
559      *
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.
562      *
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
568      */
569     public function get_potential_authors($musthavesubmission=true, $groupid=0, $limitfrom=0, $limitnum=0) {
570         global $DB;
572         list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
574         if (empty($sql)) {
575             return array();
576         }
578         list($sort, $sortparams) = users_order_by_sql('tmp');
579         $sql = "SELECT *
580                   FROM ($sql) tmp
581               ORDER BY $sort";
583         return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
584     }
586     /**
587      * Returns the total number of users that would be fetched by {@link self::get_potential_authors()}
588      *
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
591      * @return int
592      */
593     public function count_potential_authors($musthavesubmission=true, $groupid=0) {
594         global $DB;
596         list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
598         if (empty($sql)) {
599             return 0;
600         }
602         $sql = "SELECT COUNT(*)
603                   FROM ($sql) tmp";
605         return $DB->count_records_sql($sql, $params);
606     }
608     /**
609      * Fetches all enrolled users with the capability mod/workshop:peerassess in the current workshop
610      *
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.
613      *
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
619      */
620     public function get_potential_reviewers($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
621         global $DB;
623         list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
625         if (empty($sql)) {
626             return array();
627         }
629         list($sort, $sortparams) = users_order_by_sql('tmp');
630         $sql = "SELECT *
631                   FROM ($sql) tmp
632               ORDER BY $sort";
634         return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
635     }
637     /**
638      * Returns the total number of users that would be fetched by {@link self::get_potential_reviewers()}
639      *
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
642      * @return int
643      */
644     public function count_potential_reviewers($musthavesubmission=false, $groupid=0) {
645         global $DB;
647         list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
649         if (empty($sql)) {
650             return 0;
651         }
653         $sql = "SELECT COUNT(*)
654                   FROM ($sql) tmp";
656         return $DB->count_records_sql($sql, $params);
657     }
659     /**
660      * Fetches all enrolled users that are authors or reviewers (or both) in the current workshop
661      *
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.
664      *
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
672      */
673     public function get_participants($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
674         global $DB;
676         list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
678         if (empty($sql)) {
679             return array();
680         }
682         list($sort, $sortparams) = users_order_by_sql('tmp');
683         $sql = "SELECT *
684                   FROM ($sql) tmp
685               ORDER BY $sort";
687         return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
688     }
690     /**
691      * Returns the total number of records that would be returned by {@link self::get_participants()}
692      *
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
695      * @return int
696      */
697     public function count_participants($musthavesubmission=false, $groupid=0) {
698         global $DB;
700         list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
702         if (empty($sql)) {
703             return 0;
704         }
706         $sql = "SELECT COUNT(*)
707                   FROM ($sql) tmp";
709         return $DB->count_records_sql($sql, $params);
710     }
712     /**
713      * Checks if the given user is an actively enrolled participant in the workshop
714      *
715      * @param int $userid, defaults to the current $USER
716      * @return boolean
717      */
718     public function is_participant($userid=null) {
719         global $USER, $DB;
721         if (is_null($userid)) {
722             $userid = $USER->id;
723         }
725         list($sql, $params) = $this->get_participants_sql();
727         if (empty($sql)) {
728             return false;
729         }
731         $sql = "SELECT COUNT(*)
732                   FROM {user} uxx
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)) {
738             return true;
739         }
741         return false;
742     }
744     /**
745      * Groups the given users by the group membership
746      *
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.
750      *
751      * @param array $users array[userid] => stdclass{->id ->lastname ->firstname}
752      * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname}
753      */
754     public function get_grouped($users) {
755         global $DB;
756         global $CFG;
758         $grouped = array();  // grouped users to be returned
759         if (empty($users)) {
760             return $grouped;
761         }
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
765             // this grouping.
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();
770         } else {
771             $groupingid = 0;
772             // there is no need to be member of a group so $grouped[0] will contain
773             // all users
774             $grouped[0] = $users;
775         }
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();
781             }
782             $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid];
783             $grouped[0][$gmembership->userid] = $users[$gmembership->userid];
784         }
785         return $grouped;
786     }
788     /**
789      * Returns the list of all allocations (i.e. assigned assessments) in the workshop
790      *
791      * Assessments of example submissions are ignored
792      *
793      * @return array
794      */
795     public function get_allocations() {
796         global $DB;
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);
805     }
807     /**
808      * Returns the total number of records that would be returned by {@link self::get_submissions()}
809      *
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
813      */
814     public function count_submissions($authorid='all', $groupid=0) {
815         global $DB;
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)";
821         if ($groupid) {
822             $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
823             $params['groupid'] = $groupid;
824         }
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);
833         } else {
834             // $authorid is empty
835             return 0;
836         }
838         return $DB->count_records_sql($sql, $params);
839     }
842     /**
843      * Returns submissions from this workshop
844      *
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.
847      *
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
854      */
855     public function get_submissions($authorid='all', $groupid=0, $limitfrom=0, $limitnum=0) {
856         global $DB;
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)";
866         if ($groupid) {
867             $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
868             $params['groupid'] = $groupid;
869         }
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);
879         } else {
880             // $authorid is empty
881             return array();
882         }
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);
887     }
889     /**
890      * Returns submissions from this workshop that are viewable by the current user (except example submissions).
891      *
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
897      * @since  Moodle 3.4
898      */
899     public function get_visible_submissions($authorid = 0, $groupid = 0, $limitfrom = 0, $limitnum = 0) {
900         global $DB, $USER;
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);
911         }
913         if ($groupid) {
914             $from .= " JOIN {groups_members} gm ON (gm.userid = s.authorid AND gm.groupid = :groupid)";
915             $params['groupid'] = $groupid;
916         }
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";
925             } else {
926                 $published = '';
927             }
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;
933         }
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);
940         }
942         $order = " ORDER BY s.timecreated";
944         $totalcount = $DB->count_records_sql($selectcount.$from.$where, $params);
945         if ($totalcount) {
946             $submissions = $DB->get_records_sql($select.$from.$where.$order, $params, $limitfrom, $limitnum);
947         }
948         return array($submissions, $totalcount);
949     }
952     /**
953      * Returns a submission record with the author's data
954      *
955      * @param int $id submission id
956      * @return stdclass
957      */
958     public function get_submission_by_id($id) {
959         global $DB;
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);
972     }
974     /**
975      * Returns a submission submitted by the given author
976      *
977      * @param int $id author id
978      * @return stdclass|false
979      */
980     public function get_submission_by_author($authorid) {
981         global $DB;
983         if (empty($authorid)) {
984             return false;
985         }
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);
995     }
997     /**
998      * Returns published submissions with their authors data
999      *
1000      * @return array of stdclass
1001      */
1002     public function get_published_submissions($orderby='finalgrade DESC') {
1003         global $DB;
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,
1008                        $authorfields
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
1012               ORDER BY $orderby";
1013         $params = array('workshopid' => $this->id);
1014         return $DB->get_records_sql($sql, $params);
1015     }
1017     /**
1018      * Returns full record of the given example submission
1019      *
1020      * @param int $id example submission od
1021      * @return object
1022      */
1023     public function get_example_by_id($id) {
1024         global $DB;
1025         return $DB->get_record('workshop_submissions',
1026                 array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST);
1027     }
1029     /**
1030      * Returns the list of example submissions in this workshop with reference assessments attached
1031      *
1032      * @return array of objects or an empty array
1033      * @see workshop::prepare_example_summary()
1034      */
1035     public function get_examples_for_manager() {
1036         global $DB;
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
1043               ORDER BY s.title';
1044         return $DB->get_records_sql($sql, array('workshopid' => $this->id));
1045     }
1047     /**
1048      * Returns the list of all example submissions in this workshop with the information of assessments done by the given user
1049      *
1050      * @param int $reviewerid user id
1051      * @return array of objects, indexed by example submission id
1052      * @see workshop::prepare_example_summary()
1053      */
1054     public function get_examples_for_reviewer($reviewerid) {
1055         global $DB;
1057         if (empty($reviewerid)) {
1058             return false;
1059         }
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
1065               ORDER BY s.title';
1066         return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid));
1067     }
1069     /**
1070      * Prepares renderable submission component
1071      *
1072      * @param stdClass $record required by {@see workshop_submission}
1073      * @param bool $showauthor show the author-related information
1074      * @return workshop_submission
1075      */
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);
1081         return $submission;
1082     }
1084     /**
1085      * Prepares renderable submission summary component
1086      *
1087      * @param stdClass $record required by {@see workshop_submission_summary}
1088      * @param bool $showauthor show the author-related information
1089      * @return workshop_submission_summary
1090      */
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);
1096         return $summary;
1097     }
1099     /**
1100      * Prepares renderable example submission component
1101      *
1102      * @param stdClass $record required by {@see workshop_example_submission}
1103      * @return workshop_example_submission
1104      */
1105     public function prepare_example_submission(stdClass $record) {
1107         $example = new workshop_example_submission($this, $record);
1109         return $example;
1110     }
1112     /**
1113      * Prepares renderable example submission summary component
1114      *
1115      * If the example is editable, the caller must set the 'editable' flag explicitly.
1116      *
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
1119      */
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');
1127         } else {
1128             $summary->status = 'graded';
1129             $summary->assesslabel = get_string('reassess', 'workshop');
1130         }
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()));
1140         return $summary;
1141     }
1143     /**
1144      * Prepares renderable assessment component
1145      *
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
1151      *
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
1156      */
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);
1165         }
1167         if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1168             $assessment->form = $form;
1169         }
1171         if (empty($options['showweight'])) {
1172             $assessment->weight = null;
1173         }
1175         if (!is_null($record->grade)) {
1176             $assessment->realgrade = $this->real_grade($record->grade);
1177         }
1179         return $assessment;
1180     }
1182     /**
1183      * Prepares renderable example submission's assessment component
1184      *
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
1189      *
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
1194      */
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);
1203         }
1205         if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1206             $assessment->form = $form;
1207         }
1209         if (!is_null($record->grade)) {
1210             $assessment->realgrade = $this->real_grade($record->grade);
1211         }
1213         $assessment->weight = null;
1215         return $assessment;
1216     }
1218     /**
1219      * Prepares renderable example submission's reference assessment component
1220      *
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
1225      *
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
1230      */
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);
1238         }
1240         if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1241             $assessment->form = $form;
1242         }
1244         if (!is_null($record->grade)) {
1245             $assessment->realgrade = $this->real_grade($record->grade);
1246         }
1248         $assessment->weight = null;
1250         return $assessment;
1251     }
1253     /**
1254      * Removes the submission and all relevant data
1255      *
1256      * @param stdClass $submission record to delete
1257      * @return void
1258      */
1259     public function delete_submission(stdclass $submission) {
1260         global $DB;
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.
1272         $params = array(
1273             'context' => $this->context,
1274             'courseid' => $this->course->id,
1275             'relateduserid' => $submission->authorid,
1276             'other' => array(
1277                 'submissiontitle' => $submission->title
1278             )
1279         );
1280         $params['objectid'] = $submission->id;
1281         $event = \mod_workshop\event\submission_deleted::create($params);
1282         $event->add_record_snapshot('workshop', $this->dbrecord);
1283         $event->trigger();
1284     }
1286     /**
1287      * Returns the list of all assessments in the workshop with some data added
1288      *
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
1291      * lack issues.
1292      *
1293      * @return array [assessmentid] => assessment stdclass
1294      */
1295     public function get_all_assessments() {
1296         global $DB;
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,
1305                        s.title
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
1312               ORDER BY $sort";
1313         $params['workshopid'] = $this->id;
1315         return $DB->get_records_sql($sql, $params);
1316     }
1318     /**
1319      * Get the complete information about the given assessment
1320      *
1321      * @param int $id Assessment ID
1322      * @return stdclass
1323      */
1324     public function get_assessment_by_id($id) {
1325         global $DB;
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);
1340     }
1342     /**
1343      * Get the complete information about the user's assessment of the given submission
1344      *
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
1348      */
1349     public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
1350         global $DB;
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);
1365     }
1367     /**
1368      * Get the complete information about all assessments of the given submission
1369      *
1370      * @param int $submissionid
1371      * @return array
1372      */
1373     public function get_assessments_of_submission($submissionid) {
1374         global $DB;
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
1385               ORDER BY $sort";
1386         $params['submissionid'] = $submissionid;
1387         $params['workshopid']   = $this->id;
1389         return $DB->get_records_sql($sql, $params);
1390     }
1392     /**
1393      * Get the complete information about all assessments allocated to the given reviewer
1394      *
1395      * @param int $reviewerid
1396      * @return array
1397      */
1398     public function get_assessments_by_reviewer($reviewerid) {
1399         global $DB;
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);
1416     }
1418     /**
1419      * Get allocated assessments not graded yet by the given reviewer
1420      *
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
1424      * @return array
1425      */
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]);
1433                 continue;
1434             }
1435             if (!empty($exclude)) {
1436                 if (is_array($exclude) and in_array($id, $exclude)) {
1437                     unset($assessments[$id]);
1438                     continue;
1439                 } else if ($id == $exclude) {
1440                     unset($assessments[$id]);
1441                     continue;
1442                 }
1443             }
1444         }
1446         return $assessments;
1447     }
1449     /**
1450      * Allocate a submission to a user for review
1451      *
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
1457      */
1458     public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
1459         global $DB;
1461         if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
1462             return self::ALLOCATION_EXISTS;
1463         }
1465         $weight = (int)$weight;
1466         if ($weight < 0) {
1467             $weight = 0;
1468         }
1469         if ($weight > 16) {
1470             $weight = 16;
1471         }
1473         $now = time();
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);
1483     }
1485     /**
1486      * Delete assessment record or records.
1487      *
1488      * Removes associated records from the workshop_grades table, too.
1489      *
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.
1492      * @return bool true
1493      */
1494     public function delete_assessment($id) {
1495         global $DB;
1497         if (empty($id)) {
1498             return true;
1499         }
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);
1508             }
1509             $DB->delete_records_list('workshop_assessments', 'id', $id);
1511         } else {
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));
1516         }
1518         return true;
1519     }
1521     /**
1522      * Returns instance of grading strategy class
1523      *
1524      * @return stdclass Instance of a grading strategy
1525      */
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);
1533             } else {
1534                 throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
1535             }
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');
1540             }
1541         }
1542         return $this->strategyinstance;
1543     }
1545     /**
1546      * Sets the current evaluation method to the given plugin.
1547      *
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
1551      */
1552     public function set_grading_evaluation_method($method) {
1553         global $DB;
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));
1561             return true;
1562         }
1564         throw new coding_exception('Attempt to set a non-existing evaluation method.');
1565     }
1567     /**
1568      * Returns instance of grading evaluation class
1569      *
1570      * @return stdclass Instance of a grading evaluation
1571      */
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';
1578             }
1579             $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
1580             if (is_readable($evaluationlib)) {
1581                 require_once($evaluationlib);
1582             } else {
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);
1588                 } else {
1589                     // Fall back in case the subplugin is not available any more.
1590                     throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
1591                 }
1592             }
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');
1597             }
1598         }
1599         return $this->evaluationinstance;
1600     }
1602     /**
1603      * Returns instance of submissions allocator
1604      *
1605      * @param string $method The name of the allocation method, must be PARAM_ALPHA
1606      * @return stdclass Instance of submissions allocator
1607      */
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);
1614         } else {
1615             throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
1616         }
1617         $classname = 'workshop_' . $method . '_allocator';
1618         return new $classname($this);
1619     }
1621     /**
1622      * @return moodle_url of this workshop's view page
1623      */
1624     public function view_url() {
1625         global $CFG;
1626         return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
1627     }
1629     /**
1630      * @return moodle_url of the page for editing this workshop's grading form
1631      */
1632     public function editform_url() {
1633         global $CFG;
1634         return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
1635     }
1637     /**
1638      * @return moodle_url of the page for previewing this workshop's grading form
1639      */
1640     public function previewform_url() {
1641         global $CFG;
1642         return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
1643     }
1645     /**
1646      * @param int $assessmentid The ID of assessment record
1647      * @return moodle_url of the assessment page
1648      */
1649     public function assess_url($assessmentid) {
1650         global $CFG;
1651         $assessmentid = clean_param($assessmentid, PARAM_INT);
1652         return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
1653     }
1655     /**
1656      * @param int $assessmentid The ID of assessment record
1657      * @return moodle_url of the example assessment page
1658      */
1659     public function exassess_url($assessmentid) {
1660         global $CFG;
1661         $assessmentid = clean_param($assessmentid, PARAM_INT);
1662         return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
1663     }
1665     /**
1666      * @return moodle_url of the page to view a submission, defaults to the own one
1667      */
1668     public function submission_url($id=null) {
1669         global $CFG;
1670         return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
1671     }
1673     /**
1674      * @param int $id example submission id
1675      * @return moodle_url of the page to view an example submission
1676      */
1677     public function exsubmission_url($id) {
1678         global $CFG;
1679         return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
1680     }
1682     /**
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
1686      */
1687     public function compare_url($sid, array $aids) {
1688         global $CFG;
1690         $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
1691         $i = 0;
1692         foreach ($aids as $aid) {
1693             $url->param("aid{$i}", $aid);
1694             $i++;
1695         }
1696         return $url;
1697     }
1699     /**
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
1703      */
1704     public function excompare_url($sid, $aid) {
1705         global $CFG;
1706         return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
1707     }
1709     /**
1710      * @return moodle_url of the mod_edit form
1711      */
1712     public function updatemod_url() {
1713         global $CFG;
1714         return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
1715     }
1717     /**
1718      * @param string $method allocation method
1719      * @return moodle_url to the allocation page
1720      */
1721     public function allocation_url($method=null) {
1722         global $CFG;
1723         $params = array('cmid' => $this->cm->id);
1724         if (!empty($method)) {
1725             $params['method'] = $method;
1726         }
1727         return new moodle_url('/mod/workshop/allocation.php', $params);
1728     }
1730     /**
1731      * @param int $phasecode The internal phase code
1732      * @return moodle_url of the script to change the current phase to $phasecode
1733      */
1734     public function switchphase_url($phasecode) {
1735         global $CFG;
1736         $phasecode = clean_param($phasecode, PARAM_INT);
1737         return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
1738     }
1740     /**
1741      * @return moodle_url to the aggregation page
1742      */
1743     public function aggregate_url() {
1744         global $CFG;
1745         return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
1746     }
1748     /**
1749      * @return moodle_url of this workshop's toolbox page
1750      */
1751     public function toolbox_url($tool) {
1752         global $CFG;
1753         return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
1754     }
1756     /**
1757      * Workshop wrapper around {@see add_to_log()}
1758      * @deprecated since 2.7 Please use the provided event classes for logging actions.
1759      *
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
1765      */
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();
1771         }
1773         if (is_null($info)) {
1774             $info = $this->id;
1775         }
1777         $logurl = $this->log_convert_url($url);
1778         $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
1779         if ($return) {
1780             return $args;
1781         }
1782         call_user_func_array('add_to_log', $args);
1783     }
1785     /**
1786      * Is the given user allowed to create their submission?
1787      *
1788      * @param int $userid
1789      * @return bool
1790      */
1791     public function creating_submission_allowed($userid) {
1793         $now = time();
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
1799                 return false;
1800             }
1801             if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1802                 // late submissions are not allowed before the submission start
1803                 return false;
1804             }
1805             return true;
1807         } else {
1808             if ($this->phase != self::PHASE_SUBMISSION) {
1809                 // submissions are allowed during the submission phase only
1810                 return false;
1811             }
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
1814                 return false;
1815             }
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
1818                 return false;
1819             }
1820             return true;
1821         }
1822     }
1824     /**
1825      * Is the given user allowed to modify their existing submission?
1826      *
1827      * @param int $userid
1828      * @return bool
1829      */
1830     public function modifying_submission_allowed($userid) {
1832         $now = time();
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
1837             return false;
1838         }
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
1841             return false;
1842         }
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
1845             return false;
1846         }
1847         return true;
1848     }
1850     /**
1851      * Is the given reviewer allowed to create/edit their assessments?
1852      *
1853      * @param int $userid
1854      * @return bool
1855      */
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)) {
1862                 return false;
1863             }
1864         }
1866         $now = time();
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
1871             return false;
1872         }
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
1875             return false;
1876         }
1877         // here we go, assessing is allowed
1878         return true;
1879     }
1881     /**
1882      * Are reviewers allowed to create/edit their assessments of the example submissions?
1883      *
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.
1887      *
1888      * @return null|bool
1889      */
1890     public function assessing_examples_allowed() {
1891         if (empty($this->useexamples)) {
1892             return null;
1893         }
1894         if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
1895             return true;
1896         }
1897         if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
1898             return true;
1899         }
1900         if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
1901             return true;
1902         }
1903         return false;
1904     }
1906     /**
1907      * Are the peer-reviews available to the authors?
1908      *
1909      * @return bool
1910      */
1911     public function assessments_available() {
1912         return $this->phase == self::PHASE_CLOSED;
1913     }
1915     /**
1916      * Switch to a new workshop phase
1917      *
1918      * Modifies the underlying database record. You should terminate the script shortly after calling this.
1919      *
1920      * @param int $newphase new phase code
1921      * @return bool true if success, false otherwise
1922      */
1923     public function switch_phase($newphase) {
1924         global $DB;
1926         $known = $this->available_phases_list();
1927         if (!isset($known[$newphase])) {
1928             return false;
1929         }
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;
1936             }
1937             $workshop->course     = $this->course->id;
1938             $workshop->cmidnumber = $this->cm->id;
1939             $workshop->modname    = 'workshop';
1940             workshop_update_grades($workshop);
1941         }
1943         $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
1944         $this->phase = $newphase;
1945         $eventdata = array(
1946             'objectid' => $this->id,
1947             'context' => $this->context,
1948             'other' => array(
1949                 'workshopphase' => $this->phase
1950             )
1951         );
1952         $event = \mod_workshop\event\phase_switched::create($eventdata);
1953         $event->trigger();
1954         return true;
1955     }
1957     /**
1958      * Saves a raw grade for submission as calculated from the assessment form fields
1959      *
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
1963      */
1964     public function set_peer_grade($assessmentid, $grade) {
1965         global $DB;
1967         if (is_null($grade)) {
1968             return false;
1969         }
1970         $data = new stdclass();
1971         $data->id = $assessmentid;
1972         $data->grade = $grade;
1973         $data->timemodified = time();
1974         $DB->update_record('workshop_assessments', $data);
1975         return $grade;
1976     }
1978     /**
1979      * Prepares data object with all workshop grades to be rendered
1980      *
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
1988      */
1989     public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
1990         global $DB;
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?
1997             return array();
1998         }
2000         if (!in_array($sortby, array('lastname', 'firstname', 'submissiontitle', 'submissionmodified',
2001                 'submissiongrade', 'gradinggrade'))) {
2002             $sortby = 'lastname';
2003         }
2005         if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
2006             $sorthow = 'ASC';
2007         }
2009         // get the list of user ids to be displayed
2010         if ($canviewall) {
2011             $participants = $this->get_participants(false, $groupid);
2012         } else {
2013             // this is an ordinary workshop participant (aka student) - display the report just for him/her
2014             $participants = array($userid => (object)array('id' => $userid));
2015         }
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;
2025             $sqlsort = array();
2026             $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
2027             foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
2028                 $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
2029             }
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
2034                       FROM {user} u
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
2038                   ORDER BY $sqlsort";
2039             $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
2040         } else {
2041             $participants = array();
2042         }
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;
2058                 }
2059             }
2060         }
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;
2076                 }
2077             }
2078         }
2080         // get the user details for all reviewers of the displayed participants
2081         $reviewers = array();
2083         if ($submissions) {
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;
2104                     }
2105                 }
2106             }
2107         }
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
2118                       FROM {user} u
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;
2134                     }
2135                 }
2136             }
2137         }
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();
2152         }
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;
2163         }
2164         unset($submissions);
2165         unset($submission);
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;
2177         }
2178         unset($reviewers);
2179         unset($reviewer);
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;
2191         }
2192         unset($reviewees);
2193         unset($reviewee);
2195         foreach ($grades as $grade) {
2196             $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
2197         }
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);
2205         return $data;
2206     }
2208     /**
2209      * Calculates the real value of a grade
2210      *
2211      * @param float $value percentual value from 0 to 100
2212      * @param float $max   the maximal grade
2213      * @return string
2214      */
2215     public function real_grade_value($value, $max) {
2216         $localized = true;
2217         if (is_null($value) or $value === '') {
2218             return null;
2219         } elseif ($max == 0) {
2220             return 0;
2221         } else {
2222             return format_float($max * $value / 100, $this->gradedecimals, $localized);
2223         }
2224     }
2226     /**
2227      * Calculates the raw (percentual) value from a real grade
2228      *
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)
2234      */
2235     public function raw_grade_value($value, $max) {
2236         if (is_null($value) or $value === '') {
2237             return null;
2238         }
2239         if ($max == 0 or $value < 0) {
2240             return 0;
2241         }
2242         $p = $value / $max * 100;
2243         if ($p > 100) {
2244             return $max;
2245         }
2246         return grade_floatval($p);
2247     }
2249     /**
2250      * Calculates the real value of grade for submission
2251      *
2252      * @param float $value percentual value from 0 to 100
2253      * @return string
2254      */
2255     public function real_grade($value) {
2256         return $this->real_grade_value($value, $this->grade);
2257     }
2259     /**
2260      * Calculates the real value of grade for assessment
2261      *
2262      * @param float $value percentual value from 0 to 100
2263      * @return string
2264      */
2265     public function real_grading_grade($value) {
2266         return $this->real_grade_value($value, $this->gradinggrade);
2267     }
2269     /**
2270      * Sets the given grades and received grading grades to null
2271      *
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.
2275      *
2276      * @return void
2277      */
2278     public function clear_assessments() {
2279         global $DB;
2281         $submissions = $this->get_submissions();
2282         if (empty($submissions)) {
2283             // no money, no love
2284             return;
2285         }
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);
2291     }
2293     /**
2294      * Sets the grades for submission to null
2295      *
2296      * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2297      * @return void
2298      */
2299     public function clear_submission_grades($restrict=null) {
2300         global $DB;
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);
2311         } else {
2312             throw new coding_exception('Empty value is not a valid parameter here');
2313         }
2315         $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
2316     }
2318     /**
2319      * Calculates grades for submission for the given participant(s) and updates it in the database
2320      *
2321      * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2322      * @return void
2323      */
2324     public function aggregate_submission_grades($restrict=null) {
2325         global $DB;
2327         // fetch a recordset with all assessments to process
2328         $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
2329                        a.weight, a.grade
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);
2341         } else {
2342             throw new coding_exception('Empty value is not a valid parameter here');
2343         }
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;
2355             }
2356             if ($current->submissionid == $previous->submissionid) {
2357                 // we are still processing the current submission
2358                 $batch[] = $current;
2359             } else {
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;
2365             }
2366         }
2367         // do not forget to process the last batch!
2368         $this->aggregate_submission_grades_process($batch);
2369         $rs->close();
2370     }
2372     /**
2373      * Sets the aggregated grades for assessment to null
2374      *
2375      * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2376      * @return void
2377      */
2378     public function clear_grading_grades($restrict=null) {
2379         global $DB;
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);
2390         } else {
2391             throw new coding_exception('Empty value is not a valid parameter here');
2392         }
2394         $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
2395     }
2397     /**
2398      * Calculates grades for assessment for the given participant(s)
2399      *
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.
2402      *
2403      * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2404      * @return void
2405      */
2406     public function aggregate_grading_grades($restrict=null) {
2407         global $DB;
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);
2424         } else {
2425             throw new coding_exception('Empty value is not a valid parameter here');
2426         }
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;
2438             }
2439             if ($current->reviewerid == $previous->reviewerid) {
2440                 // we are still processing the current reviewer
2441                 $batch[] = $current;
2442             } else {
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;
2448             }
2449         }
2450         // do not forget to process the last batch!
2451         $this->aggregate_grading_grades_process($batch);
2452         $rs->close();
2453     }
2455     /**
2456      * Returns the mform the teachers use to put a feedback for the reviewer
2457      *
2458      * @param moodle_url $actionurl
2459      * @param stdClass $assessment
2460      * @param array $options editable, editableweight, overridablegradinggrade
2461      * @return workshop_feedbackreviewer_form
2462      */
2463     public function get_feedbackreviewer_form(moodle_url $actionurl, stdclass $assessment, $options=array()) {
2464         global $CFG;
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');
2476         }
2477         if (!isset($options['editable'])) {
2478             $editable = true;   // by default
2479         } else {
2480             $editable = (bool)$options['editable'];
2481         }
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);
2489     }
2491     /**
2492      * Returns the mform the teachers use to put a feedback for the author on their submission
2493      *
2494      * @param moodle_url $actionurl
2495      * @param stdClass $submission
2496      * @param array $options editable
2497      * @return workshop_feedbackauthor_form
2498      */
2499     public function get_feedbackauthor_form(moodle_url $actionurl, stdclass $submission, $options=array()) {
2500         global $CFG;
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');
2512         }
2513         if (!isset($options['editable'])) {
2514             $editable = true;   // by default
2515         } else {
2516             $editable = (bool)$options['editable'];
2517         }
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);
2525     }
2527     /**
2528      * Returns the information about the user's grades as they are stored in the gradebook
2529      *
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.
2534      *
2535      * @param int $userid the user's id
2536      * @return workshop_final_grades|false
2537      */
2538     public function get_gradebook_grades($userid) {
2539         global $CFG;
2540         require_once($CFG->libdir.'/gradelib.php');
2542         if (empty($userid)) {
2543             throw new coding_exception('User id expected, empty value given.');
2544         }
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;
2557                     }
2558                 }
2559             }
2560         }
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;
2568                     }
2569                 }
2570             }
2571         }
2573         if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
2574             return $grades;
2575         }
2577         return false;
2578     }
2580     /**
2581      * Return the editor options for the submission content field.
2582      *
2583      * @return array
2584      */
2585     public function submission_content_options() {
2586         global $CFG;
2587         require_once($CFG->dirroot.'/repository/lib.php');
2589         return array(
2590             'trusttext' => true,
2591             'subdirs' => false,
2592             'maxfiles' => $this->nattachments,
2593             'maxbytes' => $this->maxbytes,
2594             'context' => $this->context,
2595             'return_types' => FILE_INTERNAL | FILE_EXTERNAL,
2596           );
2597     }
2599     /**
2600      * Return the filemanager options for the submission attachments field.
2601      *
2602      * @return array
2603      */
2604     public function submission_attachment_options() {
2605         global $CFG;
2606         require_once($CFG->dirroot.'/repository/lib.php');
2608         $options = array(
2609             'subdirs' => true,
2610             'maxfiles' => $this->nattachments,
2611             'maxbytes' => $this->maxbytes,
2612             'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
2613         );
2615         $filetypesutil = new \core_form\filetypes_util();
2616         $options['accepted_types'] = $filetypesutil->normalize_file_types($this->submissionfiletypes);
2618         return $options;
2619     }
2621     /**
2622      * Return the editor options for the overall feedback for the author.
2623      *
2624      * @return array
2625      */
2626     public function overall_feedback_content_options() {
2627         global $CFG;
2628         require_once($CFG->dirroot.'/repository/lib.php');
2630         return array(
2631             'subdirs' => 0,
2632             'maxbytes' => $this->overallfeedbackmaxbytes,
2633             'maxfiles' => $this->overallfeedbackfiles,
2634             'changeformat' => 1,
2635             'context' => $this->context,
2636             'return_types' => FILE_INTERNAL,
2637         );
2638     }
2640     /**
2641      * Return the filemanager options for the overall feedback for the author.
2642      *
2643      * @return array
2644      */
2645     public function overall_feedback_attachment_options() {
2646         global $CFG;
2647         require_once($CFG->dirroot.'/repository/lib.php');
2649         $options = array(
2650             'subdirs' => 1,
2651             'maxbytes' => $this->overallfeedbackmaxbytes,
2652             'maxfiles' => $this->overallfeedbackfiles,
2653             'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
2654         );
2656         $filetypesutil = new \core_form\filetypes_util();
2657         $options['accepted_types'] = $filetypesutil->normalize_file_types($this->overallfeedbackfiletypes);
2659         return $options;
2660     }
2662     /**
2663      * Performs the reset of this workshop instance.
2664      *
2665      * @param stdClass $data The actual course reset settings.
2666      * @return array List of results, each being array[(string)component, (string)item, (string)error]
2667      */
2668     public function reset_userdata(stdClass $data) {
2670         $componentstr = get_string('pluginname', 'workshop').': '.format_string($this->name);
2671         $status = array();
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) {
2678                 $status[] = array(
2679                     'component' => $componentstr,
2680                     'item' => get_string('resetassessments', 'mod_workshop'),
2681                     'error' => false,
2682                 );
2683             } else {
2684                 $status[] = array(
2685                     'component' => $componentstr,
2686                     'item' => get_string('resetassessments', 'mod_workshop'),
2687                     'error' => $result,
2688                 );
2689             }
2690         }
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) {
2696                 $status[] = array(
2697                     'component' => $componentstr,
2698                     'item' => get_string('resetsubmissions', 'mod_workshop'),
2699                     'error' => false,
2700                 );
2701             } else {
2702                 $status[] = array(
2703                     'component' => $componentstr,
2704                     'item' => get_string('resetsubmissions', 'mod_workshop'),
2705                     'error' => $result,
2706                 );
2707             }
2708         }
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();
2714             $status[] = array(
2715                 'component' => $componentstr,
2716                 'item' => get_string('resetsubmissions', 'mod_workshop'),
2717                 'error' => false,
2718             );
2719         }
2721         return $status;
2722     }
2724     /**
2725      * Check if the current user can access the other user's group.
2726      *
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.
2730      *
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.
2734      *
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.
2738      *
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.
2741      */
2742     public function check_group_membership($otheruserid) {
2743         global $USER;
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.
2747             return true;
2749         } else if (has_capability('moodle/site:accessallgroups', $this->context)) {
2750             // The current user can access all groups.
2751             return true;
2753         } else {
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.
2760                 return false;
2762             } else {
2763                 // The current user has a group common with the other user.
2764                 return true;
2765             }
2766         }
2767     }
2769     /**
2770      * Check whether the given user has assessed all his required examples before submission.
2771      *
2772      * @param  int $userid the user to check
2773      * @return bool        false if there are examples missing assessment, true otherwise.
2774      * @since  Moodle 3.4
2775      */
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);
2786                 }
2787                 if (is_null($example->grade)) {
2788                     return false;
2789                 }
2790             }
2791         }
2792         return true;
2793     }
2795     /**
2796      * Check that all required examples have been assessed by the given user.
2797      *
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.
2800      * @since  Moodle 3.4
2801      */
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');
2812             } else {
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');
2817                     }
2818                 }
2819             }
2820         }
2821         return array(true, null);
2822     }
2824     /**
2825      * Trigger module viewed event and set the module viewed for completion.
2826      *
2827      * @since  Moodle 3.4
2828      */
2829     public function set_module_viewed() {
2830         global $CFG;
2831         require_once($CFG->libdir . '/completionlib.php');
2833         // Mark viewed.
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);
2846         $event->trigger();
2847     }
2849     /**
2850      * Validates the submission form or WS data.
2851      *
2852      * @param  array $data the data to be validated
2853      * @return array       the validation errors (if any)
2854      * @since  Moodle 3.4
2855      */
2856     public function validate_submission_data($data) {
2857         global $DB, $USER;
2859         $errors = array();
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');
2871             }
2872         }
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');
2878         }
2880         return $errors;
2881     }
2883     /**
2884      * Adds or updates a submission.
2885      *
2886      * @param stdClass $submission The submissin data (via form or via WS).
2887      * @return the new or updated submission id.
2888      * @since  Moodle 3.4
2889      */
2890     public function edit_submission($submission) {
2891         global $USER, $DB;
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);
2896         } else {
2897             throw new coding_exception('Invalid submission form data value: example');
2898         }
2899         $timenow = time();
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();
2906         }
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;
2915         }
2916         if ($this->phase == self::PHASE_ASSESSMENT) {
2917             $submission->late = $submission->late | 0x2;
2918         }
2920         // Event information.
2921         $params = array(
2922             'context' => $this->context,
2923             'courseid' => $this->course->id,
2924             'other' => array(
2925                 'submissiontitle' => $submission->title
2926             )
2927         );
2928         $logdata = null;
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);
2933             $event->trigger();
2934         } else {
2935             if (empty($submission->id) or empty($submission->id) or ($submission->id != $submission->id)) {
2936                 throw new moodle_exception('err_submissionid', 'workshop');
2937             }
2938         }
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;
2951         }
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);
2956         $event->trigger();
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);
2967         $event->trigger();
2969         return $submission->id;
2970     }
2972     /**
2973      * Helper method for validating if the current user can view the given assessment.
2974      *
2975      * @param  stdClass   $assessment assessment object
2976      * @param  stdClass   $submission submission object
2977      * @return void
2978      * @throws moodle_exception
2979      * @since  Moodle 3.4
2980      */
2981     public function check_view_assessment($assessment, $submission) {
2982         global $USER;
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');
2993         }
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');
2998         }
2999     }
3001     ////////////////////////////////////////////////////////////////////////////////
3002     // Internal methods (implementation details)                                  //
3003     ////////////////////////////////////////////////////////////////////////////////
3005     /**
3006      * Given an array of all assessments of a single submission, calculates the final grade for this submission
3007      *
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.
3010      *
3011      * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
3012      * @return void
3013      */
3014     protected function aggregate_submission_grades_process(array $assessments) {
3015         global $DB;
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
3020         $sumgrades      = 0;
3021         $sumweights     = 0;
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;
3027             }
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;
3031             }
3032             if (is_null($assessment->grade)) {
3033                 // this was not assessed yet
3034                 continue;
3035             }
3036             if ($assessment->weight == 0) {
3037                 // this does not influence the calculation
3038                 continue;
3039             }
3040             $sumgrades  += $assessment->grade * $assessment->weight;
3041             $sumweights += $assessment->weight;
3042         }
3043         if ($sumweights > 0 and is_null($finalgrade)) {
3044             $finalgrade = grade_floatval($sumgrades / $sumweights);
3045         }
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);
3054         }
3055     }
3057     /**
3058      * Given an array of all assessments done by a single reviewer, calculates the final grading grade
3059      *
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.
3062      *
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
3065      * @return void
3066      */
3067     protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
3068         global $DB;
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
3074         $sumgrades  = 0;
3075         $count      = 0;
3077         if (is_null($timegraded)) {
3078             $timegraded = time();
3079         }
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;
3085             }
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;
3089             }
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;
3093             }
3094             if (!is_null($assessment->gradinggradeover)) {
3095                 // the grading grade for this assessment is overridden by a teacher
3096                 $sumgrades += $assessment->gradinggradeover;
3097                 $count++;
3098             } else {
3099                 if (!is_null($assessment->gradinggrade)) {
3100                     $sumgrades += $assessment->gradinggrade;
3101                     $count++;
3102                 }
3103             }
3104         }
3105         if ($count > 0) {
3106             $finalgrade = grade_floatval($sumgrades / $count);
3107         }
3109         // Event information.
3110         $params = array(
3111             'context' => $this->context,
3112             'courseid' => $this->course->id,
3113             'relateduserid' => $reviewerid
3114         );
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
3121             );
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);
3134                 $event->trigger();
3135             } else {
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);
3143                 $event->trigger();
3144             }
3145         }
3146     }
3148     /**
3149      * Returns SQL to fetch all enrolled users with the given capability in the current workshop
3150      *
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.
3153      *
3154      * The list is automatically restricted according to any availability restrictions
3155      * that apply to user lists (e.g. group, grouping restrictions).
3156      *
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
3161      */
3162     protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) {
3163         global $CFG;
3164         /** @var int static counter used to generate unique parameter holders */
3165         static $inc = 0;
3166         $inc++;
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'));
3174             $sql = array();
3175             $params = array();
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);
3179                     $sql[] = $gsql;
3180                     $params = array_merge($params, $gparams);
3181                 }
3182             }
3183             $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql);
3184             return array($sql, $params);
3185         }
3187         list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true);
3189         $userfields = user_picture::fields('u');
3191         $sql = "SELECT $userfields
3192                   FROM {user} u
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;
3198         }
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);
3204         if ($listsql) {
3205             $sql .= " JOIN ($listsql) restricted ON restricted.id = u.id ";
3206             $params = array_merge($params, $listparams);
3207         }
3209         return array($sql, $params);
3210     }
3212     /**
3213      * Returns SQL statement that can be used to fetch all actively enrolled participants in the workshop
3214      *
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
3218      */
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)) {
3228                 $sql = $sql2;
3229                 $params = $params2;
3230             } else {
3231                 $sql = $sql1;
3232                 $params = $params1;
3233             }
3234         } else {
3235             $sql = $sql1.PHP_EOL." UNION ".PHP_EOL.$sql2;
3236             $params = array_merge($params1, $params2);
3237         }
3239         return array($sql, $params);
3240     }
3242     /**
3243      * @return array of available workshop phases
3244      */
3245     protected function available_phases_list() {
3246         return array(
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,
3252         );
3253     }
3255     /**
3256      * Converts absolute URL to relative URL needed by {@see add_to_log()}
3257      *
3258      * @param moodle_url $url absolute URL
3259      * @return string
3260      */
3261     protected function log_convert_url(moodle_url $fullurl) {
3262         static $baseurl;
3264         if (!isset($baseurl)) {
3265             $baseurl = new moodle_url('/mod/workshop/');
3266             $baseurl = $baseurl->out();
3267         }
3269         return substr($fullurl->out(), strlen($baseurl));
3270     }
3272     /**
3273      * Removes all user data related to assessments (including allocations).
3274      *
3275      * This includes assessments of example submissions as long as they are not
3276      * referential assessments.
3277      *
3278      * @param stdClass $data The actual course reset settings.
3279      * @return bool|string True on success, error message otherwise.
3280      */
3281     protected function reset_userdata_assessments(stdClass $data) {
3282         global $DB;
3284         $sql = "SELECT a.id
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));
3295         return true;
3296     }
3298     /**
3299      * Removes all user data related to participants' submissions.
3300      *
3301      * @param stdClass $data The actual course reset settings.
3302      * @return bool|string True on success, error message otherwise.
3303      */
3304     protected function reset_userdata_submissions(stdClass $data) {
3305         global $DB;
3307         $submissions = $this->get_submissions();
3308         foreach ($submissions as $submission) {
3309             $this->delete_submission($submission);
3310         }
3312         return true;
3313     }
3315     /**
3316      * Hard set the workshop phase to the setup one.
3317      */
3318     protected function reset_phase() {
3319         global $DB;
3321         $DB->set_field('workshop', 'phase', self::PHASE_SETUP, array('id' => $this->id));
3322         $this->phase = self::PHASE_SETUP;
3323     }
3326 ////////////////////////////////////////////////////////////////////////////////
3327 // Renderable components
3328 ////////////////////////////////////////////////////////////////////////////////
3330 /**
3331  * Represents the user planner tool
3332  *
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).
3335  */
3336 class workshop_user_plan implements renderable {
3338     /** @var int id of the user this plan is for */
3339     public $userid;
3340     /** @var workshop */
3341     public $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;
3347     /**
3348      * Prepare an individual workshop plan for the given user.
3349      *
3350      * @param workshop $workshop instance
3351      * @param int $userid whom the plan is prepared for
3352      */
3353     public function __construct(workshop $workshop, $userid) {
3354         global $DB;
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;
3371         }
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;