MDL-31936 workshop: Delete attachments on record removal
[moodle.git] / mod / workshop / locallib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Library of internal classes and functions for module workshop
20  *
21  * All the workshop specific functions, needed to implement the module
22  * logic, should go to here. Instead of having bunch of function named
23  * workshop_something() taking the workshop instance as the first
24  * parameter, we use a class workshop that provides all methods.
25  *
26  * @package    mod_workshop
27  * @copyright  2009 David Mudrak <david.mudrak@gmail.com>
28  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29  */
31 defined('MOODLE_INTERNAL') || die();
33 require_once(dirname(__FILE__).'/lib.php');     // we extend this library here
34 require_once($CFG->libdir . '/gradelib.php');   // we use some rounding and comparing routines here
35 require_once($CFG->libdir . '/filelib.php');
37 /**
38  * Full-featured workshop API
39  *
40  * This wraps the workshop database record with a set of methods that are called
41  * from the module itself. The class should be initialized right after you get
42  * $workshop, $cm and $course records at the begining of the script.
43  */
44 class workshop {
46     /** error status of the {@link self::add_allocation()} */
47     const ALLOCATION_EXISTS             = -9999;
49     /** the internal code of the workshop phases as are stored in the database */
50     const PHASE_SETUP                   = 10;
51     const PHASE_SUBMISSION              = 20;
52     const PHASE_ASSESSMENT              = 30;
53     const PHASE_EVALUATION              = 40;
54     const PHASE_CLOSED                  = 50;
56     /** the internal code of the examples modes as are stored in the database */
57     const EXAMPLES_VOLUNTARY            = 0;
58     const EXAMPLES_BEFORE_SUBMISSION    = 1;
59     const EXAMPLES_BEFORE_ASSESSMENT    = 2;
61     /** @var cm_info course module record */
62     public $cm;
64     /** @var stdclass course record */
65     public $course;
67     /** @var stdclass context object */
68     public $context;
70     /** @var int workshop instance identifier */
71     public $id;
73     /** @var string workshop activity name */
74     public $name;
76     /** @var string introduction or description of the activity */
77     public $intro;
79     /** @var int format of the {@link $intro} */
80     public $introformat;
82     /** @var string instructions for the submission phase */
83     public $instructauthors;
85     /** @var int format of the {@link $instructauthors} */
86     public $instructauthorsformat;
88     /** @var string instructions for the assessment phase */
89     public $instructreviewers;
91     /** @var int format of the {@link $instructreviewers} */
92     public $instructreviewersformat;
94     /** @var int timestamp of when the module was modified */
95     public $timemodified;
97     /** @var int current phase of workshop, for example {@link workshop::PHASE_SETUP} */
98     public $phase;
100     /** @var bool optional feature: students practise evaluating on example submissions from teacher */
101     public $useexamples;
103     /** @var bool optional feature: students perform peer assessment of others' work (deprecated, consider always enabled) */
104     public $usepeerassessment;
106     /** @var bool optional feature: students perform self assessment of their own work */
107     public $useselfassessment;
109     /** @var float number (10, 5) unsigned, the maximum grade for submission */
110     public $grade;
112     /** @var float number (10, 5) unsigned, the maximum grade for assessment */
113     public $gradinggrade;
115     /** @var string type of the current grading strategy used in this workshop, for example 'accumulative' */
116     public $strategy;
118     /** @var string the name of the evaluation plugin to use for grading grades calculation */
119     public $evaluation;
121     /** @var int number of digits that should be shown after the decimal point when displaying grades */
122     public $gradedecimals;
124     /** @var int number of allowed submission attachments and the files embedded into submission */
125     public $nattachments;
127     /** @var bool allow submitting the work after the deadline */
128     public $latesubmissions;
130     /** @var int maximum size of the one attached file in bytes */
131     public $maxbytes;
133     /** @var int mode of example submissions support, for example {@link workshop::EXAMPLES_VOLUNTARY} */
134     public $examplesmode;
136     /** @var int if greater than 0 then the submission is not allowed before this timestamp */
137     public $submissionstart;
139     /** @var int if greater than 0 then the submission is not allowed after this timestamp */
140     public $submissionend;
142     /** @var int if greater than 0 then the peer assessment is not allowed before this timestamp */
143     public $assessmentstart;
145     /** @var int if greater than 0 then the peer assessment is not allowed after this timestamp */
146     public $assessmentend;
148     /** @var bool automatically switch to the assessment phase after the submissions deadline */
149     public $phaseswitchassessment;
151     /** @var string conclusion text to be displayed at the end of the activity */
152     public $conclusion;
154     /** @var int format of the conclusion text */
155     public $conclusionformat;
157     /** @var int the mode of the overall feedback */
158     public $overallfeedbackmode;
160     /** @var int maximum number of overall feedback attachments */
161     public $overallfeedbackfiles;
163     /** @var int maximum size of one file attached to the overall feedback */
164     public $overallfeedbackmaxbytes;
166     /**
167      * @var workshop_strategy grading strategy instance
168      * Do not use directly, get the instance using {@link workshop::grading_strategy_instance()}
169      */
170     protected $strategyinstance = null;
172     /**
173      * @var workshop_evaluation grading evaluation instance
174      * Do not use directly, get the instance using {@link workshop::grading_evaluation_instance()}
175      */
176     protected $evaluationinstance = null;
178     /**
179      * Initializes the workshop API instance using the data from DB
180      *
181      * Makes deep copy of all passed records properties.
182      *
183      * For unit testing only, $cm and $course may be set to null. This is so that
184      * you can test without having any real database objects if you like. Not all
185      * functions will work in this situation.
186      *
187      * @param stdClass $dbrecord Workshop instance data from {workshop} table
188      * @param stdClass|cm_info $cm Course module record
189      * @param stdClass $course Course record from {course} table
190      * @param stdClass $context The context of the workshop instance
191      */
192     public function __construct(stdclass $dbrecord, $cm, $course, stdclass $context=null) {
193         foreach ($dbrecord as $field => $value) {
194             if (property_exists('workshop', $field)) {
195                 $this->{$field} = $value;
196             }
197         }
198         if (is_null($cm) || is_null($course)) {
199             throw new coding_exception('Must specify $cm and $course');
200         }
201         $this->course = $course;
202         if ($cm instanceof cm_info) {
203             $this->cm = $cm;
204         } else {
205             $modinfo = get_fast_modinfo($course);
206             $this->cm = $modinfo->get_cm($cm->id);
207         }
208         if (is_null($context)) {
209             $this->context = context_module::instance($this->cm->id);
210         } else {
211             $this->context = $context;
212         }
213     }
215     ////////////////////////////////////////////////////////////////////////////////
216     // Static methods                                                             //
217     ////////////////////////////////////////////////////////////////////////////////
219     /**
220      * Return list of available allocation methods
221      *
222      * @return array Array ['string' => 'string'] of localized allocation method names
223      */
224     public static function installed_allocators() {
225         $installed = core_component::get_plugin_list('workshopallocation');
226         $forms = array();
227         foreach ($installed as $allocation => $allocationpath) {
228             if (file_exists($allocationpath . '/lib.php')) {
229                 $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation);
230             }
231         }
232         // usability - make sure that manual allocation appears the first
233         if (isset($forms['manual'])) {
234             $m = array('manual' => $forms['manual']);
235             unset($forms['manual']);
236             $forms = array_merge($m, $forms);
237         }
238         return $forms;
239     }
241     /**
242      * Returns an array of options for the editors that are used for submitting and assessing instructions
243      *
244      * @param stdClass $context
245      * @uses EDITOR_UNLIMITED_FILES hard-coded value for the 'maxfiles' option
246      * @return array
247      */
248     public static function instruction_editors_options(stdclass $context) {
249         return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => -1,
250                      'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0);
251     }
253     /**
254      * Given the percent and the total, returns the number
255      *
256      * @param float $percent from 0 to 100
257      * @param float $total   the 100% value
258      * @return float
259      */
260     public static function percent_to_value($percent, $total) {
261         if ($percent < 0 or $percent > 100) {
262             throw new coding_exception('The percent can not be less than 0 or higher than 100');
263         }
265         return $total * $percent / 100;
266     }
268     /**
269      * Returns an array of numeric values that can be used as maximum grades
270      *
271      * @return array Array of integers
272      */
273     public static function available_maxgrades_list() {
274         $grades = array();
275         for ($i=100; $i>=0; $i--) {
276             $grades[$i] = $i;
277         }
278         return $grades;
279     }
281     /**
282      * Returns the localized list of supported examples modes
283      *
284      * @return array
285      */
286     public static function available_example_modes_list() {
287         $options = array();
288         $options[self::EXAMPLES_VOLUNTARY]         = get_string('examplesvoluntary', 'workshop');
289         $options[self::EXAMPLES_BEFORE_SUBMISSION] = get_string('examplesbeforesubmission', 'workshop');
290         $options[self::EXAMPLES_BEFORE_ASSESSMENT] = get_string('examplesbeforeassessment', 'workshop');
291         return $options;
292     }
294     /**
295      * Returns the list of available grading strategy methods
296      *
297      * @return array ['string' => 'string']
298      */
299     public static function available_strategies_list() {
300         $installed = core_component::get_plugin_list('workshopform');
301         $forms = array();
302         foreach ($installed as $strategy => $strategypath) {
303             if (file_exists($strategypath . '/lib.php')) {
304                 $forms[$strategy] = get_string('pluginname', 'workshopform_' . $strategy);
305             }
306         }
307         return $forms;
308     }
310     /**
311      * Returns the list of available grading evaluation methods
312      *
313      * @return array of (string)name => (string)localized title
314      */
315     public static function available_evaluators_list() {
316         $evals = array();
317         foreach (core_component::get_plugin_list_with_file('workshopeval', 'lib.php', false) as $eval => $evalpath) {
318             $evals[$eval] = get_string('pluginname', 'workshopeval_' . $eval);
319         }
320         return $evals;
321     }
323     /**
324      * Return an array of possible values of assessment dimension weight
325      *
326      * @return array of integers 0, 1, 2, ..., 16
327      */
328     public static function available_dimension_weights_list() {
329         $weights = array();
330         for ($i=16; $i>=0; $i--) {
331             $weights[$i] = $i;
332         }
333         return $weights;
334     }
336     /**
337      * Return an array of possible values of assessment weight
338      *
339      * Note there is no real reason why the maximum value here is 16. It used to be 10 in
340      * workshop 1.x and I just decided to use the same number as in the maximum weight of
341      * a single assessment dimension.
342      * The value looks reasonable, though. Teachers who would want to assign themselves
343      * higher weight probably do not want peer assessment really...
344      *
345      * @return array of integers 0, 1, 2, ..., 16
346      */
347     public static function available_assessment_weights_list() {
348         $weights = array();
349         for ($i=16; $i>=0; $i--) {
350             $weights[$i] = $i;
351         }
352         return $weights;
353     }
355     /**
356      * Helper function returning the greatest common divisor
357      *
358      * @param int $a
359      * @param int $b
360      * @return int
361      */
362     public static function gcd($a, $b) {
363         return ($b == 0) ? ($a):(self::gcd($b, $a % $b));
364     }
366     /**
367      * Helper function returning the least common multiple
368      *
369      * @param int $a
370      * @param int $b
371      * @return int
372      */
373     public static function lcm($a, $b) {
374         return ($a / self::gcd($a,$b)) * $b;
375     }
377     /**
378      * Returns an object suitable for strings containing dates/times
379      *
380      * The returned object contains properties date, datefullshort, datetime, ... containing the given
381      * timestamp formatted using strftimedate, strftimedatefullshort, strftimedatetime, ... from the
382      * current lang's langconfig.php
383      * This allows translators and administrators customize the date/time format.
384      *
385      * @param int $timestamp the timestamp in UTC
386      * @return stdclass
387      */
388     public static function timestamp_formats($timestamp) {
389         $formats = array('date', 'datefullshort', 'dateshort', 'datetime',
390                 'datetimeshort', 'daydate', 'daydatetime', 'dayshort', 'daytime',
391                 'monthyear', 'recent', 'recentfull', 'time');
392         $a = new stdclass();
393         foreach ($formats as $format) {
394             $a->{$format} = userdate($timestamp, get_string('strftime'.$format, 'langconfig'));
395         }
396         $day = userdate($timestamp, '%Y%m%d', 99, false);
397         $today = userdate(time(), '%Y%m%d', 99, false);
398         $tomorrow = userdate(time() + DAYSECS, '%Y%m%d', 99, false);
399         $yesterday = userdate(time() - DAYSECS, '%Y%m%d', 99, false);
400         $distance = (int)round(abs(time() - $timestamp) / DAYSECS);
401         if ($day == $today) {
402             $a->distanceday = get_string('daystoday', 'workshop');
403         } elseif ($day == $yesterday) {
404             $a->distanceday = get_string('daysyesterday', 'workshop');
405         } elseif ($day < $today) {
406             $a->distanceday = get_string('daysago', 'workshop', $distance);
407         } elseif ($day == $tomorrow) {
408             $a->distanceday = get_string('daystomorrow', 'workshop');
409         } elseif ($day > $today) {
410             $a->distanceday = get_string('daysleft', 'workshop', $distance);
411         }
412         return $a;
413     }
415     ////////////////////////////////////////////////////////////////////////////////
416     // Workshop API                                                               //
417     ////////////////////////////////////////////////////////////////////////////////
419     /**
420      * Fetches all enrolled users with the capability mod/workshop:submit in the current workshop
421      *
422      * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
423      * Only users with the active enrolment are returned.
424      *
425      * @param bool $musthavesubmission if true, return only users who have already submitted
426      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
427      * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
428      * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
429      * @return array array[userid] => stdClass
430      */
431     public function get_potential_authors($musthavesubmission=true, $groupid=0, $limitfrom=0, $limitnum=0) {
432         global $DB;
434         list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
436         if (empty($sql)) {
437             return array();
438         }
440         list($sort, $sortparams) = users_order_by_sql('tmp');
441         $sql = "SELECT *
442                   FROM ($sql) tmp
443               ORDER BY $sort";
445         return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
446     }
448     /**
449      * Returns the total number of users that would be fetched by {@link self::get_potential_authors()}
450      *
451      * @param bool $musthavesubmission if true, count only users who have already submitted
452      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
453      * @return int
454      */
455     public function count_potential_authors($musthavesubmission=true, $groupid=0) {
456         global $DB;
458         list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
460         if (empty($sql)) {
461             return 0;
462         }
464         $sql = "SELECT COUNT(*)
465                   FROM ($sql) tmp";
467         return $DB->count_records_sql($sql, $params);
468     }
470     /**
471      * Fetches all enrolled users with the capability mod/workshop:peerassess in the current workshop
472      *
473      * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
474      * Only users with the active enrolment are returned.
475      *
476      * @param bool $musthavesubmission if true, return only users who have already submitted
477      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
478      * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
479      * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
480      * @return array array[userid] => stdClass
481      */
482     public function get_potential_reviewers($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
483         global $DB;
485         list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
487         if (empty($sql)) {
488             return array();
489         }
491         list($sort, $sortparams) = users_order_by_sql('tmp');
492         $sql = "SELECT *
493                   FROM ($sql) tmp
494               ORDER BY $sort";
496         return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
497     }
499     /**
500      * Returns the total number of users that would be fetched by {@link self::get_potential_reviewers()}
501      *
502      * @param bool $musthavesubmission if true, count only users who have already submitted
503      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
504      * @return int
505      */
506     public function count_potential_reviewers($musthavesubmission=false, $groupid=0) {
507         global $DB;
509         list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
511         if (empty($sql)) {
512             return 0;
513         }
515         $sql = "SELECT COUNT(*)
516                   FROM ($sql) tmp";
518         return $DB->count_records_sql($sql, $params);
519     }
521     /**
522      * Fetches all enrolled users that are authors or reviewers (or both) in the current workshop
523      *
524      * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
525      * Only users with the active enrolment are returned.
526      *
527      * @see self::get_potential_authors()
528      * @see self::get_potential_reviewers()
529      * @param bool $musthavesubmission if true, return only users who have already submitted
530      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
531      * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
532      * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
533      * @return array array[userid] => stdClass
534      */
535     public function get_participants($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
536         global $DB;
538         list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
540         if (empty($sql)) {
541             return array();
542         }
544         list($sort, $sortparams) = users_order_by_sql('tmp');
545         $sql = "SELECT *
546                   FROM ($sql) tmp
547               ORDER BY $sort";
549         return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
550     }
552     /**
553      * Returns the total number of records that would be returned by {@link self::get_participants()}
554      *
555      * @param bool $musthavesubmission if true, return only users who have already submitted
556      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
557      * @return int
558      */
559     public function count_participants($musthavesubmission=false, $groupid=0) {
560         global $DB;
562         list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
564         if (empty($sql)) {
565             return 0;
566         }
568         $sql = "SELECT COUNT(*)
569                   FROM ($sql) tmp";
571         return $DB->count_records_sql($sql, $params);
572     }
574     /**
575      * Checks if the given user is an actively enrolled participant in the workshop
576      *
577      * @param int $userid, defaults to the current $USER
578      * @return boolean
579      */
580     public function is_participant($userid=null) {
581         global $USER, $DB;
583         if (is_null($userid)) {
584             $userid = $USER->id;
585         }
587         list($sql, $params) = $this->get_participants_sql();
589         if (empty($sql)) {
590             return false;
591         }
593         $sql = "SELECT COUNT(*)
594                   FROM {user} uxx
595                   JOIN ({$sql}) pxx ON uxx.id = pxx.id
596                  WHERE uxx.id = :uxxid";
597         $params['uxxid'] = $userid;
599         if ($DB->count_records_sql($sql, $params)) {
600             return true;
601         }
603         return false;
604     }
606     /**
607      * Groups the given users by the group membership
608      *
609      * This takes the module grouping settings into account. If a grouping is
610      * set, returns only groups withing the course module grouping. Always
611      * returns group [0] with all the given users.
612      *
613      * @param array $users array[userid] => stdclass{->id ->lastname ->firstname}
614      * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname}
615      */
616     public function get_grouped($users) {
617         global $DB;
618         global $CFG;
620         $grouped = array();  // grouped users to be returned
621         if (empty($users)) {
622             return $grouped;
623         }
624         if ($this->cm->groupingid) {
625             // Group workshop set to specified grouping - only consider groups
626             // within this grouping, and leave out users who aren't members of
627             // this grouping.
628             $groupingid = $this->cm->groupingid;
629             // All users that are members of at least one group will be
630             // added into a virtual group id 0
631             $grouped[0] = array();
632         } else {
633             $groupingid = 0;
634             // there is no need to be member of a group so $grouped[0] will contain
635             // all users
636             $grouped[0] = $users;
637         }
638         $gmemberships = groups_get_all_groups($this->cm->course, array_keys($users), $groupingid,
639                             'gm.id,gm.groupid,gm.userid');
640         foreach ($gmemberships as $gmembership) {
641             if (!isset($grouped[$gmembership->groupid])) {
642                 $grouped[$gmembership->groupid] = array();
643             }
644             $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid];
645             $grouped[0][$gmembership->userid] = $users[$gmembership->userid];
646         }
647         return $grouped;
648     }
650     /**
651      * Returns the list of all allocations (i.e. assigned assessments) in the workshop
652      *
653      * Assessments of example submissions are ignored
654      *
655      * @return array
656      */
657     public function get_allocations() {
658         global $DB;
660         $sql = 'SELECT a.id, a.submissionid, a.reviewerid, s.authorid
661                   FROM {workshop_assessments} a
662             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
663                  WHERE s.example = 0 AND s.workshopid = :workshopid';
664         $params = array('workshopid' => $this->id);
666         return $DB->get_records_sql($sql, $params);
667     }
669     /**
670      * Returns the total number of records that would be returned by {@link self::get_submissions()}
671      *
672      * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
673      * @param int $groupid If non-zero, return only submissions by authors in the specified group
674      * @return int number of records
675      */
676     public function count_submissions($authorid='all', $groupid=0) {
677         global $DB;
679         $params = array('workshopid' => $this->id);
680         $sql = "SELECT COUNT(s.id)
681                   FROM {workshop_submissions} s
682                   JOIN {user} u ON (s.authorid = u.id)";
683         if ($groupid) {
684             $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
685             $params['groupid'] = $groupid;
686         }
687         $sql .= " WHERE s.example = 0 AND s.workshopid = :workshopid";
689         if ('all' === $authorid) {
690             // no additional conditions
691         } elseif (!empty($authorid)) {
692             list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
693             $sql .= " AND authorid $usql";
694             $params = array_merge($params, $uparams);
695         } else {
696             // $authorid is empty
697             return 0;
698         }
700         return $DB->count_records_sql($sql, $params);
701     }
704     /**
705      * Returns submissions from this workshop
706      *
707      * Fetches data from {workshop_submissions} and adds some useful information from other
708      * tables. Does not return textual fields to prevent possible memory lack issues.
709      *
710      * @see self::count_submissions()
711      * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
712      * @param int $groupid If non-zero, return only submissions by authors in the specified group
713      * @param int $limitfrom Return a subset of records, starting at this point (optional)
714      * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
715      * @return array of records or an empty array
716      */
717     public function get_submissions($authorid='all', $groupid=0, $limitfrom=0, $limitnum=0) {
718         global $DB;
720         $authorfields      = user_picture::fields('u', null, 'authoridx', 'author');
721         $gradeoverbyfields = user_picture::fields('t', null, 'gradeoverbyx', 'over');
722         $params            = array('workshopid' => $this->id);
723         $sql = "SELECT s.id, s.workshopid, s.example, s.authorid, s.timecreated, s.timemodified,
724                        s.title, s.grade, s.gradeover, s.gradeoverby, s.published,
725                        $authorfields, $gradeoverbyfields
726                   FROM {workshop_submissions} s
727                   JOIN {user} u ON (s.authorid = u.id)";
728         if ($groupid) {
729             $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
730             $params['groupid'] = $groupid;
731         }
732         $sql .= " LEFT JOIN {user} t ON (s.gradeoverby = t.id)
733                  WHERE s.example = 0 AND s.workshopid = :workshopid";
735         if ('all' === $authorid) {
736             // no additional conditions
737         } elseif (!empty($authorid)) {
738             list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
739             $sql .= " AND authorid $usql";
740             $params = array_merge($params, $uparams);
741         } else {
742             // $authorid is empty
743             return array();
744         }
745         list($sort, $sortparams) = users_order_by_sql('u');
746         $sql .= " ORDER BY $sort";
748         return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
749     }
751     /**
752      * Returns a submission record with the author's data
753      *
754      * @param int $id submission id
755      * @return stdclass
756      */
757     public function get_submission_by_id($id) {
758         global $DB;
760         // we intentionally check the workshopid here, too, so the workshop can't touch submissions
761         // from other instances
762         $authorfields      = user_picture::fields('u', null, 'authoridx', 'author');
763         $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
764         $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
765                   FROM {workshop_submissions} s
766             INNER JOIN {user} u ON (s.authorid = u.id)
767              LEFT JOIN {user} g ON (s.gradeoverby = g.id)
768                  WHERE s.example = 0 AND s.workshopid = :workshopid AND s.id = :id";
769         $params = array('workshopid' => $this->id, 'id' => $id);
770         return $DB->get_record_sql($sql, $params, MUST_EXIST);
771     }
773     /**
774      * Returns a submission submitted by the given author
775      *
776      * @param int $id author id
777      * @return stdclass|false
778      */
779     public function get_submission_by_author($authorid) {
780         global $DB;
782         if (empty($authorid)) {
783             return false;
784         }
785         $authorfields      = user_picture::fields('u', null, 'authoridx', 'author');
786         $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
787         $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
788                   FROM {workshop_submissions} s
789             INNER JOIN {user} u ON (s.authorid = u.id)
790              LEFT JOIN {user} g ON (s.gradeoverby = g.id)
791                  WHERE s.example = 0 AND s.workshopid = :workshopid AND s.authorid = :authorid";
792         $params = array('workshopid' => $this->id, 'authorid' => $authorid);
793         return $DB->get_record_sql($sql, $params);
794     }
796     /**
797      * Returns published submissions with their authors data
798      *
799      * @return array of stdclass
800      */
801     public function get_published_submissions($orderby='finalgrade DESC') {
802         global $DB;
804         $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
805         $sql = "SELECT s.id, s.authorid, s.timecreated, s.timemodified,
806                        s.title, s.grade, s.gradeover, COALESCE(s.gradeover,s.grade) AS finalgrade,
807                        $authorfields
808                   FROM {workshop_submissions} s
809             INNER JOIN {user} u ON (s.authorid = u.id)
810                  WHERE s.example = 0 AND s.workshopid = :workshopid AND s.published = 1
811               ORDER BY $orderby";
812         $params = array('workshopid' => $this->id);
813         return $DB->get_records_sql($sql, $params);
814     }
816     /**
817      * Returns full record of the given example submission
818      *
819      * @param int $id example submission od
820      * @return object
821      */
822     public function get_example_by_id($id) {
823         global $DB;
824         return $DB->get_record('workshop_submissions',
825                 array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST);
826     }
828     /**
829      * Returns the list of example submissions in this workshop with reference assessments attached
830      *
831      * @return array of objects or an empty array
832      * @see workshop::prepare_example_summary()
833      */
834     public function get_examples_for_manager() {
835         global $DB;
837         $sql = 'SELECT s.id, s.title,
838                        a.id AS assessmentid, a.grade, a.gradinggrade
839                   FROM {workshop_submissions} s
840              LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.weight = 1)
841                  WHERE s.example = 1 AND s.workshopid = :workshopid
842               ORDER BY s.title';
843         return $DB->get_records_sql($sql, array('workshopid' => $this->id));
844     }
846     /**
847      * Returns the list of all example submissions in this workshop with the information of assessments done by the given user
848      *
849      * @param int $reviewerid user id
850      * @return array of objects, indexed by example submission id
851      * @see workshop::prepare_example_summary()
852      */
853     public function get_examples_for_reviewer($reviewerid) {
854         global $DB;
856         if (empty($reviewerid)) {
857             return false;
858         }
859         $sql = 'SELECT s.id, s.title,
860                        a.id AS assessmentid, a.grade, a.gradinggrade
861                   FROM {workshop_submissions} s
862              LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.reviewerid = :reviewerid AND a.weight = 0)
863                  WHERE s.example = 1 AND s.workshopid = :workshopid
864               ORDER BY s.title';
865         return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid));
866     }
868     /**
869      * Prepares renderable submission component
870      *
871      * @param stdClass $record required by {@see workshop_submission}
872      * @param bool $showauthor show the author-related information
873      * @return workshop_submission
874      */
875     public function prepare_submission(stdClass $record, $showauthor = false) {
877         $submission         = new workshop_submission($this, $record, $showauthor);
878         $submission->url    = $this->submission_url($record->id);
880         return $submission;
881     }
883     /**
884      * Prepares renderable submission summary component
885      *
886      * @param stdClass $record required by {@see workshop_submission_summary}
887      * @param bool $showauthor show the author-related information
888      * @return workshop_submission_summary
889      */
890     public function prepare_submission_summary(stdClass $record, $showauthor = false) {
892         $summary        = new workshop_submission_summary($this, $record, $showauthor);
893         $summary->url   = $this->submission_url($record->id);
895         return $summary;
896     }
898     /**
899      * Prepares renderable example submission component
900      *
901      * @param stdClass $record required by {@see workshop_example_submission}
902      * @return workshop_example_submission
903      */
904     public function prepare_example_submission(stdClass $record) {
906         $example = new workshop_example_submission($this, $record);
908         return $example;
909     }
911     /**
912      * Prepares renderable example submission summary component
913      *
914      * If the example is editable, the caller must set the 'editable' flag explicitly.
915      *
916      * @param stdClass $example as returned by {@link workshop::get_examples_for_manager()} or {@link workshop::get_examples_for_reviewer()}
917      * @return workshop_example_submission_summary to be rendered
918      */
919     public function prepare_example_summary(stdClass $example) {
921         $summary = new workshop_example_submission_summary($this, $example);
923         if (is_null($example->grade)) {
924             $summary->status = 'notgraded';
925             $summary->assesslabel = get_string('assess', 'workshop');
926         } else {
927             $summary->status = 'graded';
928             $summary->assesslabel = get_string('reassess', 'workshop');
929         }
931         $summary->gradeinfo           = new stdclass();
932         $summary->gradeinfo->received = $this->real_grade($example->grade);
933         $summary->gradeinfo->max      = $this->real_grade(100);
935         $summary->url       = new moodle_url($this->exsubmission_url($example->id));
936         $summary->editurl   = new moodle_url($this->exsubmission_url($example->id), array('edit' => 'on'));
937         $summary->assessurl = new moodle_url($this->exsubmission_url($example->id), array('assess' => 'on', 'sesskey' => sesskey()));
939         return $summary;
940     }
942     /**
943      * Prepares renderable assessment component
944      *
945      * The $options array supports the following keys:
946      * showauthor - should the author user info be available for the renderer
947      * showreviewer - should the reviewer user info be available for the renderer
948      * showform - show the assessment form if it is available
949      * showweight - should the assessment weight be available for the renderer
950      *
951      * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
952      * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
953      * @param array $options
954      * @return workshop_assessment
955      */
956     public function prepare_assessment(stdClass $record, $form, array $options = array()) {
958         $assessment             = new workshop_assessment($this, $record, $options);
959         $assessment->url        = $this->assess_url($record->id);
960         $assessment->maxgrade   = $this->real_grade(100);
962         if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
963             debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
964         }
966         if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
967             $assessment->form = $form;
968         }
970         if (empty($options['showweight'])) {
971             $assessment->weight = null;
972         }
974         if (!is_null($record->grade)) {
975             $assessment->realgrade = $this->real_grade($record->grade);
976         }
978         return $assessment;
979     }
981     /**
982      * Prepares renderable example submission's assessment component
983      *
984      * The $options array supports the following keys:
985      * showauthor - should the author user info be available for the renderer
986      * showreviewer - should the reviewer user info be available for the renderer
987      * showform - show the assessment form if it is available
988      *
989      * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
990      * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
991      * @param array $options
992      * @return workshop_example_assessment
993      */
994     public function prepare_example_assessment(stdClass $record, $form = null, array $options = array()) {
996         $assessment             = new workshop_example_assessment($this, $record, $options);
997         $assessment->url        = $this->exassess_url($record->id);
998         $assessment->maxgrade   = $this->real_grade(100);
1000         if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1001             debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1002         }
1004         if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1005             $assessment->form = $form;
1006         }
1008         if (!is_null($record->grade)) {
1009             $assessment->realgrade = $this->real_grade($record->grade);
1010         }
1012         $assessment->weight = null;
1014         return $assessment;
1015     }
1017     /**
1018      * Prepares renderable example submission's reference assessment component
1019      *
1020      * The $options array supports the following keys:
1021      * showauthor - should the author user info be available for the renderer
1022      * showreviewer - should the reviewer user info be available for the renderer
1023      * showform - show the assessment form if it is available
1024      *
1025      * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1026      * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1027      * @param array $options
1028      * @return workshop_example_reference_assessment
1029      */
1030     public function prepare_example_reference_assessment(stdClass $record, $form = null, array $options = array()) {
1032         $assessment             = new workshop_example_reference_assessment($this, $record, $options);
1033         $assessment->maxgrade   = $this->real_grade(100);
1035         if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1036             debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1037         }
1039         if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1040             $assessment->form = $form;
1041         }
1043         if (!is_null($record->grade)) {
1044             $assessment->realgrade = $this->real_grade($record->grade);
1045         }
1047         $assessment->weight = null;
1049         return $assessment;
1050     }
1052     /**
1053      * Removes the submission and all relevant data
1054      *
1055      * @param stdClass $submission record to delete
1056      * @return void
1057      */
1058     public function delete_submission(stdclass $submission) {
1059         global $DB;
1060         $assessments = $DB->get_records('workshop_assessments', array('submissionid' => $submission->id), '', 'id');
1061         $this->delete_assessment(array_keys($assessments));
1063         $fs = get_file_storage();
1064         $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_content', $submission->id);
1065         $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
1067         $DB->delete_records('workshop_submissions', array('id' => $submission->id));
1068     }
1070     /**
1071      * Returns the list of all assessments in the workshop with some data added
1072      *
1073      * Fetches data from {workshop_assessments} and adds some useful information from other
1074      * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory
1075      * lack issues.
1076      *
1077      * @return array [assessmentid] => assessment stdclass
1078      */
1079     public function get_all_assessments() {
1080         global $DB;
1082         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1083         $authorfields   = user_picture::fields('author', null, 'authorid', 'author');
1084         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1085         list($sort, $params) = users_order_by_sql('reviewer');
1086         $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified,
1087                        a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby,
1088                        $reviewerfields, $authorfields, $overbyfields,
1089                        s.title
1090                   FROM {workshop_assessments} a
1091             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1092             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1093             INNER JOIN {user} author ON (s.authorid = author.id)
1094              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1095                  WHERE s.workshopid = :workshopid AND s.example = 0
1096               ORDER BY $sort";
1097         $params['workshopid'] = $this->id;
1099         return $DB->get_records_sql($sql, $params);
1100     }
1102     /**
1103      * Get the complete information about the given assessment
1104      *
1105      * @param int $id Assessment ID
1106      * @return stdclass
1107      */
1108     public function get_assessment_by_id($id) {
1109         global $DB;
1111         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1112         $authorfields   = user_picture::fields('author', null, 'authorid', 'author');
1113         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1114         $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1115                   FROM {workshop_assessments} a
1116             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1117             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1118             INNER JOIN {user} author ON (s.authorid = author.id)
1119              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1120                  WHERE a.id = :id AND s.workshopid = :workshopid";
1121         $params = array('id' => $id, 'workshopid' => $this->id);
1123         return $DB->get_record_sql($sql, $params, MUST_EXIST);
1124     }
1126     /**
1127      * Get the complete information about the user's assessment of the given submission
1128      *
1129      * @param int $sid submission ID
1130      * @param int $uid user ID of the reviewer
1131      * @return false|stdclass false if not found, stdclass otherwise
1132      */
1133     public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
1134         global $DB;
1136         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1137         $authorfields   = user_picture::fields('author', null, 'authorid', 'author');
1138         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1139         $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1140                   FROM {workshop_assessments} a
1141             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1142             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1143             INNER JOIN {user} author ON (s.authorid = author.id)
1144              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1145                  WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid";
1146         $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id);
1148         return $DB->get_record_sql($sql, $params, IGNORE_MISSING);
1149     }
1151     /**
1152      * Get the complete information about all assessments of the given submission
1153      *
1154      * @param int $submissionid
1155      * @return array
1156      */
1157     public function get_assessments_of_submission($submissionid) {
1158         global $DB;
1160         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1161         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1162         list($sort, $params) = users_order_by_sql('reviewer');
1163         $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields
1164                   FROM {workshop_assessments} a
1165             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1166             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1167              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1168                  WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid
1169               ORDER BY $sort";
1170         $params['submissionid'] = $submissionid;
1171         $params['workshopid']   = $this->id;
1173         return $DB->get_records_sql($sql, $params);
1174     }
1176     /**
1177      * Get the complete information about all assessments allocated to the given reviewer
1178      *
1179      * @param int $reviewerid
1180      * @return array
1181      */
1182     public function get_assessments_by_reviewer($reviewerid) {
1183         global $DB;
1185         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1186         $authorfields   = user_picture::fields('author', null, 'authorid', 'author');
1187         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1188         $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields,
1189                        s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated,
1190                        s.timemodified AS submissionmodified
1191                   FROM {workshop_assessments} a
1192             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1193             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1194             INNER JOIN {user} author ON (s.authorid = author.id)
1195              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1196                  WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid";
1197         $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id);
1199         return $DB->get_records_sql($sql, $params);
1200     }
1202     /**
1203      * Get allocated assessments not graded yet by the given reviewer
1204      *
1205      * @see self::get_assessments_by_reviewer()
1206      * @param int $reviewerid the reviewer id
1207      * @param null|int|array $exclude optional assessment id (or list of them) to be excluded
1208      * @return array
1209      */
1210     public function get_pending_assessments_by_reviewer($reviewerid, $exclude = null) {
1212         $assessments = $this->get_assessments_by_reviewer($reviewerid);
1214         foreach ($assessments as $id => $assessment) {
1215             if (!is_null($assessment->grade)) {
1216                 unset($assessments[$id]);
1217                 continue;
1218             }
1219             if (!empty($exclude)) {
1220                 if (is_array($exclude) and in_array($id, $exclude)) {
1221                     unset($assessments[$id]);
1222                     continue;
1223                 } else if ($id == $exclude) {
1224                     unset($assessments[$id]);
1225                     continue;
1226                 }
1227             }
1228         }
1230         return $assessments;
1231     }
1233     /**
1234      * Allocate a submission to a user for review
1235      *
1236      * @param stdClass $submission Submission object with at least id property
1237      * @param int $reviewerid User ID
1238      * @param int $weight of the new assessment, from 0 to 16
1239      * @param bool $bulk repeated inserts into DB expected
1240      * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists
1241      */
1242     public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
1243         global $DB;
1245         if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
1246             return self::ALLOCATION_EXISTS;
1247         }
1249         $weight = (int)$weight;
1250         if ($weight < 0) {
1251             $weight = 0;
1252         }
1253         if ($weight > 16) {
1254             $weight = 16;
1255         }
1257         $now = time();
1258         $assessment = new stdclass();
1259         $assessment->submissionid           = $submission->id;
1260         $assessment->reviewerid             = $reviewerid;
1261         $assessment->timecreated            = $now;         // do not set timemodified here
1262         $assessment->weight                 = $weight;
1263         $assessment->feedbackauthorformat   = editors_get_preferred_format();
1264         $assessment->feedbackreviewerformat = editors_get_preferred_format();
1266         return $DB->insert_record('workshop_assessments', $assessment, true, $bulk);
1267     }
1269     /**
1270      * Delete assessment record or records.
1271      *
1272      * Removes associated records from the workshop_grades table, too.
1273      *
1274      * @param int|array $id assessment id or array of assessments ids
1275      * @todo Give grading strategy plugins a chance to clean up their data, too.
1276      * @return bool true
1277      */
1278     public function delete_assessment($id) {
1279         global $DB;
1281         if (empty($id)) {
1282             return true;
1283         }
1285         $fs = get_file_storage();
1287         if (is_array($id)) {
1288             $DB->delete_records_list('workshop_grades', 'assessmentid', $id);
1289             foreach ($id as $itemid) {
1290                 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $itemid);
1291                 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $itemid);
1292             }
1293             $DB->delete_records_list('workshop_assessments', 'id', $id);
1295         } else {
1296             $DB->delete_records('workshop_grades', array('assessmentid' => $id));
1297             $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $id);
1298             $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $id);
1299             $DB->delete_records('workshop_assessments', array('id' => $id));
1300         }
1302         return true;
1303     }
1305     /**
1306      * Returns instance of grading strategy class
1307      *
1308      * @return stdclass Instance of a grading strategy
1309      */
1310     public function grading_strategy_instance() {
1311         global $CFG;    // because we require other libs here
1313         if (is_null($this->strategyinstance)) {
1314             $strategylib = dirname(__FILE__) . '/form/' . $this->strategy . '/lib.php';
1315             if (is_readable($strategylib)) {
1316                 require_once($strategylib);
1317             } else {
1318                 throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
1319             }
1320             $classname = 'workshop_' . $this->strategy . '_strategy';
1321             $this->strategyinstance = new $classname($this);
1322             if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) {
1323                 throw new coding_exception($classname . ' does not implement workshop_strategy interface');
1324             }
1325         }
1326         return $this->strategyinstance;
1327     }
1329     /**
1330      * Sets the current evaluation method to the given plugin.
1331      *
1332      * @param string $method the name of the workshopeval subplugin
1333      * @return bool true if successfully set
1334      * @throws coding_exception if attempting to set a non-installed evaluation method
1335      */
1336     public function set_grading_evaluation_method($method) {
1337         global $DB;
1339         $evaluationlib = dirname(__FILE__) . '/eval/' . $method . '/lib.php';
1341         if (is_readable($evaluationlib)) {
1342             $this->evaluationinstance = null;
1343             $this->evaluation = $method;
1344             $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id));
1345             return true;
1346         }
1348         throw new coding_exception('Attempt to set a non-existing evaluation method.');
1349     }
1351     /**
1352      * Returns instance of grading evaluation class
1353      *
1354      * @return stdclass Instance of a grading evaluation
1355      */
1356     public function grading_evaluation_instance() {
1357         global $CFG;    // because we require other libs here
1359         if (is_null($this->evaluationinstance)) {
1360             if (empty($this->evaluation)) {
1361                 $this->evaluation = 'best';
1362             }
1363             $evaluationlib = dirname(__FILE__) . '/eval/' . $this->evaluation . '/lib.php';
1364             if (is_readable($evaluationlib)) {
1365                 require_once($evaluationlib);
1366             } else {
1367                 // Fall back in case the subplugin is not available.
1368                 $this->evaluation = 'best';
1369                 $evaluationlib = dirname(__FILE__) . '/eval/' . $this->evaluation . '/lib.php';
1370                 if (is_readable($evaluationlib)) {
1371                     require_once($evaluationlib);
1372                 } else {
1373                     // Fall back in case the subplugin is not available any more.
1374                     throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
1375                 }
1376             }
1377             $classname = 'workshop_' . $this->evaluation . '_evaluation';
1378             $this->evaluationinstance = new $classname($this);
1379             if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) {
1380                 throw new coding_exception($classname . ' does not extend workshop_evaluation class');
1381             }
1382         }
1383         return $this->evaluationinstance;
1384     }
1386     /**
1387      * Returns instance of submissions allocator
1388      *
1389      * @param string $method The name of the allocation method, must be PARAM_ALPHA
1390      * @return stdclass Instance of submissions allocator
1391      */
1392     public function allocator_instance($method) {
1393         global $CFG;    // because we require other libs here
1395         $allocationlib = dirname(__FILE__) . '/allocation/' . $method . '/lib.php';
1396         if (is_readable($allocationlib)) {
1397             require_once($allocationlib);
1398         } else {
1399             throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
1400         }
1401         $classname = 'workshop_' . $method . '_allocator';
1402         return new $classname($this);
1403     }
1405     /**
1406      * @return moodle_url of this workshop's view page
1407      */
1408     public function view_url() {
1409         global $CFG;
1410         return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
1411     }
1413     /**
1414      * @return moodle_url of the page for editing this workshop's grading form
1415      */
1416     public function editform_url() {
1417         global $CFG;
1418         return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
1419     }
1421     /**
1422      * @return moodle_url of the page for previewing this workshop's grading form
1423      */
1424     public function previewform_url() {
1425         global $CFG;
1426         return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
1427     }
1429     /**
1430      * @param int $assessmentid The ID of assessment record
1431      * @return moodle_url of the assessment page
1432      */
1433     public function assess_url($assessmentid) {
1434         global $CFG;
1435         $assessmentid = clean_param($assessmentid, PARAM_INT);
1436         return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
1437     }
1439     /**
1440      * @param int $assessmentid The ID of assessment record
1441      * @return moodle_url of the example assessment page
1442      */
1443     public function exassess_url($assessmentid) {
1444         global $CFG;
1445         $assessmentid = clean_param($assessmentid, PARAM_INT);
1446         return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
1447     }
1449     /**
1450      * @return moodle_url of the page to view a submission, defaults to the own one
1451      */
1452     public function submission_url($id=null) {
1453         global $CFG;
1454         return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
1455     }
1457     /**
1458      * @param int $id example submission id
1459      * @return moodle_url of the page to view an example submission
1460      */
1461     public function exsubmission_url($id) {
1462         global $CFG;
1463         return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
1464     }
1466     /**
1467      * @param int $sid submission id
1468      * @param array $aid of int assessment ids
1469      * @return moodle_url of the page to compare assessments of the given submission
1470      */
1471     public function compare_url($sid, array $aids) {
1472         global $CFG;
1474         $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
1475         $i = 0;
1476         foreach ($aids as $aid) {
1477             $url->param("aid{$i}", $aid);
1478             $i++;
1479         }
1480         return $url;
1481     }
1483     /**
1484      * @param int $sid submission id
1485      * @param int $aid assessment id
1486      * @return moodle_url of the page to compare the reference assessments of the given example submission
1487      */
1488     public function excompare_url($sid, $aid) {
1489         global $CFG;
1490         return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
1491     }
1493     /**
1494      * @return moodle_url of the mod_edit form
1495      */
1496     public function updatemod_url() {
1497         global $CFG;
1498         return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
1499     }
1501     /**
1502      * @param string $method allocation method
1503      * @return moodle_url to the allocation page
1504      */
1505     public function allocation_url($method=null) {
1506         global $CFG;
1507         $params = array('cmid' => $this->cm->id);
1508         if (!empty($method)) {
1509             $params['method'] = $method;
1510         }
1511         return new moodle_url('/mod/workshop/allocation.php', $params);
1512     }
1514     /**
1515      * @param int $phasecode The internal phase code
1516      * @return moodle_url of the script to change the current phase to $phasecode
1517      */
1518     public function switchphase_url($phasecode) {
1519         global $CFG;
1520         $phasecode = clean_param($phasecode, PARAM_INT);
1521         return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
1522     }
1524     /**
1525      * @return moodle_url to the aggregation page
1526      */
1527     public function aggregate_url() {
1528         global $CFG;
1529         return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
1530     }
1532     /**
1533      * @return moodle_url of this workshop's toolbox page
1534      */
1535     public function toolbox_url($tool) {
1536         global $CFG;
1537         return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
1538     }
1540     /**
1541      * Workshop wrapper around {@see add_to_log()}
1542      * @deprecated since 2.7 Please use the provided event classes for logging actions.
1543      *
1544      * @param string $action to be logged
1545      * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends
1546      * @param mixed $info additional info, usually id in a table
1547      * @param bool $return true to return the arguments for add_to_log.
1548      * @return void|array array of arguments for add_to_log if $return is true
1549      */
1550     public function log($action, moodle_url $url = null, $info = null, $return = false) {
1551         debugging('The log method is now deprecated, please use event classes instead', DEBUG_DEVELOPER);
1553         if (is_null($url)) {
1554             $url = $this->view_url();
1555         }
1557         if (is_null($info)) {
1558             $info = $this->id;
1559         }
1561         $logurl = $this->log_convert_url($url);
1562         $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
1563         if ($return) {
1564             return $args;
1565         }
1566         call_user_func_array('add_to_log', $args);
1567     }
1569     /**
1570      * Is the given user allowed to create their submission?
1571      *
1572      * @param int $userid
1573      * @return bool
1574      */
1575     public function creating_submission_allowed($userid) {
1577         $now = time();
1578         $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1580         if ($this->latesubmissions) {
1581             if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) {
1582                 // late submissions are allowed in the submission and assessment phase only
1583                 return false;
1584             }
1585             if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1586                 // late submissions are not allowed before the submission start
1587                 return false;
1588             }
1589             return true;
1591         } else {
1592             if ($this->phase != self::PHASE_SUBMISSION) {
1593                 // submissions are allowed during the submission phase only
1594                 return false;
1595             }
1596             if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1597                 // if enabled, submitting is not allowed before the date/time defined in the mod_form
1598                 return false;
1599             }
1600             if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) {
1601                 // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed
1602                 return false;
1603             }
1604             return true;
1605         }
1606     }
1608     /**
1609      * Is the given user allowed to modify their existing submission?
1610      *
1611      * @param int $userid
1612      * @return bool
1613      */
1614     public function modifying_submission_allowed($userid) {
1616         $now = time();
1617         $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1619         if ($this->phase != self::PHASE_SUBMISSION) {
1620             // submissions can be edited during the submission phase only
1621             return false;
1622         }
1623         if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1624             // if enabled, re-submitting is not allowed before the date/time defined in the mod_form
1625             return false;
1626         }
1627         if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) {
1628             // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed
1629             return false;
1630         }
1631         return true;
1632     }
1634     /**
1635      * Is the given reviewer allowed to create/edit their assessments?
1636      *
1637      * @param int $userid
1638      * @return bool
1639      */
1640     public function assessing_allowed($userid) {
1642         if ($this->phase != self::PHASE_ASSESSMENT) {
1643             // assessing is allowed in the assessment phase only, unless the user is a teacher
1644             // providing additional assessment during the evaluation phase
1645             if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) {
1646                 return false;
1647             }
1648         }
1650         $now = time();
1651         $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1653         if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) {
1654             // if enabled, assessing is not allowed before the date/time defined in the mod_form
1655             return false;
1656         }
1657         if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) {
1658             // if enabled, assessing is not allowed after the date/time defined in the mod_form
1659             return false;
1660         }
1661         // here we go, assessing is allowed
1662         return true;
1663     }
1665     /**
1666      * Are reviewers allowed to create/edit their assessments of the example submissions?
1667      *
1668      * Returns null if example submissions are not enabled in this workshop. Otherwise returns
1669      * true or false. Note this does not check other conditions like the number of already
1670      * assessed examples, examples mode etc.
1671      *
1672      * @return null|bool
1673      */
1674     public function assessing_examples_allowed() {
1675         if (empty($this->useexamples)) {
1676             return null;
1677         }
1678         if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
1679             return true;
1680         }
1681         if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
1682             return true;
1683         }
1684         if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
1685             return true;
1686         }
1687         return false;
1688     }
1690     /**
1691      * Are the peer-reviews available to the authors?
1692      *
1693      * @return bool
1694      */
1695     public function assessments_available() {
1696         return $this->phase == self::PHASE_CLOSED;
1697     }
1699     /**
1700      * Switch to a new workshop phase
1701      *
1702      * Modifies the underlying database record. You should terminate the script shortly after calling this.
1703      *
1704      * @param int $newphase new phase code
1705      * @return bool true if success, false otherwise
1706      */
1707     public function switch_phase($newphase) {
1708         global $DB;
1710         $known = $this->available_phases_list();
1711         if (!isset($known[$newphase])) {
1712             return false;
1713         }
1715         if (self::PHASE_CLOSED == $newphase) {
1716             // push the grades into the gradebook
1717             $workshop = new stdclass();
1718             foreach ($this as $property => $value) {
1719                 $workshop->{$property} = $value;
1720             }
1721             $workshop->course     = $this->course->id;
1722             $workshop->cmidnumber = $this->cm->id;
1723             $workshop->modname    = 'workshop';
1724             workshop_update_grades($workshop);
1725         }
1727         $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
1728         $this->phase = $newphase;
1729         $eventdata = array(
1730             'objectid' => $this->id,
1731             'context' => $this->context,
1732             'other' => array(
1733                 'workshopphase' => $this->phase
1734             )
1735         );
1736         $event = \mod_workshop\event\phase_switched::create($eventdata);
1737         $event->trigger();
1738         return true;
1739     }
1741     /**
1742      * Saves a raw grade for submission as calculated from the assessment form fields
1743      *
1744      * @param array $assessmentid assessment record id, must exists
1745      * @param mixed $grade        raw percentual grade from 0.00000 to 100.00000
1746      * @return false|float        the saved grade
1747      */
1748     public function set_peer_grade($assessmentid, $grade) {
1749         global $DB;
1751         if (is_null($grade)) {
1752             return false;
1753         }
1754         $data = new stdclass();
1755         $data->id = $assessmentid;
1756         $data->grade = $grade;
1757         $data->timemodified = time();
1758         $DB->update_record('workshop_assessments', $data);
1759         return $grade;
1760     }
1762     /**
1763      * Prepares data object with all workshop grades to be rendered
1764      *
1765      * @param int $userid the user we are preparing the report for
1766      * @param int $groupid if non-zero, prepare the report for the given group only
1767      * @param int $page the current page (for the pagination)
1768      * @param int $perpage participants per page (for the pagination)
1769      * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
1770      * @param string $sorthow ASC|DESC
1771      * @return stdclass data for the renderer
1772      */
1773     public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
1774         global $DB;
1776         $canviewall     = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
1777         $isparticipant  = $this->is_participant($userid);
1779         if (!$canviewall and !$isparticipant) {
1780             // who the hell is this?
1781             return array();
1782         }
1784         if (!in_array($sortby, array('lastname','firstname','submissiontitle','submissiongrade','gradinggrade'))) {
1785             $sortby = 'lastname';
1786         }
1788         if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
1789             $sorthow = 'ASC';
1790         }
1792         // get the list of user ids to be displayed
1793         if ($canviewall) {
1794             $participants = $this->get_participants(false, $groupid);
1795         } else {
1796             // this is an ordinary workshop participant (aka student) - display the report just for him/her
1797             $participants = array($userid => (object)array('id' => $userid));
1798         }
1800         // we will need to know the number of all records later for the pagination purposes
1801         $numofparticipants = count($participants);
1803         if ($numofparticipants > 0) {
1804             // load all fields which can be used for sorting and paginate the records
1805             list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1806             $params['workshopid1'] = $this->id;
1807             $params['workshopid2'] = $this->id;
1808             $sqlsort = array();
1809             $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
1810             foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
1811                 $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
1812             }
1813             $sqlsort = implode(',', $sqlsort);
1814             $picturefields = user_picture::fields('u', array(), 'userid');
1815             $sql = "SELECT $picturefields, s.title AS submissiontitle, s.grade AS submissiongrade, ag.gradinggrade
1816                       FROM {user} u
1817                  LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)
1818                  LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)
1819                      WHERE u.id $participantids
1820                   ORDER BY $sqlsort";
1821             $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1822         } else {
1823             $participants = array();
1824         }
1826         // this will hold the information needed to display user names and pictures
1827         $userinfo = array();
1829         // get the user details for all participants to display
1830         $additionalnames = get_all_user_name_fields();
1831         foreach ($participants as $participant) {
1832             if (!isset($userinfo[$participant->userid])) {
1833                 $userinfo[$participant->userid]            = new stdclass();
1834                 $userinfo[$participant->userid]->id        = $participant->userid;
1835                 $userinfo[$participant->userid]->picture   = $participant->picture;
1836                 $userinfo[$participant->userid]->imagealt  = $participant->imagealt;
1837                 $userinfo[$participant->userid]->email     = $participant->email;
1838                 foreach ($additionalnames as $addname) {
1839                     $userinfo[$participant->userid]->$addname = $participant->$addname;
1840                 }
1841             }
1842         }
1844         // load the submissions details
1845         $submissions = $this->get_submissions(array_keys($participants));
1847         // get the user details for all moderators (teachers) that have overridden a submission grade
1848         foreach ($submissions as $submission) {
1849             if (!isset($userinfo[$submission->gradeoverby])) {
1850                 $userinfo[$submission->gradeoverby]            = new stdclass();
1851                 $userinfo[$submission->gradeoverby]->id        = $submission->gradeoverby;
1852                 $userinfo[$submission->gradeoverby]->picture   = $submission->overpicture;
1853                 $userinfo[$submission->gradeoverby]->imagealt  = $submission->overimagealt;
1854                 $userinfo[$submission->gradeoverby]->email     = $submission->overemail;
1855                 foreach ($additionalnames as $addname) {
1856                     $temp = 'over' . $addname;
1857                     $userinfo[$submission->gradeoverby]->$addname = $submission->$temp;
1858                 }
1859             }
1860         }
1862         // get the user details for all reviewers of the displayed participants
1863         $reviewers = array();
1865         if ($submissions) {
1866             list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
1867             list($sort, $sortparams) = users_order_by_sql('r');
1868             $picturefields = user_picture::fields('r', array(), 'reviewerid');
1869             $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,
1870                            $picturefields, s.id AS submissionid, s.authorid
1871                       FROM {workshop_assessments} a
1872                       JOIN {user} r ON (a.reviewerid = r.id)
1873                       JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1874                      WHERE a.submissionid $submissionids
1875                   ORDER BY a.weight DESC, $sort";
1876             $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
1877             foreach ($reviewers as $reviewer) {
1878                 if (!isset($userinfo[$reviewer->reviewerid])) {
1879                     $userinfo[$reviewer->reviewerid]            = new stdclass();
1880                     $userinfo[$reviewer->reviewerid]->id        = $reviewer->reviewerid;
1881                     $userinfo[$reviewer->reviewerid]->picture   = $reviewer->picture;
1882                     $userinfo[$reviewer->reviewerid]->imagealt  = $reviewer->imagealt;
1883                     $userinfo[$reviewer->reviewerid]->email     = $reviewer->email;
1884                     foreach ($additionalnames as $addname) {
1885                         $userinfo[$reviewer->reviewerid]->$addname = $reviewer->$addname;
1886                     }
1887                 }
1888             }
1889         }
1891         // get the user details for all reviewees of the displayed participants
1892         $reviewees = array();
1893         if ($participants) {
1894             list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1895             list($sort, $sortparams) = users_order_by_sql('e');
1896             $params['workshopid'] = $this->id;
1897             $picturefields = user_picture::fields('e', array(), 'authorid');
1898             $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,
1899                            s.id AS submissionid, $picturefields
1900                       FROM {user} u
1901                       JOIN {workshop_assessments} a ON (a.reviewerid = u.id)
1902                       JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1903                       JOIN {user} e ON (s.authorid = e.id)
1904                      WHERE u.id $participantids AND s.workshopid = :workshopid
1905                   ORDER BY a.weight DESC, $sort";
1906             $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
1907             foreach ($reviewees as $reviewee) {
1908                 if (!isset($userinfo[$reviewee->authorid])) {
1909                     $userinfo[$reviewee->authorid]            = new stdclass();
1910                     $userinfo[$reviewee->authorid]->id        = $reviewee->authorid;
1911                     $userinfo[$reviewee->authorid]->picture   = $reviewee->picture;
1912                     $userinfo[$reviewee->authorid]->imagealt  = $reviewee->imagealt;
1913                     $userinfo[$reviewee->authorid]->email     = $reviewee->email;
1914                     foreach ($additionalnames as $addname) {
1915                         $userinfo[$reviewee->authorid]->$addname = $reviewee->$addname;
1916                     }
1917                 }
1918             }
1919         }
1921         // finally populate the object to be rendered
1922         $grades = $participants;
1924         foreach ($participants as $participant) {
1925             // set up default (null) values
1926             $grades[$participant->userid]->submissionid = null;
1927             $grades[$participant->userid]->submissiontitle = null;
1928             $grades[$participant->userid]->submissiongrade = null;
1929             $grades[$participant->userid]->submissiongradeover = null;
1930             $grades[$participant->userid]->submissiongradeoverby = null;
1931             $grades[$participant->userid]->submissionpublished = null;
1932             $grades[$participant->userid]->reviewedby = array();
1933             $grades[$participant->userid]->reviewerof = array();
1934         }
1935         unset($participants);
1936         unset($participant);
1938         foreach ($submissions as $submission) {
1939             $grades[$submission->authorid]->submissionid = $submission->id;
1940             $grades[$submission->authorid]->submissiontitle = $submission->title;
1941             $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
1942             $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
1943             $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
1944             $grades[$submission->authorid]->submissionpublished = $submission->published;
1945         }
1946         unset($submissions);
1947         unset($submission);
1949         foreach($reviewers as $reviewer) {
1950             $info = new stdclass();
1951             $info->userid = $reviewer->reviewerid;
1952             $info->assessmentid = $reviewer->assessmentid;
1953             $info->submissionid = $reviewer->submissionid;
1954             $info->grade = $this->real_grade($reviewer->grade);
1955             $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
1956             $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
1957             $info->weight = $reviewer->weight;
1958             $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
1959         }
1960         unset($reviewers);
1961         unset($reviewer);
1963         foreach($reviewees as $reviewee) {
1964             $info = new stdclass();
1965             $info->userid = $reviewee->authorid;
1966             $info->assessmentid = $reviewee->assessmentid;
1967             $info->submissionid = $reviewee->submissionid;
1968             $info->grade = $this->real_grade($reviewee->grade);
1969             $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
1970             $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
1971             $info->weight = $reviewee->weight;
1972             $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
1973         }
1974         unset($reviewees);
1975         unset($reviewee);
1977         foreach ($grades as $grade) {
1978             $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
1979         }
1981         $data = new stdclass();
1982         $data->grades = $grades;
1983         $data->userinfo = $userinfo;
1984         $data->totalcount = $numofparticipants;
1985         $data->maxgrade = $this->real_grade(100);
1986         $data->maxgradinggrade = $this->real_grading_grade(100);
1987         return $data;
1988     }
1990     /**
1991      * Calculates the real value of a grade
1992      *
1993      * @param float $value percentual value from 0 to 100
1994      * @param float $max   the maximal grade
1995      * @return string
1996      */
1997     public function real_grade_value($value, $max) {
1998         $localized = true;
1999         if (is_null($value) or $value === '') {
2000             return null;
2001         } elseif ($max == 0) {
2002             return 0;
2003         } else {
2004             return format_float($max * $value / 100, $this->gradedecimals, $localized);
2005         }
2006     }
2008     /**
2009      * Calculates the raw (percentual) value from a real grade
2010      *
2011      * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save
2012      * this value in a raw percentual form into DB
2013      * @param float $value given grade
2014      * @param float $max   the maximal grade
2015      * @return float       suitable to be stored as numeric(10,5)
2016      */
2017     public function raw_grade_value($value, $max) {
2018         if (is_null($value) or $value === '') {
2019             return null;
2020         }
2021         if ($max == 0 or $value < 0) {
2022             return 0;
2023         }
2024         $p = $value / $max * 100;
2025         if ($p > 100) {
2026             return $max;
2027         }
2028         return grade_floatval($p);
2029     }
2031     /**
2032      * Calculates the real value of grade for submission
2033      *
2034      * @param float $value percentual value from 0 to 100
2035      * @return string
2036      */
2037     public function real_grade($value) {
2038         return $this->real_grade_value($value, $this->grade);
2039     }
2041     /**
2042      * Calculates the real value of grade for assessment
2043      *
2044      * @param float $value percentual value from 0 to 100
2045      * @return string
2046      */
2047     public function real_grading_grade($value) {
2048         return $this->real_grade_value($value, $this->gradinggrade);
2049     }
2051     /**
2052      * Sets the given grades and received grading grades to null
2053      *
2054      * This does not clear the information about how the peers filled the assessment forms, but
2055      * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess
2056      * the allocated submissions.
2057      *
2058      * @return void
2059      */
2060     public function clear_assessments() {
2061         global $DB;
2063         $submissions = $this->get_submissions();
2064         if (empty($submissions)) {
2065             // no money, no love
2066             return;
2067         }
2068         $submissions = array_keys($submissions);
2069         list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED);
2070         $sql = "submissionid $sql";
2071         $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params);
2072         $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params);
2073     }
2075     /**
2076      * Sets the grades for submission to null
2077      *
2078      * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2079      * @return void
2080      */
2081     public function clear_submission_grades($restrict=null) {
2082         global $DB;
2084         $sql = "workshopid = :workshopid AND example = 0";
2085         $params = array('workshopid' => $this->id);
2087         if (is_null($restrict)) {
2088             // update all users - no more conditions
2089         } elseif (!empty($restrict)) {
2090             list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2091             $sql .= " AND authorid $usql";
2092             $params = array_merge($params, $uparams);
2093         } else {
2094             throw new coding_exception('Empty value is not a valid parameter here');
2095         }
2097         $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
2098     }
2100     /**
2101      * Calculates grades for submission for the given participant(s) and updates it in the database
2102      *
2103      * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2104      * @return void
2105      */
2106     public function aggregate_submission_grades($restrict=null) {
2107         global $DB;
2109         // fetch a recordset with all assessments to process
2110         $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
2111                        a.weight, a.grade
2112                   FROM {workshop_submissions} s
2113              LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id)
2114                  WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2115         $params = array('workshopid' => $this->id);
2117         if (is_null($restrict)) {
2118             // update all users - no more conditions
2119         } elseif (!empty($restrict)) {
2120             list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2121             $sql .= " AND s.authorid $usql";
2122             $params = array_merge($params, $uparams);
2123         } else {
2124             throw new coding_exception('Empty value is not a valid parameter here');
2125         }
2127         $sql .= ' ORDER BY s.id'; // this is important for bulk processing
2129         $rs         = $DB->get_recordset_sql($sql, $params);
2130         $batch      = array();    // will contain a set of all assessments of a single submission
2131         $previous   = null;       // a previous record in the recordset
2133         foreach ($rs as $current) {
2134             if (is_null($previous)) {
2135                 // we are processing the very first record in the recordset
2136                 $previous   = $current;
2137             }
2138             if ($current->submissionid == $previous->submissionid) {
2139                 // we are still processing the current submission
2140                 $batch[] = $current;
2141             } else {
2142                 // process all the assessments of a sigle submission
2143                 $this->aggregate_submission_grades_process($batch);
2144                 // and then start to process another submission
2145                 $batch      = array($current);
2146                 $previous   = $current;
2147             }
2148         }
2149         // do not forget to process the last batch!
2150         $this->aggregate_submission_grades_process($batch);
2151         $rs->close();
2152     }
2154     /**
2155      * Sets the aggregated grades for assessment to null
2156      *
2157      * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2158      * @return void
2159      */
2160     public function clear_grading_grades($restrict=null) {
2161         global $DB;
2163         $sql = "workshopid = :workshopid";
2164         $params = array('workshopid' => $this->id);
2166         if (is_null($restrict)) {
2167             // update all users - no more conditions
2168         } elseif (!empty($restrict)) {
2169             list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2170             $sql .= " AND userid $usql";
2171             $params = array_merge($params, $uparams);
2172         } else {
2173             throw new coding_exception('Empty value is not a valid parameter here');
2174         }
2176         $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
2177     }
2179     /**
2180      * Calculates grades for assessment for the given participant(s)
2181      *
2182      * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator.
2183      * The assessment weight is not taken into account here.
2184      *
2185      * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2186      * @return void
2187      */
2188     public function aggregate_grading_grades($restrict=null) {
2189         global $DB;
2191         // fetch a recordset with all assessments to process
2192         $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover,
2193                        ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade
2194                   FROM {workshop_assessments} a
2195             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
2196              LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid)
2197                  WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2198         $params = array('workshopid' => $this->id);
2200         if (is_null($restrict)) {
2201             // update all users - no more conditions
2202         } elseif (!empty($restrict)) {
2203             list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2204             $sql .= " AND a.reviewerid $usql";
2205             $params = array_merge($params, $uparams);
2206         } else {
2207             throw new coding_exception('Empty value is not a valid parameter here');
2208         }
2210         $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing
2212         $rs         = $DB->get_recordset_sql($sql, $params);
2213         $batch      = array();    // will contain a set of all assessments of a single submission
2214         $previous   = null;       // a previous record in the recordset
2216         foreach ($rs as $current) {
2217             if (is_null($previous)) {
2218                 // we are processing the very first record in the recordset
2219                 $previous   = $current;
2220             }
2221             if ($current->reviewerid == $previous->reviewerid) {
2222                 // we are still processing the current reviewer
2223                 $batch[] = $current;
2224             } else {
2225                 // process all the assessments of a sigle submission
2226                 $this->aggregate_grading_grades_process($batch);
2227                 // and then start to process another reviewer
2228                 $batch      = array($current);
2229                 $previous   = $current;
2230             }
2231         }
2232         // do not forget to process the last batch!
2233         $this->aggregate_grading_grades_process($batch);
2234         $rs->close();
2235     }
2237     /**
2238      * Returns the mform the teachers use to put a feedback for the reviewer
2239      *
2240      * @param moodle_url $actionurl
2241      * @param stdClass $assessment
2242      * @param array $options editable, editableweight, overridablegradinggrade
2243      * @return workshop_feedbackreviewer_form
2244      */
2245     public function get_feedbackreviewer_form(moodle_url $actionurl, stdclass $assessment, $options=array()) {
2246         global $CFG;
2247         require_once(dirname(__FILE__) . '/feedbackreviewer_form.php');
2249         $current = new stdclass();
2250         $current->asid                      = $assessment->id;
2251         $current->weight                    = $assessment->weight;
2252         $current->gradinggrade              = $this->real_grading_grade($assessment->gradinggrade);
2253         $current->gradinggradeover          = $this->real_grading_grade($assessment->gradinggradeover);
2254         $current->feedbackreviewer          = $assessment->feedbackreviewer;
2255         $current->feedbackreviewerformat    = $assessment->feedbackreviewerformat;
2256         if (is_null($current->gradinggrade)) {
2257             $current->gradinggrade = get_string('nullgrade', 'workshop');
2258         }
2259         if (!isset($options['editable'])) {
2260             $editable = true;   // by default
2261         } else {
2262             $editable = (bool)$options['editable'];
2263         }
2265         // prepare wysiwyg editor
2266         $current = file_prepare_standard_editor($current, 'feedbackreviewer', array());
2268         return new workshop_feedbackreviewer_form($actionurl,
2269                 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2270                 'post', '', null, $editable);
2271     }
2273     /**
2274      * Returns the mform the teachers use to put a feedback for the author on their submission
2275      *
2276      * @param moodle_url $actionurl
2277      * @param stdClass $submission
2278      * @param array $options editable
2279      * @return workshop_feedbackauthor_form
2280      */
2281     public function get_feedbackauthor_form(moodle_url $actionurl, stdclass $submission, $options=array()) {
2282         global $CFG;
2283         require_once(dirname(__FILE__) . '/feedbackauthor_form.php');
2285         $current = new stdclass();
2286         $current->submissionid          = $submission->id;
2287         $current->published             = $submission->published;
2288         $current->grade                 = $this->real_grade($submission->grade);
2289         $current->gradeover             = $this->real_grade($submission->gradeover);
2290         $current->feedbackauthor        = $submission->feedbackauthor;
2291         $current->feedbackauthorformat  = $submission->feedbackauthorformat;
2292         if (is_null($current->grade)) {
2293             $current->grade = get_string('nullgrade', 'workshop');
2294         }
2295         if (!isset($options['editable'])) {
2296             $editable = true;   // by default
2297         } else {
2298             $editable = (bool)$options['editable'];
2299         }
2301         // prepare wysiwyg editor
2302         $current = file_prepare_standard_editor($current, 'feedbackauthor', array());
2304         return new workshop_feedbackauthor_form($actionurl,
2305                 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2306                 'post', '', null, $editable);
2307     }
2309     /**
2310      * Returns the information about the user's grades as they are stored in the gradebook
2311      *
2312      * The submission grade is returned for users with the capability mod/workshop:submit and the
2313      * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
2314      * user has the capability to view hidden grades, grades must be visible to be returned. Null
2315      * grades are not returned. If none grade is to be returned, this method returns false.
2316      *
2317      * @param int $userid the user's id
2318      * @return workshop_final_grades|false
2319      */
2320     public function get_gradebook_grades($userid) {
2321         global $CFG;
2322         require_once($CFG->libdir.'/gradelib.php');
2324         if (empty($userid)) {
2325             throw new coding_exception('User id expected, empty value given.');
2326         }
2328         // Read data via the Gradebook API
2329         $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
2331         $grades = new workshop_final_grades();
2333         if (has_capability('mod/workshop:submit', $this->context, $userid)) {
2334             if (!empty($gradebook->items[0]->grades)) {
2335                 $submissiongrade = reset($gradebook->items[0]->grades);
2336                 if (!is_null($submissiongrade->grade)) {
2337                     if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2338                         $grades->submissiongrade = $submissiongrade;
2339                     }
2340                 }
2341             }
2342         }
2344         if (has_capability('mod/workshop:peerassess', $this->context, $userid)) {
2345             if (!empty($gradebook->items[1]->grades)) {
2346                 $assessmentgrade = reset($gradebook->items[1]->grades);
2347                 if (!is_null($assessmentgrade->grade)) {
2348                     if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2349                         $grades->assessmentgrade = $assessmentgrade;
2350                     }
2351                 }
2352             }
2353         }
2355         if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
2356             return $grades;
2357         }
2359         return false;
2360     }
2362     /**
2363      * Return the editor options for the overall feedback for the author.
2364      *
2365      * @return array
2366      */
2367     public function overall_feedback_content_options() {
2368         return array(
2369             'subdirs' => 0,
2370             'maxbytes' => $this->overallfeedbackmaxbytes,
2371             'maxfiles' => $this->overallfeedbackfiles,
2372             'changeformat' => 1,
2373             'context' => $this->context,
2374         );
2375     }
2377     /**
2378      * Return the filemanager options for the overall feedback for the author.
2379      *
2380      * @return array
2381      */
2382     public function overall_feedback_attachment_options() {
2383         return array(
2384             'subdirs' => 1,
2385             'maxbytes' => $this->overallfeedbackmaxbytes,
2386             'maxfiles' => $this->overallfeedbackfiles,
2387             'return_types' => FILE_INTERNAL,
2388         );
2389     }
2391     ////////////////////////////////////////////////////////////////////////////////
2392     // Internal methods (implementation details)                                  //
2393     ////////////////////////////////////////////////////////////////////////////////
2395     /**
2396      * Given an array of all assessments of a single submission, calculates the final grade for this submission
2397      *
2398      * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade
2399      * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored.
2400      *
2401      * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
2402      * @return void
2403      */
2404     protected function aggregate_submission_grades_process(array $assessments) {
2405         global $DB;
2407         $submissionid   = null; // the id of the submission being processed
2408         $current        = null; // the grade currently saved in database
2409         $finalgrade     = null; // the new grade to be calculated
2410         $sumgrades      = 0;
2411         $sumweights     = 0;
2413         foreach ($assessments as $assessment) {
2414             if (is_null($submissionid)) {
2415                 // the id is the same in all records, fetch it during the first loop cycle
2416                 $submissionid = $assessment->submissionid;
2417             }
2418             if (is_null($current)) {
2419                 // the currently saved grade is the same in all records, fetch it during the first loop cycle
2420                 $current = $assessment->submissiongrade;
2421             }
2422             if (is_null($assessment->grade)) {
2423                 // this was not assessed yet
2424                 continue;
2425             }
2426             if ($assessment->weight == 0) {
2427                 // this does not influence the calculation
2428                 continue;
2429             }
2430             $sumgrades  += $assessment->grade * $assessment->weight;
2431             $sumweights += $assessment->weight;
2432         }
2433         if ($sumweights > 0 and is_null($finalgrade)) {
2434             $finalgrade = grade_floatval($sumgrades / $sumweights);
2435         }
2436         // check if the new final grade differs from the one stored in the database
2437         if (grade_floats_different($finalgrade, $current)) {
2438             // we need to save new calculation into the database
2439             $record = new stdclass();
2440             $record->id = $submissionid;
2441             $record->grade = $finalgrade;
2442             $record->timegraded = time();
2443             $DB->update_record('workshop_submissions', $record);
2444         }
2445     }
2447     /**
2448      * Given an array of all assessments done by a single reviewer, calculates the final grading grade
2449      *
2450      * This calculates the simple mean of the passed grading grades. If, however, the grading grade
2451      * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored.
2452      *
2453      * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade)
2454      * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time
2455      * @return void
2456      */
2457     protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
2458         global $DB;
2460         $reviewerid = null; // the id of the reviewer being processed
2461         $current    = null; // the gradinggrade currently saved in database
2462         $finalgrade = null; // the new grade to be calculated
2463         $agid       = null; // aggregation id
2464         $sumgrades  = 0;
2465         $count      = 0;
2467         if (is_null($timegraded)) {
2468             $timegraded = time();
2469         }
2471         foreach ($assessments as $assessment) {
2472             if (is_null($reviewerid)) {
2473                 // the id is the same in all records, fetch it during the first loop cycle
2474                 $reviewerid = $assessment->reviewerid;
2475             }
2476             if (is_null($agid)) {
2477                 // the id is the same in all records, fetch it during the first loop cycle
2478                 $agid = $assessment->aggregationid;
2479             }
2480             if (is_null($current)) {
2481                 // the currently saved grade is the same in all records, fetch it during the first loop cycle
2482                 $current = $assessment->aggregatedgrade;
2483             }
2484             if (!is_null($assessment->gradinggradeover)) {
2485                 // the grading grade for this assessment is overridden by a teacher
2486                 $sumgrades += $assessment->gradinggradeover;
2487                 $count++;
2488             } else {
2489                 if (!is_null($assessment->gradinggrade)) {
2490                     $sumgrades += $assessment->gradinggrade;
2491                     $count++;
2492                 }
2493             }
2494         }
2495         if ($count > 0) {
2496             $finalgrade = grade_floatval($sumgrades / $count);
2497         }
2499         // Event information.
2500         $params = array(
2501             'context' => $this->context,
2502             'courseid' => $this->course->id,
2503             'relateduserid' => $reviewerid
2504         );
2506         // check if the new final grade differs from the one stored in the database
2507         if (grade_floats_different($finalgrade, $current)) {
2508             $params['other'] = array(
2509                 'currentgrade' => $current,
2510                 'finalgrade' => $finalgrade
2511             );
2513             // we need to save new calculation into the database
2514             if (is_null($agid)) {
2515                 // no aggregation record yet
2516                 $record = new stdclass();
2517                 $record->workshopid = $this->id;
2518                 $record->userid = $reviewerid;
2519                 $record->gradinggrade = $finalgrade;
2520                 $record->timegraded = $timegraded;
2521                 $record->id = $DB->insert_record('workshop_aggregations', $record);
2522                 $params['objectid'] = $record->id;
2523                 $event = \mod_workshop\event\assessment_evaluated::create($params);
2524                 $event->trigger();
2525             } else {
2526                 $record = new stdclass();
2527                 $record->id = $agid;
2528                 $record->gradinggrade = $finalgrade;
2529                 $record->timegraded = $timegraded;
2530                 $DB->update_record('workshop_aggregations', $record);
2531                 $params['objectid'] = $agid;
2532                 $event = \mod_workshop\event\assessment_reevaluated::create($params);
2533                 $event->trigger();
2534             }
2535         }
2536     }
2538     /**
2539      * Returns SQL to fetch all enrolled users with the given capability in the current workshop
2540      *
2541      * The returned array consists of string $sql and the $params array. Note that the $sql can be
2542      * empty if a grouping is selected and it has no groups.
2543      *
2544      * The list is automatically restricted according to any availability restrictions
2545      * that apply to user lists (e.g. group, grouping restrictions).
2546      *
2547      * @param string $capability the name of the capability
2548      * @param bool $musthavesubmission ff true, return only users who have already submitted
2549      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2550      * @return array of (string)sql, (array)params
2551      */
2552     protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) {
2553         global $CFG;
2554         /** @var int static counter used to generate unique parameter holders */
2555         static $inc = 0;
2556         $inc++;
2558         // If the caller requests all groups and we are using a selected grouping,
2559         // recursively call this function for each group in the grouping (this is
2560         // needed because get_enrolled_sql only supports a single group).
2561         if (empty($groupid) and $this->cm->groupingid) {
2562             $groupingid = $this->cm->groupingid;
2563             $groupinggroupids = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
2564             $sql = array();
2565             $params = array();
2566             foreach ($groupinggroupids as $groupinggroupid) {
2567                 if ($groupinggroupid > 0) { // just in case in order not to fall into the endless loop
2568                     list($gsql, $gparams) = $this->get_users_with_capability_sql($capability, $musthavesubmission, $groupinggroupid);
2569                     $sql[] = $gsql;
2570                     $params = array_merge($params, $gparams);
2571                 }
2572             }
2573             $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql);
2574             return array($sql, $params);
2575         }
2577         list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true);
2579         $userfields = user_picture::fields('u');
2581         $sql = "SELECT $userfields
2582                   FROM {user} u
2583                   JOIN ($esql) je ON (je.id = u.id AND u.deleted = 0) ";
2585         if ($musthavesubmission) {
2586             $sql .= " JOIN {workshop_submissions} ws ON (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid{$inc}) ";
2587             $params['workshopid'.$inc] = $this->id;
2588         }
2590         // If the activity is restricted so that only certain users should appear
2591         // in user lists, integrate this into the same SQL.
2592         $info = new \core_availability\info_module($this->cm);
2593         list ($listsql, $listparams) = $info->get_user_list_sql(false);
2594         if ($listsql) {
2595             $sql .= " JOIN ($listsql) restricted ON restricted.id = u.id ";
2596             $params = array_merge($params, $listparams);
2597         }
2599         return array($sql, $params);
2600     }
2602     /**
2603      * Returns SQL statement that can be used to fetch all actively enrolled participants in the workshop
2604      *
2605      * @param bool $musthavesubmission if true, return only users who have already submitted
2606      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2607      * @return array of (string)sql, (array)params
2608      */
2609     protected function get_participants_sql($musthavesubmission=false, $groupid=0) {
2611         list($sql1, $params1) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
2612         list($sql2, $params2) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
2614         if (empty($sql1) or empty($sql2)) {
2615             if (empty($sql1) and empty($sql2)) {
2616                 return array('', array());
2617             } else if (empty($sql1)) {
2618                 $sql = $sql2;
2619                 $params = $params2;
2620             } else {
2621                 $sql = $sql1;
2622                 $params = $params1;
2623             }
2624         } else {
2625             $sql = $sql1.PHP_EOL." UNION ".PHP_EOL.$sql2;
2626             $params = array_merge($params1, $params2);
2627         }
2629         return array($sql, $params);
2630     }
2632     /**
2633      * @return array of available workshop phases
2634      */
2635     protected function available_phases_list() {
2636         return array(
2637             self::PHASE_SETUP       => true,
2638             self::PHASE_SUBMISSION  => true,
2639             self::PHASE_ASSESSMENT  => true,
2640             self::PHASE_EVALUATION  => true,
2641             self::PHASE_CLOSED      => true,
2642         );
2643     }
2645     /**
2646      * Converts absolute URL to relative URL needed by {@see add_to_log()}
2647      *
2648      * @param moodle_url $url absolute URL
2649      * @return string
2650      */
2651     protected function log_convert_url(moodle_url $fullurl) {
2652         static $baseurl;
2654         if (!isset($baseurl)) {
2655             $baseurl = new moodle_url('/mod/workshop/');
2656             $baseurl = $baseurl->out();
2657         }
2659         return substr($fullurl->out(), strlen($baseurl));
2660     }
2661     
2662     /**
2663      * Resets this activity's content
2664      * @param array The reset data object.
2665      * @return bool True if the reset was successful, false if there was an error
2666      */
2667     public function reset_userdata($data) {
2668         $componentstr = get_string('modulenameplural', 'workshop');
2669         $status = array();
2670         $this->reset_submissions();
2671         $delaggregations = $DB->delete_records('workshop_aggregations', array('workshopid' => $this->id));
2672         $this->reset_allocators();
2673         $this->reset_evaluators();
2674         $this->reset_strategies();
2676         $events = $DB->get_records('event', array('modulename' => 'workshop', 'instance' => $this->id));\r
2677         foreach ($events as $event) {
2678             $event = calendar_event::load($event);
2679             $event->delete();\r
2680         }
2682         // Set the phase.
2683         // $DB->set_field('workshop', 'phase', 0, array('id' => $workshop->id));    // Left in to give option to switch back after discussion.
2684         $this->switch_phase(self::PHASE_SETUP);    // Use the API but we may not want to raise events about this....
2686         $status[] = array('component' => $componentstr, 'item' => get_string('resetworkshopall', 'workshop'), 'error' => false);
2687         return $status;
2688     }
2690     /**
2691      * Remove user content, including grades
2692      */
2693     protected function reset_submissions() {
2694         $submissions = $this->get_submissions();\r
2695         foreach ($submissions as $submission) {\r
2696             $this->delete_submission($submission);\r
2697         }
2698         // Clean up submission files.
2699         $fs = get_file_storage();
2700         $files = $fs->get_area_files($this->context, 'mod_workshop', 'submission_attachment', false);
2701         $numberfilestodelete = count($files);
2702         $numfilesdeleted = 0;
2703         foreach ($files as $file) {
2704              try {
2705                 $file->delete();
2706                 $numfilesdeleted += 1;
2707             }
2708             catch (Exception $exception) {
2709                 // The delete can fail if necessary it just leaves an orphan in the DB. The record its attached to will have rady been removed.
2710             }
2711         }
2712     }
2713     
2714     protected function reset_allocators() {
2715         $allocators = core_component::get_plugin_list('workshopallocation');
2716         foreach ($allocators as $allocator => $path) {\r
2717             require_once($path.'/lib.php');\r
2718             $classname = 'workshop_'.$allocator.'_allocator';\r
2719             call_user_func($classname.'::reset_user_data', $this->id);\r
2720         }
2721     }
2723     protected function reset_strategies() {
2724         $evaluators = core_component::get_plugin_list('workshopeval');
2725         foreach ($evaluators as $evaluator => $path) {\r
2726             require_once($path.'/lib.php');\r
2727             $classname = 'workshop_'.$evaluator.'_evaluation';\r
2728             call_user_func($classname.'::reset_user_data', $this->id);\r
2729         }
2730     }
2732     protected function reset_evaluators() {
2733         $evaluators = core_component::get_plugin_list('workshopeval');\r
2734         foreach ($evaluators as $evaluator => $path) {\r
2735             require_once($path.'/lib.php');\r
2736             $classname = 'workshop_'.$evaluator.'_evaluation';\r
2737             call_user_func($classname.'::reset_user_data', $this->id);\r
2738         }
2739     }
2742 ////////////////////////////////////////////////////////////////////////////////
2743 // Renderable components
2744 ////////////////////////////////////////////////////////////////////////////////
2746 /**
2747  * Represents the user planner tool
2748  *
2749  * Planner contains list of phases. Each phase contains list of tasks. Task is a simple object with
2750  * title, link and completed (true/false/null logic).
2751  */
2752 class workshop_user_plan implements renderable {
2754     /** @var int id of the user this plan is for */
2755     public $userid;
2756     /** @var workshop */
2757     public $workshop;
2758     /** @var array of (stdclass)tasks */
2759     public $phases = array();
2760     /** @var null|array of example submissions to be assessed by the planner owner */
2761     protected $examples = null;
2763     /**
2764      * Prepare an individual workshop plan for the given user.
2765      *
2766      * @param workshop $workshop instance
2767      * @param int $userid whom the plan is prepared for
2768      */
2769     public function __construct(workshop $workshop, $userid) {
2770         global $DB;
2772         $this->workshop = $workshop;
2773         $this->userid   = $userid;
2775         //---------------------------------------------------------
2776         // * SETUP | submission | assessment | evaluation | closed
2777         //---------------------------------------------------------
2778         $phase = new stdclass();
2779         $phase->title = get_string('phasesetup', 'workshop');
2780         $phase->tasks = array();
2781         if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2782             $task = new stdclass();
2783             $task->title = get_string('taskintro', 'workshop');
2784             $task->link = $workshop->updatemod_url();
2785             $task->completed = !(trim($workshop->intro) == '');
2786             $phase->tasks['intro'] = $task;
2787         }
2788         if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2789             $task = new stdclass();
2790             $task->title = get_string('taskinstructauthors', 'workshop');
2791             $task->link = $workshop->updatemod_url();
2792             $task->completed = !(trim($workshop->instructauthors) == '');
2793             $phase->tasks['instructauthors'] = $task;
2794         }
2795         if (has_capability('mod/workshop:editdimensions', $workshop->context, $userid)) {
2796             $task = new stdclass();
2797             $task->title = get_string('editassessmentform', 'workshop');
2798             $task->link = $workshop->editform_url();
2799             if ($workshop->grading_strategy_instance()->form_ready()) {
2800                 $task->completed = true;
2801             } elseif ($workshop->phase > workshop::PHASE_SETUP) {
2802                 $task->completed = false;
2803             }
2804             $phase->tasks['editform'] = $task;
2805         }
2806         if ($workshop->useexamples and has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2807             $task = new stdclass();
2808             $task->title = get_string('prepareexamples', 'workshop');
2809             if ($DB->count_records('workshop_submissions', array('example' => 1, 'workshopid' => $workshop->id)) > 0) {
2810                 $task->completed = true;
2811             } elseif ($workshop->phase > workshop::PHASE_SETUP) {
2812                 $task->completed = false;
2813             }
2814             $phase->tasks['prepareexamples'] = $task;
2815         }
2816         if (empty($phase->tasks) and $workshop->phase == workshop::PHASE_SETUP) {
2817             // if we are in the setup phase and there is no task (typical for students), let us
2818             // display some explanation what is going on
2819             $task = new stdclass();
2820             $task->title = get_string('undersetup', 'workshop');
2821             $task->completed = 'info';
2822             $phase->tasks['setupinfo'] = $task;
2823         }
2824         $this->phases[workshop::PHASE_SETUP] = $phase;
2826         //---------------------------------------------------------
2827         // setup | * SUBMISSION | assessment | evaluation | closed
2828         //---------------------------------------------------------
2829         $phase = new stdclass();
2830         $phase->title = get_string('phasesubmission', 'workshop');
2831         $phase->tasks = array();
2832         if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2833             $task = new stdclass();
2834             $task->title = get_string('taskinstructreviewers', 'workshop');
2835             $task->link = $workshop->updatemod_url();
2836             if (trim($workshop->instructreviewers)) {
2837                 $task->completed = true;
2838             } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2839                 $task->completed = false;
2840             }
2841             $phase->tasks['instructreviewers'] = $task;
2842         }
2843         if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION
2844                 and has_capability('mod/workshop:submit', $workshop->context, $userid, false)
2845                     and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2846             $task = new stdclass();
2847             $task->title = get_string('exampleassesstask', 'workshop');
2848             $examples = $this->get_examples();
2849             $a = new stdclass();
2850             $a->expected = count($examples);
2851             $a->assessed = 0;
2852             foreach ($examples as $exampleid => $example) {
2853                 if (!is_null($example->grade)) {
2854                     $a->assessed++;
2855                 }
2856             }
2857             $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
2858             if ($a->assessed == $a->expected) {
2859                 $task->completed = true;
2860             } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2861                 $task->completed = false;
2862             }
2863             $phase->tasks['examples'] = $task;
2864         }
2865         if (has_capability('mod/workshop:submit', $workshop->context, $userid, false)) {
2866             $task = new stdclass();
2867             $task->title = get_string('tasksubmit', 'workshop');
2868             $task->link = $workshop->submission_url();
2869             if ($DB->record_exists('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0, 'authorid'=>$userid))) {
2870                 $task->completed = true;
2871             } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2872                 $task->completed = false;
2873             } else {
2874                 $task->completed = null;    // still has a chance to submit
2875             }
2876             $phase->tasks['submit'] = $task;
2877         }
2878         if (has_capability('mod/workshop:allocate', $workshop->context, $userid)) {
2879             if ($workshop->phaseswitchassessment) {
2880                 $task = new stdClass();
2881                 $allocator = $DB->get_record('workshopallocation_scheduled', array('workshopid' => $workshop->id));
2882                 if (empty($allocator)) {
2883                     $task->completed = false;
2884                 } else if ($allocator->enabled and is_null($allocator->resultstatus)) {
2885                     $task->completed = true;
2886                 } else if ($workshop->submissionend > time()) {
2887                     $task->completed = null;
2888                 } else {
2889                     $task->completed = false;
2890                 }
2891                 $task->title = get_string('setup', 'workshopallocation_scheduled');
2892                 $task->link = $workshop->allocation_url('scheduled');
2893                 $phase->tasks['allocatescheduled'] = $task;
2894             }
2895             $task = new stdclass();
2896             $task->title = get_string('allocate', 'workshop');
2897             $task->link = $workshop->allocation_url();
2898             $numofauthors = $workshop->count_potential_authors(false);
2899             $numofsubmissions = $DB->count_records('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0));
2900             $sql = 'SELECT COUNT(s.id) AS nonallocated
2901                       FROM {workshop_submissions} s
2902                  LEFT JOIN {workshop_assessments} a ON (a.submissionid=s.id)
2903                      WHERE s.workshopid = :workshopid AND s.example=0 AND a.submissionid IS NULL';
2904             $params['workshopid'] = $workshop->id;
2905             $numnonallocated = $DB->count_records_sql($sql, $params);
2906             if ($numofsubmissions == 0) {
2907                 $task->completed = null;
2908             } elseif ($numnonallocated == 0) {
2909                 $task->completed = true;
2910             } elseif ($workshop->phase > workshop::PHASE_SUBMISSION) {
2911                 $task->completed = false;
2912             } else {
2913                 $task->completed = null;    // still has a chance to allocate
2914             }
2915             $a = new stdclass();
2916             $a->expected    = $numofauthors;
2917             $a->submitted   = $numofsubmissions;
2918             $a->allocate    = $numnonallocated;
2919             $task->details  = get_string('allocatedetails', 'workshop', $a);
2920             unset($a);
2921             $phase->tasks['allocate'] = $task;
2923             if ($numofsubmissions < $numofauthors and $workshop->phase >= workshop::PHASE_SUBMISSION) {
2924                 $task = new stdclass();
2925                 $task->title = get_string('someuserswosubmission', 'workshop');
2926                 $task->completed = 'info';
2927                 $phase->tasks['allocateinfo'] = $task;
2928             }
2930         }
2931         if ($workshop->submissionstart) {
2932             $task = new stdclass();
2933             $task->title = get_string('submissionstartdatetime', 'workshop', workshop::timestamp_formats($workshop->submissionstart));
2934             $task->completed = 'info';
2935             $phase->tasks['submissionstartdatetime'] = $task;
2936         }
2937         if ($workshop->submissionend) {
2938             $task = new stdclass();
2939             $task->title = get_string('submissionenddatetime', 'workshop', workshop::timestamp_formats($workshop->submissionend));
2940             $task->completed = 'info';
2941             $phase->tasks['submissionenddatetime'] = $task;
2942         }
2943         if (($workshop->submissionstart < time()) and $workshop->latesubmissions) {
2944             $task = new stdclass();
2945             $task->title = get_string('latesubmissionsallowed', 'workshop');
2946             $task->completed = 'info';
2947             $phase->tasks['latesubmissionsallowed'] = $task;
2948         }
2949         if (isset($phase->tasks['submissionstartdatetime']) or isset($phase->tasks['submissionenddatetime'])) {
2950             if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
2951                 $task = new stdclass();
2952                 $task->title = get_string('deadlinesignored', 'workshop');
2953                 $task->completed = 'info';
2954                 $phase->tasks['deadlinesignored'] = $task;
2955             }
2956         }
2957         $this->phases[workshop::PHASE_SUBMISSION] = $phase;
2959         //---------------------------------------------------------
2960         // setup | submission | * ASSESSMENT | evaluation | closed
2961         //---------------------------------------------------------
2962         $phase = new stdclass();
2963         $phase->title = get_string('phaseassessment', 'workshop');
2964         $phase->tasks = array();
2965         $phase->isreviewer = has_capability('mod/workshop:peerassess', $workshop->context, $userid);
2966         if ($workshop->phase == workshop::PHASE_SUBMISSION and $workshop->phaseswitchassessment
2967                 and has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
2968             $task = new stdClass();
2969             $task->title = get_string('switchphase30auto', 'mod_workshop', workshop::timestamp_formats($workshop->submissionend));
2970             $task->completed = 'info';
2971             $phase->tasks['autoswitchinfo'] = $task;
2972         }
2973         if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_ASSESSMENT
2974                 and $phase->isreviewer and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2975             $task = new stdclass();
2976             $task->title = get_string('exampleassesstask', 'workshop');
2977             $examples = $workshop->get_examples_for_reviewer($userid);
2978             $a = new stdclass();
2979             $a->expected = count($examples);
2980             $a->assessed = 0;
2981             foreach ($examples as $exampleid => $example) {
2982                 if (!is_null($example->grade)) {
2983                     $a->assessed++;
2984                 }
2985             }
2986             $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
2987             if ($a->assessed == $a->expected) {
2988                 $task->completed = true;
2989             } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
2990                 $task->completed = false;
2991             }
2992             $phase->tasks['examples'] = $task;
2993         }
2994         if (empty($phase->tasks['examples']) or !empty($phase->tasks['examples']->completed)) {
2995             $phase->assessments = $workshop->get_assessments_by_reviewer($userid);
2996             $numofpeers     = 0;    // number of allocated peer-assessments
2997             $numofpeerstodo = 0;    // number of peer-assessments to do
2998             $numofself      = 0;    // number of allocated self-assessments - should be 0 or 1
2999             $numofselftodo  = 0;    // number of self-assessments to do - should be 0 or 1
3000             foreach ($phase->assessments as $a) {
3001                 if ($a->authorid == $userid) {
3002                     $numofself++;
3003                     if (is_null($a->grade)) {
3004                         $numofselftodo++;
3005                     }
3006                 } else {
3007                     $numofpeers++;
3008                     if (is_null($a->grade)) {
3009                         $numofpeerstodo++;
3010                     }
3011                 }
3012             }
3013             unset($a);
3014             if ($numofpeers) {
3015                 $task = new stdclass();
3016                 if ($numofpeerstodo == 0) {
3017                     $task->completed = true;
3018                 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3019                     $task->completed = false;
3020                 }
3021                 $a = new stdclass();
3022                 $a->total = $numofpeers;
3023                 $a->todo  = $numofpeerstodo;
3024                 $task->title = get_string('taskassesspeers', 'workshop');
3025                 $task->details = get_string('taskassesspeersdetails', 'workshop', $a);
3026                 unset($a);
3027                 $phase->tasks['assesspeers'] = $task;
3028             }
3029             if ($workshop->useselfassessment and $numofself) {
3030                 $task = new stdclass();
3031                 if ($numofselftodo == 0) {
3032                     $task->completed = true;
3033                 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3034                     $task->completed = false;
3035                 }
3036                 $task->title = get_string('taskassessself', 'workshop');
3037                 $phase->tasks['assessself'] = $task;
3038             }
3039         }
3040         if ($workshop->assessmentstart) {
3041             $task = new stdclass();
3042             $task->title = get_string('assessmentstartdatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentstart));
3043             $task->completed = 'info';
3044             $phase->tasks['assessmentstartdatetime'] = $task;
3045         }
3046         if ($workshop->assessmentend) {
3047             $task = new stdclass();
3048             $task->title = get_string('assessmentenddatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentend));
3049             $task->completed = 'info';
3050             $phase->tasks['assessmentenddatetime'] = $task;
3051         }
3052         if (isset($phase->tasks['assessmentstartdatetime']) or isset($phase->tasks['assessmentenddatetime'])) {
3053             if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
3054                 $task = new stdclass();
3055                 $task->title = get_string('deadlinesignored', 'workshop');
3056                 $task->completed = 'info';
3057                 $phase->tasks['deadlinesignored'] = $task;
3058             }
3059         }
3060         $this->phases[workshop::PHASE_ASSESSMENT] = $phase;
3062         //---------------------------------------------------------
3063         // setup | submission | assessment | * EVALUATION | closed
3064         //---------------------------------------------------------
3065         $phase = new stdclass();
3066         $phase->title = get_string('phaseevaluation', 'workshop');
3067         $phase->tasks = array();
3068         if (has_capability('mod/workshop:overridegrades', $workshop->context)) {
3069             $expected = $workshop->count_potential_authors(false);
3070             $calculated = $DB->count_records_select('workshop_submissions',
3071                     'workshopid = ? AND (grade IS NOT NULL OR gradeover IS NOT NULL)', array($workshop->id));
3072             $task = new stdclass();
3073             $task->title = get_string('calculatesubmissiongrades', 'workshop');
3074             $a = new stdclass();
3075             $a->expected    = $expected;
3076             $a->calculated  = $calculated;
3077             $task->details  = get_string('calculatesubmissiongradesdetails', 'workshop', $a);
3078             if ($calculated >= $expected) {
3079                 $task->completed = true;
3080             } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
3081                 $task->completed = false;
3082             }
3083             $phase->tasks['calculatesubmissiongrade'] = $task;
3085             $expected = $workshop->count_potential_reviewers(false);
3086             $calculated = $DB->count_records_select('workshop_aggregations',
3087                     'workshopid = ? AND gradinggrade IS NOT NULL', array($workshop->id));
3088             $task = new stdclass();
3089             $task->title = get_string('calculategradinggrades', 'workshop');
3090             $a = new stdclass();
3091             $a->expected    = $expected;
3092             $a->calculated  = $calculated;
3093             $task->details  = get_string('calculategradinggradesdetails', 'workshop', $a);
3094             if ($calculated >= $expected) {
3095                 $task->completed = true;
3096             } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
3097                 $task->completed = false;
3098             }
3099             $phase->tasks['calculategradinggrade'] = $task;
3101         } elseif ($workshop->phase == workshop::PHASE_EVALUATION) {
3102             $task = new stdclass();
3103             $task->title = get_string('evaluategradeswait', 'workshop');
3104             $task->completed = 'info';
3105             $phase->tasks['evaluateinfo'] = $task;
3106         }
3108         if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3109             $task = new stdclass();
3110             $task->title = get_string('taskconclusion', 'workshop');
3111             $task->link = $workshop->updatemod_url();
3112             if (trim($workshop->conclusion)) {
3113                 $task->completed = true;
3114             } elseif ($workshop->phase >= workshop::PHASE_EVALUATION) {
3115                 $task->completed = false;
3116             }
3117             $phase->tasks['conclusion'] = $task;
3118         }
3120         $this->phases[workshop::PHASE_EVALUATION] = $phase;
3122         //---------------------------------------------------------
3123         // setup | submission | assessment | evaluation | * CLOSED
3124         //---------------------------------------------------------
3125         $phase = new stdclass();
3126         $phase->title = get_string('phaseclosed', 'workshop');
3127         $phase->tasks = array();
3128         $this->phases[workshop::PHASE_CLOSED] = $phase;
3130         // Polish data, set default values if not done explicitly
3131         foreach ($this->phases as $phasecode => $phase) {
3132             $phase->title       = isset($phase->title)      ? $phase->title     : '';
3133             $phase->tasks       = isset($phase->tasks)      ? $phase->tasks     : array();
3134             if ($phasecode == $workshop->phase) {
3135                 $phase->active = true;
3136             } else {
3137                 $phase->active = false;
3138             }
3139             if (!isset($phase->actions)) {
3140                 $phase->actions = array();
3141             }
3143             foreach ($phase->tasks as $taskcode => $task) {
3144                 $task->title        = isset($task->title)       ? $task->title      : '';
3145                 $task->link         = isset($task->link)        ? $task->link       : null;
3146                 $task->details      = isset($task->details)     ? $task->details    : '';
3147                 $task->completed    = isset($task->completed)   ? $task->completed  : null;
3148             }
3149         }
3151         // Add phase switching actions
3152         if (has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
3153             foreach ($this->phases as $phasecode => $phase) {
3154                 if (! $phase->active) {
3155                     $action = new stdclass();
3156                     $action->type = 'switchphase';
3157                     $action->url  = $workshop->switchphase_url($phasecode);
3158                     $phase->actions[] = $action;
3159                 }
3160             }
3161         }
3162     }
3164     /**
3165      * Returns example submissions to be assessed by the owner of the planner
3166      *
3167      * This is here to cache the DB query because the same list is needed later in view.php
3168      *
3169      * @see workshop::get_examples_for_reviewer() for the format of returned value
3170      * @return array
3171      */
3172     public function get_examples() {
3173         if (is_null($this->examples)) {
3174             $this->examples = $this->workshop->get_examples_for_reviewer($this->userid);
3175         }
3176         return $this->examples;
3177     }
3180 /**
3181  * Common base class for submissions and example submissions rendering
3182  *
3183  * Subclasses of this class convert raw submission record from
3184  * workshop_submissions table (as returned by {@see workshop::get_submission_by_id()}
3185  * for example) into renderable objects.
3186  */
3187 abstract class workshop_submission_base {
3189     /** @var bool is the submission anonymous (i.e. contains author information) */
3190     protected $anonymous;
3192     /* @var array of columns from workshop_submissions that are assigned as properties */
3193     protected $fields = array();
3195     /** @var workshop */
3196     protected $workshop;
3198     /**
3199      * Copies the properties of the given database record into properties of $this instance
3200      *
3201      * @param workshop $workshop
3202      * @param stdClass $submission full record
3203      * @param bool $showauthor show the author-related information
3204      * @param array $options additional properties
3205      */
3206     public function __construct(workshop $workshop, stdClass $submission, $showauthor = false) {
3208         $this->workshop = $workshop;
3210         foreach ($this->fields as $field) {
3211             if (!property_exists($submission, $field)) {
3212                 throw new coding_exception('Submission record must provide public property ' . $field);
3213             }
3214             if (!property_exists($this, $field)) {
3215                 throw new coding_exception('Renderable component must accept public property ' . $field);
3216             }
3217             $this->{$field} = $submission->{$field};
3218         }
3220         if ($showauthor) {
3221             $this->anonymous = false;
3222         } else {
3223             $this->anonymize();
3224         }
3225     }
3227     /**
3228      * Unsets all author-related properties so that the renderer does not have access to them
3229      *
3230      * Usually this is called by the contructor but can be called explicitely, too.
3231      */
3232     public function anonymize() {
3233         $authorfields = explode(',', user_picture::fields());
3234         foreach ($authorfields as $field) {
3235             $prefixedusernamefield = 'author' . $field;
3236             unset($this->{$prefixedusernamefield});
3237         }
3238         $this->anonymous = true;
3239     }
3241     /**
3242      * Does the submission object contain author-related information?
3243      *
3244      * @return null|boolean
3245      */
3246     public function is_anonymous() {
3247         return $this->anonymous;
3248     }
3251 /**
3252  * Renderable object containing a basic set of information needed to display the submission summary
3253  *
3254  * @see workshop_renderer::render_workshop_submission_summary
3255  */
3256 class workshop_submission_summary extends workshop_submission_base implements renderable {
3258     /** @var int */
3259     public $id;
3260     /** @var string */
3261     public $title;
3262     /** @var string graded|notgraded */
3263     public $status;
3264     /** @var int */
3265     public $timecreated;
3266     /** @var int */
3267     public $timemodified;
3268     /** @var int */
3269     public $authorid;
3270     /** @var string */
3271     public $authorfirstname;
3272     /** @var string */
3273     public $authorlastname;
3274     /** @var string */
3275     public $authorfirstnamephonetic;
3276     /** @var string */
3277     public $authorlastnamephonetic;
3278     /** @var string */
3279     public $authormiddlename;
3280     /** @var string */
3281     public $authoralternatename;
3282     /** @var int */
3283     public $authorpicture;
3284     /** @var string */
3285     public $authorimagealt;
3286     /** @var string */
3287     public $authoremail;
3288     /** @var moodle_url to display submission */
3289     public $url;
3291     /**
3292      * @var array of columns from workshop_submissions that are assigned as properties
3293      * of instances of this class
3294      */
3295     protected $fields = array(
3296         'id', 'title', 'timecreated', 'timemodified',
3297         'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
3298         'authormiddlename', 'authoralternatename', 'authorpicture',
3299         'authorimagealt', 'authoremail');
3302 /**
3303  * Renderable object containing all the information needed to display the submission
3304  *
3305  * @see workshop_renderer::render_workshop_submission()
3306  */
3307 class workshop_submission extends workshop_submission_summary implements renderable {
3309     /** @var string */
3310     public $content;
3311     /** @var int */
3312     public $contentformat;
3313     /** @var bool */
3314     public $contenttrust;
3315     /** @var array */
3316     public $attachment;
3318     /**
3319      * @var array of columns from workshop_submissions that are assigned as properties
3320      * of instances of this class
3321      */
3322     protected $fields = array(
3323         'id', 'title', 'timecreated', 'timemodified', 'content', 'contentformat', 'contenttrust',
3324         'attachment', 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
3325         'authormiddlename', 'authoralternatename', 'authorpicture', 'authorimagealt', 'authoremail');
3328 /**
3329  * Renderable object containing a basic set of information needed to display the example submission summary
3330  *
3331  * @see workshop::prepare_example_summary()
3332  * @see workshop_renderer::render_workshop_example_submission_summary()
3333  */
3334 class workshop_example_submission_summary extends workshop_submission_base implements renderable {
3336     /** @var int */
3337     public $id;
3338     /** @var string */
3339     public $title;
3340     /** @var string graded|notgraded */
3341     public $status;
3342     /** @var stdClass */
3343     public $gradeinfo;
3344   &n