9c314ddfb5f50cb84f07e144e65dade6df678842
[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));
1062         $DB->delete_records('workshop_submissions', array('id' => $submission->id));
1063     }
1065     /**
1066      * Returns the list of all assessments in the workshop with some data added
1067      *
1068      * Fetches data from {workshop_assessments} and adds some useful information from other
1069      * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory
1070      * lack issues.
1071      *
1072      * @return array [assessmentid] => assessment stdclass
1073      */
1074     public function get_all_assessments() {
1075         global $DB;
1077         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1078         $authorfields   = user_picture::fields('author', null, 'authorid', 'author');
1079         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1080         list($sort, $params) = users_order_by_sql('reviewer');
1081         $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified,
1082                        a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby,
1083                        $reviewerfields, $authorfields, $overbyfields,
1084                        s.title
1085                   FROM {workshop_assessments} a
1086             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1087             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1088             INNER JOIN {user} author ON (s.authorid = author.id)
1089              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1090                  WHERE s.workshopid = :workshopid AND s.example = 0
1091               ORDER BY $sort";
1092         $params['workshopid'] = $this->id;
1094         return $DB->get_records_sql($sql, $params);
1095     }
1097     /**
1098      * Get the complete information about the given assessment
1099      *
1100      * @param int $id Assessment ID
1101      * @return stdclass
1102      */
1103     public function get_assessment_by_id($id) {
1104         global $DB;
1106         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1107         $authorfields   = user_picture::fields('author', null, 'authorid', 'author');
1108         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1109         $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1110                   FROM {workshop_assessments} a
1111             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1112             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1113             INNER JOIN {user} author ON (s.authorid = author.id)
1114              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1115                  WHERE a.id = :id AND s.workshopid = :workshopid";
1116         $params = array('id' => $id, 'workshopid' => $this->id);
1118         return $DB->get_record_sql($sql, $params, MUST_EXIST);
1119     }
1121     /**
1122      * Get the complete information about the user's assessment of the given submission
1123      *
1124      * @param int $sid submission ID
1125      * @param int $uid user ID of the reviewer
1126      * @return false|stdclass false if not found, stdclass otherwise
1127      */
1128     public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
1129         global $DB;
1131         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1132         $authorfields   = user_picture::fields('author', null, 'authorid', 'author');
1133         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1134         $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1135                   FROM {workshop_assessments} a
1136             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1137             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1138             INNER JOIN {user} author ON (s.authorid = author.id)
1139              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1140                  WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid";
1141         $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id);
1143         return $DB->get_record_sql($sql, $params, IGNORE_MISSING);
1144     }
1146     /**
1147      * Get the complete information about all assessments of the given submission
1148      *
1149      * @param int $submissionid
1150      * @return array
1151      */
1152     public function get_assessments_of_submission($submissionid) {
1153         global $DB;
1155         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1156         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1157         list($sort, $params) = users_order_by_sql('reviewer');
1158         $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields
1159                   FROM {workshop_assessments} a
1160             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1161             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1162              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1163                  WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid
1164               ORDER BY $sort";
1165         $params['submissionid'] = $submissionid;
1166         $params['workshopid']   = $this->id;
1168         return $DB->get_records_sql($sql, $params);
1169     }
1171     /**
1172      * Get the complete information about all assessments allocated to the given reviewer
1173      *
1174      * @param int $reviewerid
1175      * @return array
1176      */
1177     public function get_assessments_by_reviewer($reviewerid) {
1178         global $DB;
1180         $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1181         $authorfields   = user_picture::fields('author', null, 'authorid', 'author');
1182         $overbyfields   = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1183         $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields,
1184                        s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated,
1185                        s.timemodified AS submissionmodified
1186                   FROM {workshop_assessments} a
1187             INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1188             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1189             INNER JOIN {user} author ON (s.authorid = author.id)
1190              LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1191                  WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid";
1192         $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id);
1194         return $DB->get_records_sql($sql, $params);
1195     }
1197     /**
1198      * Get allocated assessments not graded yet by the given reviewer
1199      *
1200      * @see self::get_assessments_by_reviewer()
1201      * @param int $reviewerid the reviewer id
1202      * @param null|int|array $exclude optional assessment id (or list of them) to be excluded
1203      * @return array
1204      */
1205     public function get_pending_assessments_by_reviewer($reviewerid, $exclude = null) {
1207         $assessments = $this->get_assessments_by_reviewer($reviewerid);
1209         foreach ($assessments as $id => $assessment) {
1210             if (!is_null($assessment->grade)) {
1211                 unset($assessments[$id]);
1212                 continue;
1213             }
1214             if (!empty($exclude)) {
1215                 if (is_array($exclude) and in_array($id, $exclude)) {
1216                     unset($assessments[$id]);
1217                     continue;
1218                 } else if ($id == $exclude) {
1219                     unset($assessments[$id]);
1220                     continue;
1221                 }
1222             }
1223         }
1225         return $assessments;
1226     }
1228     /**
1229      * Allocate a submission to a user for review
1230      *
1231      * @param stdClass $submission Submission object with at least id property
1232      * @param int $reviewerid User ID
1233      * @param int $weight of the new assessment, from 0 to 16
1234      * @param bool $bulk repeated inserts into DB expected
1235      * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists
1236      */
1237     public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
1238         global $DB;
1240         if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
1241             return self::ALLOCATION_EXISTS;
1242         }
1244         $weight = (int)$weight;
1245         if ($weight < 0) {
1246             $weight = 0;
1247         }
1248         if ($weight > 16) {
1249             $weight = 16;
1250         }
1252         $now = time();
1253         $assessment = new stdclass();
1254         $assessment->submissionid           = $submission->id;
1255         $assessment->reviewerid             = $reviewerid;
1256         $assessment->timecreated            = $now;         // do not set timemodified here
1257         $assessment->weight                 = $weight;
1258         $assessment->feedbackauthorformat   = editors_get_preferred_format();
1259         $assessment->feedbackreviewerformat = editors_get_preferred_format();
1261         return $DB->insert_record('workshop_assessments', $assessment, true, $bulk);
1262     }
1264     /**
1265      * Delete assessment record or records
1266      *
1267      * @param mixed $id int|array assessment id or array of assessments ids
1268      * @return bool false if $id not a valid parameter, true otherwise
1269      */
1270     public function delete_assessment($id) {
1271         global $DB;
1273         // todo remove all given grades from workshop_grades;
1275         if (is_array($id)) {
1276             return $DB->delete_records_list('workshop_assessments', 'id', $id);
1277         } else {
1278             return $DB->delete_records('workshop_assessments', array('id' => $id));
1279         }
1280     }
1282     /**
1283      * Returns instance of grading strategy class
1284      *
1285      * @return stdclass Instance of a grading strategy
1286      */
1287     public function grading_strategy_instance() {
1288         global $CFG;    // because we require other libs here
1290         if (is_null($this->strategyinstance)) {
1291             $strategylib = dirname(__FILE__) . '/form/' . $this->strategy . '/lib.php';
1292             if (is_readable($strategylib)) {
1293                 require_once($strategylib);
1294             } else {
1295                 throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
1296             }
1297             $classname = 'workshop_' . $this->strategy . '_strategy';
1298             $this->strategyinstance = new $classname($this);
1299             if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) {
1300                 throw new coding_exception($classname . ' does not implement workshop_strategy interface');
1301             }
1302         }
1303         return $this->strategyinstance;
1304     }
1306     /**
1307      * Sets the current evaluation method to the given plugin.
1308      *
1309      * @param string $method the name of the workshopeval subplugin
1310      * @return bool true if successfully set
1311      * @throws coding_exception if attempting to set a non-installed evaluation method
1312      */
1313     public function set_grading_evaluation_method($method) {
1314         global $DB;
1316         $evaluationlib = dirname(__FILE__) . '/eval/' . $method . '/lib.php';
1318         if (is_readable($evaluationlib)) {
1319             $this->evaluationinstance = null;
1320             $this->evaluation = $method;
1321             $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id));
1322             return true;
1323         }
1325         throw new coding_exception('Attempt to set a non-existing evaluation method.');
1326     }
1328     /**
1329      * Returns instance of grading evaluation class
1330      *
1331      * @return stdclass Instance of a grading evaluation
1332      */
1333     public function grading_evaluation_instance() {
1334         global $CFG;    // because we require other libs here
1336         if (is_null($this->evaluationinstance)) {
1337             if (empty($this->evaluation)) {
1338                 $this->evaluation = 'best';
1339             }
1340             $evaluationlib = dirname(__FILE__) . '/eval/' . $this->evaluation . '/lib.php';
1341             if (is_readable($evaluationlib)) {
1342                 require_once($evaluationlib);
1343             } else {
1344                 // Fall back in case the subplugin is not available.
1345                 $this->evaluation = 'best';
1346                 $evaluationlib = dirname(__FILE__) . '/eval/' . $this->evaluation . '/lib.php';
1347                 if (is_readable($evaluationlib)) {
1348                     require_once($evaluationlib);
1349                 } else {
1350                     // Fall back in case the subplugin is not available any more.
1351                     throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
1352                 }
1353             }
1354             $classname = 'workshop_' . $this->evaluation . '_evaluation';
1355             $this->evaluationinstance = new $classname($this);
1356             if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) {
1357                 throw new coding_exception($classname . ' does not extend workshop_evaluation class');
1358             }
1359         }
1360         return $this->evaluationinstance;
1361     }
1363     /**
1364      * Returns instance of submissions allocator
1365      *
1366      * @param string $method The name of the allocation method, must be PARAM_ALPHA
1367      * @return stdclass Instance of submissions allocator
1368      */
1369     public function allocator_instance($method) {
1370         global $CFG;    // because we require other libs here
1372         $allocationlib = dirname(__FILE__) . '/allocation/' . $method . '/lib.php';
1373         if (is_readable($allocationlib)) {
1374             require_once($allocationlib);
1375         } else {
1376             throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
1377         }
1378         $classname = 'workshop_' . $method . '_allocator';
1379         return new $classname($this);
1380     }
1382     /**
1383      * @return moodle_url of this workshop's view page
1384      */
1385     public function view_url() {
1386         global $CFG;
1387         return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
1388     }
1390     /**
1391      * @return moodle_url of the page for editing this workshop's grading form
1392      */
1393     public function editform_url() {
1394         global $CFG;
1395         return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
1396     }
1398     /**
1399      * @return moodle_url of the page for previewing this workshop's grading form
1400      */
1401     public function previewform_url() {
1402         global $CFG;
1403         return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
1404     }
1406     /**
1407      * @param int $assessmentid The ID of assessment record
1408      * @return moodle_url of the assessment page
1409      */
1410     public function assess_url($assessmentid) {
1411         global $CFG;
1412         $assessmentid = clean_param($assessmentid, PARAM_INT);
1413         return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
1414     }
1416     /**
1417      * @param int $assessmentid The ID of assessment record
1418      * @return moodle_url of the example assessment page
1419      */
1420     public function exassess_url($assessmentid) {
1421         global $CFG;
1422         $assessmentid = clean_param($assessmentid, PARAM_INT);
1423         return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
1424     }
1426     /**
1427      * @return moodle_url of the page to view a submission, defaults to the own one
1428      */
1429     public function submission_url($id=null) {
1430         global $CFG;
1431         return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
1432     }
1434     /**
1435      * @param int $id example submission id
1436      * @return moodle_url of the page to view an example submission
1437      */
1438     public function exsubmission_url($id) {
1439         global $CFG;
1440         return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
1441     }
1443     /**
1444      * @param int $sid submission id
1445      * @param array $aid of int assessment ids
1446      * @return moodle_url of the page to compare assessments of the given submission
1447      */
1448     public function compare_url($sid, array $aids) {
1449         global $CFG;
1451         $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
1452         $i = 0;
1453         foreach ($aids as $aid) {
1454             $url->param("aid{$i}", $aid);
1455             $i++;
1456         }
1457         return $url;
1458     }
1460     /**
1461      * @param int $sid submission id
1462      * @param int $aid assessment id
1463      * @return moodle_url of the page to compare the reference assessments of the given example submission
1464      */
1465     public function excompare_url($sid, $aid) {
1466         global $CFG;
1467         return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
1468     }
1470     /**
1471      * @return moodle_url of the mod_edit form
1472      */
1473     public function updatemod_url() {
1474         global $CFG;
1475         return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
1476     }
1478     /**
1479      * @param string $method allocation method
1480      * @return moodle_url to the allocation page
1481      */
1482     public function allocation_url($method=null) {
1483         global $CFG;
1484         $params = array('cmid' => $this->cm->id);
1485         if (!empty($method)) {
1486             $params['method'] = $method;
1487         }
1488         return new moodle_url('/mod/workshop/allocation.php', $params);
1489     }
1491     /**
1492      * @param int $phasecode The internal phase code
1493      * @return moodle_url of the script to change the current phase to $phasecode
1494      */
1495     public function switchphase_url($phasecode) {
1496         global $CFG;
1497         $phasecode = clean_param($phasecode, PARAM_INT);
1498         return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
1499     }
1501     /**
1502      * @return moodle_url to the aggregation page
1503      */
1504     public function aggregate_url() {
1505         global $CFG;
1506         return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
1507     }
1509     /**
1510      * @return moodle_url of this workshop's toolbox page
1511      */
1512     public function toolbox_url($tool) {
1513         global $CFG;
1514         return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
1515     }
1517     /**
1518      * Workshop wrapper around {@see add_to_log()}
1519      * @deprecated since 2.7 Please use the provided event classes for logging actions.
1520      *
1521      * @param string $action to be logged
1522      * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends
1523      * @param mixed $info additional info, usually id in a table
1524      * @param bool $return true to return the arguments for add_to_log.
1525      * @return void|array array of arguments for add_to_log if $return is true
1526      */
1527     public function log($action, moodle_url $url = null, $info = null, $return = false) {
1528         debugging('The log method is now deprecated, please use event classes instead', DEBUG_DEVELOPER);
1530         if (is_null($url)) {
1531             $url = $this->view_url();
1532         }
1534         if (is_null($info)) {
1535             $info = $this->id;
1536         }
1538         $logurl = $this->log_convert_url($url);
1539         $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
1540         if ($return) {
1541             return $args;
1542         }
1543         call_user_func_array('add_to_log', $args);
1544     }
1546     /**
1547      * Is the given user allowed to create their submission?
1548      *
1549      * @param int $userid
1550      * @return bool
1551      */
1552     public function creating_submission_allowed($userid) {
1554         $now = time();
1555         $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1557         if ($this->latesubmissions) {
1558             if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) {
1559                 // late submissions are allowed in the submission and assessment phase only
1560                 return false;
1561             }
1562             if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1563                 // late submissions are not allowed before the submission start
1564                 return false;
1565             }
1566             return true;
1568         } else {
1569             if ($this->phase != self::PHASE_SUBMISSION) {
1570                 // submissions are allowed during the submission phase only
1571                 return false;
1572             }
1573             if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1574                 // if enabled, submitting is not allowed before the date/time defined in the mod_form
1575                 return false;
1576             }
1577             if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) {
1578                 // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed
1579                 return false;
1580             }
1581             return true;
1582         }
1583     }
1585     /**
1586      * Is the given user allowed to modify their existing submission?
1587      *
1588      * @param int $userid
1589      * @return bool
1590      */
1591     public function modifying_submission_allowed($userid) {
1593         $now = time();
1594         $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1596         if ($this->phase != self::PHASE_SUBMISSION) {
1597             // submissions can be edited during the submission phase only
1598             return false;
1599         }
1600         if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1601             // if enabled, re-submitting is not allowed before the date/time defined in the mod_form
1602             return false;
1603         }
1604         if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) {
1605             // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed
1606             return false;
1607         }
1608         return true;
1609     }
1611     /**
1612      * Is the given reviewer allowed to create/edit their assessments?
1613      *
1614      * @param int $userid
1615      * @return bool
1616      */
1617     public function assessing_allowed($userid) {
1619         if ($this->phase != self::PHASE_ASSESSMENT) {
1620             // assessing is allowed in the assessment phase only, unless the user is a teacher
1621             // providing additional assessment during the evaluation phase
1622             if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) {
1623                 return false;
1624             }
1625         }
1627         $now = time();
1628         $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1630         if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) {
1631             // if enabled, assessing is not allowed before the date/time defined in the mod_form
1632             return false;
1633         }
1634         if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) {
1635             // if enabled, assessing is not allowed after the date/time defined in the mod_form
1636             return false;
1637         }
1638         // here we go, assessing is allowed
1639         return true;
1640     }
1642     /**
1643      * Are reviewers allowed to create/edit their assessments of the example submissions?
1644      *
1645      * Returns null if example submissions are not enabled in this workshop. Otherwise returns
1646      * true or false. Note this does not check other conditions like the number of already
1647      * assessed examples, examples mode etc.
1648      *
1649      * @return null|bool
1650      */
1651     public function assessing_examples_allowed() {
1652         if (empty($this->useexamples)) {
1653             return null;
1654         }
1655         if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
1656             return true;
1657         }
1658         if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
1659             return true;
1660         }
1661         if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
1662             return true;
1663         }
1664         return false;
1665     }
1667     /**
1668      * Are the peer-reviews available to the authors?
1669      *
1670      * @return bool
1671      */
1672     public function assessments_available() {
1673         return $this->phase == self::PHASE_CLOSED;
1674     }
1676     /**
1677      * Switch to a new workshop phase
1678      *
1679      * Modifies the underlying database record. You should terminate the script shortly after calling this.
1680      *
1681      * @param int $newphase new phase code
1682      * @return bool true if success, false otherwise
1683      */
1684     public function switch_phase($newphase) {
1685         global $DB;
1687         $known = $this->available_phases_list();
1688         if (!isset($known[$newphase])) {
1689             return false;
1690         }
1692         if (self::PHASE_CLOSED == $newphase) {
1693             // push the grades into the gradebook
1694             $workshop = new stdclass();
1695             foreach ($this as $property => $value) {
1696                 $workshop->{$property} = $value;
1697             }
1698             $workshop->course     = $this->course->id;
1699             $workshop->cmidnumber = $this->cm->id;
1700             $workshop->modname    = 'workshop';
1701             workshop_update_grades($workshop);
1702         }
1704         $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
1705         $this->phase = $newphase;
1706         $eventdata = array(
1707             'objectid' => $this->id,
1708             'context' => $this->context,
1709             'other' => array(
1710                 'workshopphase' => $this->phase
1711             )
1712         );
1713         $event = \mod_workshop\event\phase_switched::create($eventdata);
1714         $event->trigger();
1715         return true;
1716     }
1718     /**
1719      * Saves a raw grade for submission as calculated from the assessment form fields
1720      *
1721      * @param array $assessmentid assessment record id, must exists
1722      * @param mixed $grade        raw percentual grade from 0.00000 to 100.00000
1723      * @return false|float        the saved grade
1724      */
1725     public function set_peer_grade($assessmentid, $grade) {
1726         global $DB;
1728         if (is_null($grade)) {
1729             return false;
1730         }
1731         $data = new stdclass();
1732         $data->id = $assessmentid;
1733         $data->grade = $grade;
1734         $data->timemodified = time();
1735         $DB->update_record('workshop_assessments', $data);
1736         return $grade;
1737     }
1739     /**
1740      * Prepares data object with all workshop grades to be rendered
1741      *
1742      * @param int $userid the user we are preparing the report for
1743      * @param int $groupid if non-zero, prepare the report for the given group only
1744      * @param int $page the current page (for the pagination)
1745      * @param int $perpage participants per page (for the pagination)
1746      * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
1747      * @param string $sorthow ASC|DESC
1748      * @return stdclass data for the renderer
1749      */
1750     public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
1751         global $DB;
1753         $canviewall     = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
1754         $isparticipant  = $this->is_participant($userid);
1756         if (!$canviewall and !$isparticipant) {
1757             // who the hell is this?
1758             return array();
1759         }
1761         if (!in_array($sortby, array('lastname','firstname','submissiontitle','submissiongrade','gradinggrade'))) {
1762             $sortby = 'lastname';
1763         }
1765         if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
1766             $sorthow = 'ASC';
1767         }
1769         // get the list of user ids to be displayed
1770         if ($canviewall) {
1771             $participants = $this->get_participants(false, $groupid);
1772         } else {
1773             // this is an ordinary workshop participant (aka student) - display the report just for him/her
1774             $participants = array($userid => (object)array('id' => $userid));
1775         }
1777         // we will need to know the number of all records later for the pagination purposes
1778         $numofparticipants = count($participants);
1780         if ($numofparticipants > 0) {
1781             // load all fields which can be used for sorting and paginate the records
1782             list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1783             $params['workshopid1'] = $this->id;
1784             $params['workshopid2'] = $this->id;
1785             $sqlsort = array();
1786             $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
1787             foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
1788                 $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
1789             }
1790             $sqlsort = implode(',', $sqlsort);
1791             $picturefields = user_picture::fields('u', array(), 'userid');
1792             $sql = "SELECT $picturefields, s.title AS submissiontitle, s.grade AS submissiongrade, ag.gradinggrade
1793                       FROM {user} u
1794                  LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)
1795                  LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)
1796                      WHERE u.id $participantids
1797                   ORDER BY $sqlsort";
1798             $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1799         } else {
1800             $participants = array();
1801         }
1803         // this will hold the information needed to display user names and pictures
1804         $userinfo = array();
1806         // get the user details for all participants to display
1807         $additionalnames = get_all_user_name_fields();
1808         foreach ($participants as $participant) {
1809             if (!isset($userinfo[$participant->userid])) {
1810                 $userinfo[$participant->userid]            = new stdclass();
1811                 $userinfo[$participant->userid]->id        = $participant->userid;
1812                 $userinfo[$participant->userid]->picture   = $participant->picture;
1813                 $userinfo[$participant->userid]->imagealt  = $participant->imagealt;
1814                 $userinfo[$participant->userid]->email     = $participant->email;
1815                 foreach ($additionalnames as $addname) {
1816                     $userinfo[$participant->userid]->$addname = $participant->$addname;
1817                 }
1818             }
1819         }
1821         // load the submissions details
1822         $submissions = $this->get_submissions(array_keys($participants));
1824         // get the user details for all moderators (teachers) that have overridden a submission grade
1825         foreach ($submissions as $submission) {
1826             if (!isset($userinfo[$submission->gradeoverby])) {
1827                 $userinfo[$submission->gradeoverby]            = new stdclass();
1828                 $userinfo[$submission->gradeoverby]->id        = $submission->gradeoverby;
1829                 $userinfo[$submission->gradeoverby]->picture   = $submission->overpicture;
1830                 $userinfo[$submission->gradeoverby]->imagealt  = $submission->overimagealt;
1831                 $userinfo[$submission->gradeoverby]->email     = $submission->overemail;
1832                 foreach ($additionalnames as $addname) {
1833                     $temp = 'over' . $addname;
1834                     $userinfo[$submission->gradeoverby]->$addname = $submission->$temp;
1835                 }
1836             }
1837         }
1839         // get the user details for all reviewers of the displayed participants
1840         $reviewers = array();
1842         if ($submissions) {
1843             list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
1844             list($sort, $sortparams) = users_order_by_sql('r');
1845             $picturefields = user_picture::fields('r', array(), 'reviewerid');
1846             $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,
1847                            $picturefields, s.id AS submissionid, s.authorid
1848                       FROM {workshop_assessments} a
1849                       JOIN {user} r ON (a.reviewerid = r.id)
1850                       JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1851                      WHERE a.submissionid $submissionids
1852                   ORDER BY a.weight DESC, $sort";
1853             $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
1854             foreach ($reviewers as $reviewer) {
1855                 if (!isset($userinfo[$reviewer->reviewerid])) {
1856                     $userinfo[$reviewer->reviewerid]            = new stdclass();
1857                     $userinfo[$reviewer->reviewerid]->id        = $reviewer->reviewerid;
1858                     $userinfo[$reviewer->reviewerid]->picture   = $reviewer->picture;
1859                     $userinfo[$reviewer->reviewerid]->imagealt  = $reviewer->imagealt;
1860                     $userinfo[$reviewer->reviewerid]->email     = $reviewer->email;
1861                     foreach ($additionalnames as $addname) {
1862                         $userinfo[$reviewer->reviewerid]->$addname = $reviewer->$addname;
1863                     }
1864                 }
1865             }
1866         }
1868         // get the user details for all reviewees of the displayed participants
1869         $reviewees = array();
1870         if ($participants) {
1871             list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
1872             list($sort, $sortparams) = users_order_by_sql('e');
1873             $params['workshopid'] = $this->id;
1874             $picturefields = user_picture::fields('e', array(), 'authorid');
1875             $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,
1876                            s.id AS submissionid, $picturefields
1877                       FROM {user} u
1878                       JOIN {workshop_assessments} a ON (a.reviewerid = u.id)
1879                       JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1880                       JOIN {user} e ON (s.authorid = e.id)
1881                      WHERE u.id $participantids AND s.workshopid = :workshopid
1882                   ORDER BY a.weight DESC, $sort";
1883             $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
1884             foreach ($reviewees as $reviewee) {
1885                 if (!isset($userinfo[$reviewee->authorid])) {
1886                     $userinfo[$reviewee->authorid]            = new stdclass();
1887                     $userinfo[$reviewee->authorid]->id        = $reviewee->authorid;
1888                     $userinfo[$reviewee->authorid]->picture   = $reviewee->picture;
1889                     $userinfo[$reviewee->authorid]->imagealt  = $reviewee->imagealt;
1890                     $userinfo[$reviewee->authorid]->email     = $reviewee->email;
1891                     foreach ($additionalnames as $addname) {
1892                         $userinfo[$reviewee->authorid]->$addname = $reviewee->$addname;
1893                     }
1894                 }
1895             }
1896         }
1898         // finally populate the object to be rendered
1899         $grades = $participants;
1901         foreach ($participants as $participant) {
1902             // set up default (null) values
1903             $grades[$participant->userid]->submissionid = null;
1904             $grades[$participant->userid]->submissiontitle = null;
1905             $grades[$participant->userid]->submissiongrade = null;
1906             $grades[$participant->userid]->submissiongradeover = null;
1907             $grades[$participant->userid]->submissiongradeoverby = null;
1908             $grades[$participant->userid]->submissionpublished = null;
1909             $grades[$participant->userid]->reviewedby = array();
1910             $grades[$participant->userid]->reviewerof = array();
1911         }
1912         unset($participants);
1913         unset($participant);
1915         foreach ($submissions as $submission) {
1916             $grades[$submission->authorid]->submissionid = $submission->id;
1917             $grades[$submission->authorid]->submissiontitle = $submission->title;
1918             $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
1919             $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
1920             $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
1921             $grades[$submission->authorid]->submissionpublished = $submission->published;
1922         }
1923         unset($submissions);
1924         unset($submission);
1926         foreach($reviewers as $reviewer) {
1927             $info = new stdclass();
1928             $info->userid = $reviewer->reviewerid;
1929             $info->assessmentid = $reviewer->assessmentid;
1930             $info->submissionid = $reviewer->submissionid;
1931             $info->grade = $this->real_grade($reviewer->grade);
1932             $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
1933             $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
1934             $info->weight = $reviewer->weight;
1935             $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
1936         }
1937         unset($reviewers);
1938         unset($reviewer);
1940         foreach($reviewees as $reviewee) {
1941             $info = new stdclass();
1942             $info->userid = $reviewee->authorid;
1943             $info->assessmentid = $reviewee->assessmentid;
1944             $info->submissionid = $reviewee->submissionid;
1945             $info->grade = $this->real_grade($reviewee->grade);
1946             $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
1947             $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
1948             $info->weight = $reviewee->weight;
1949             $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
1950         }
1951         unset($reviewees);
1952         unset($reviewee);
1954         foreach ($grades as $grade) {
1955             $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
1956         }
1958         $data = new stdclass();
1959         $data->grades = $grades;
1960         $data->userinfo = $userinfo;
1961         $data->totalcount = $numofparticipants;
1962         $data->maxgrade = $this->real_grade(100);
1963         $data->maxgradinggrade = $this->real_grading_grade(100);
1964         return $data;
1965     }
1967     /**
1968      * Calculates the real value of a grade
1969      *
1970      * @param float $value percentual value from 0 to 100
1971      * @param float $max   the maximal grade
1972      * @return string
1973      */
1974     public function real_grade_value($value, $max) {
1975         $localized = true;
1976         if (is_null($value) or $value === '') {
1977             return null;
1978         } elseif ($max == 0) {
1979             return 0;
1980         } else {
1981             return format_float($max * $value / 100, $this->gradedecimals, $localized);
1982         }
1983     }
1985     /**
1986      * Calculates the raw (percentual) value from a real grade
1987      *
1988      * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save
1989      * this value in a raw percentual form into DB
1990      * @param float $value given grade
1991      * @param float $max   the maximal grade
1992      * @return float       suitable to be stored as numeric(10,5)
1993      */
1994     public function raw_grade_value($value, $max) {
1995         if (is_null($value) or $value === '') {
1996             return null;
1997         }
1998         if ($max == 0 or $value < 0) {
1999             return 0;
2000         }
2001         $p = $value / $max * 100;
2002         if ($p > 100) {
2003             return $max;
2004         }
2005         return grade_floatval($p);
2006     }
2008     /**
2009      * Calculates the real value of grade for submission
2010      *
2011      * @param float $value percentual value from 0 to 100
2012      * @return string
2013      */
2014     public function real_grade($value) {
2015         return $this->real_grade_value($value, $this->grade);
2016     }
2018     /**
2019      * Calculates the real value of grade for assessment
2020      *
2021      * @param float $value percentual value from 0 to 100
2022      * @return string
2023      */
2024     public function real_grading_grade($value) {
2025         return $this->real_grade_value($value, $this->gradinggrade);
2026     }
2028     /**
2029      * Sets the given grades and received grading grades to null
2030      *
2031      * This does not clear the information about how the peers filled the assessment forms, but
2032      * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess
2033      * the allocated submissions.
2034      *
2035      * @return void
2036      */
2037     public function clear_assessments() {
2038         global $DB;
2040         $submissions = $this->get_submissions();
2041         if (empty($submissions)) {
2042             // no money, no love
2043             return;
2044         }
2045         $submissions = array_keys($submissions);
2046         list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED);
2047         $sql = "submissionid $sql";
2048         $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params);
2049         $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params);
2050     }
2052     /**
2053      * Sets the grades for submission to null
2054      *
2055      * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2056      * @return void
2057      */
2058     public function clear_submission_grades($restrict=null) {
2059         global $DB;
2061         $sql = "workshopid = :workshopid AND example = 0";
2062         $params = array('workshopid' => $this->id);
2064         if (is_null($restrict)) {
2065             // update all users - no more conditions
2066         } elseif (!empty($restrict)) {
2067             list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2068             $sql .= " AND authorid $usql";
2069             $params = array_merge($params, $uparams);
2070         } else {
2071             throw new coding_exception('Empty value is not a valid parameter here');
2072         }
2074         $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
2075     }
2077     /**
2078      * Calculates grades for submission for the given participant(s) and updates it in the database
2079      *
2080      * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2081      * @return void
2082      */
2083     public function aggregate_submission_grades($restrict=null) {
2084         global $DB;
2086         // fetch a recordset with all assessments to process
2087         $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
2088                        a.weight, a.grade
2089                   FROM {workshop_submissions} s
2090              LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id)
2091                  WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2092         $params = array('workshopid' => $this->id);
2094         if (is_null($restrict)) {
2095             // update all users - no more conditions
2096         } elseif (!empty($restrict)) {
2097             list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2098             $sql .= " AND s.authorid $usql";
2099             $params = array_merge($params, $uparams);
2100         } else {
2101             throw new coding_exception('Empty value is not a valid parameter here');
2102         }
2104         $sql .= ' ORDER BY s.id'; // this is important for bulk processing
2106         $rs         = $DB->get_recordset_sql($sql, $params);
2107         $batch      = array();    // will contain a set of all assessments of a single submission
2108         $previous   = null;       // a previous record in the recordset
2110         foreach ($rs as $current) {
2111             if (is_null($previous)) {
2112                 // we are processing the very first record in the recordset
2113                 $previous   = $current;
2114             }
2115             if ($current->submissionid == $previous->submissionid) {
2116                 // we are still processing the current submission
2117                 $batch[] = $current;
2118             } else {
2119                 // process all the assessments of a sigle submission
2120                 $this->aggregate_submission_grades_process($batch);
2121                 // and then start to process another submission
2122                 $batch      = array($current);
2123                 $previous   = $current;
2124             }
2125         }
2126         // do not forget to process the last batch!
2127         $this->aggregate_submission_grades_process($batch);
2128         $rs->close();
2129     }
2131     /**
2132      * Sets the aggregated grades for assessment to null
2133      *
2134      * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2135      * @return void
2136      */
2137     public function clear_grading_grades($restrict=null) {
2138         global $DB;
2140         $sql = "workshopid = :workshopid";
2141         $params = array('workshopid' => $this->id);
2143         if (is_null($restrict)) {
2144             // update all users - no more conditions
2145         } elseif (!empty($restrict)) {
2146             list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2147             $sql .= " AND userid $usql";
2148             $params = array_merge($params, $uparams);
2149         } else {
2150             throw new coding_exception('Empty value is not a valid parameter here');
2151         }
2153         $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
2154     }
2156     /**
2157      * Calculates grades for assessment for the given participant(s)
2158      *
2159      * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator.
2160      * The assessment weight is not taken into account here.
2161      *
2162      * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2163      * @return void
2164      */
2165     public function aggregate_grading_grades($restrict=null) {
2166         global $DB;
2168         // fetch a recordset with all assessments to process
2169         $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover,
2170                        ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade
2171                   FROM {workshop_assessments} a
2172             INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
2173              LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid)
2174                  WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2175         $params = array('workshopid' => $this->id);
2177         if (is_null($restrict)) {
2178             // update all users - no more conditions
2179         } elseif (!empty($restrict)) {
2180             list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2181             $sql .= " AND a.reviewerid $usql";
2182             $params = array_merge($params, $uparams);
2183         } else {
2184             throw new coding_exception('Empty value is not a valid parameter here');
2185         }
2187         $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing
2189         $rs         = $DB->get_recordset_sql($sql, $params);
2190         $batch      = array();    // will contain a set of all assessments of a single submission
2191         $previous   = null;       // a previous record in the recordset
2193         foreach ($rs as $current) {
2194             if (is_null($previous)) {
2195                 // we are processing the very first record in the recordset
2196                 $previous   = $current;
2197             }
2198             if ($current->reviewerid == $previous->reviewerid) {
2199                 // we are still processing the current reviewer
2200                 $batch[] = $current;
2201             } else {
2202                 // process all the assessments of a sigle submission
2203                 $this->aggregate_grading_grades_process($batch);
2204                 // and then start to process another reviewer
2205                 $batch      = array($current);
2206                 $previous   = $current;
2207             }
2208         }
2209         // do not forget to process the last batch!
2210         $this->aggregate_grading_grades_process($batch);
2211         $rs->close();
2212     }
2214     /**
2215      * Returns the mform the teachers use to put a feedback for the reviewer
2216      *
2217      * @param moodle_url $actionurl
2218      * @param stdClass $assessment
2219      * @param array $options editable, editableweight, overridablegradinggrade
2220      * @return workshop_feedbackreviewer_form
2221      */
2222     public function get_feedbackreviewer_form(moodle_url $actionurl, stdclass $assessment, $options=array()) {
2223         global $CFG;
2224         require_once(dirname(__FILE__) . '/feedbackreviewer_form.php');
2226         $current = new stdclass();
2227         $current->asid                      = $assessment->id;
2228         $current->weight                    = $assessment->weight;
2229         $current->gradinggrade              = $this->real_grading_grade($assessment->gradinggrade);
2230         $current->gradinggradeover          = $this->real_grading_grade($assessment->gradinggradeover);
2231         $current->feedbackreviewer          = $assessment->feedbackreviewer;
2232         $current->feedbackreviewerformat    = $assessment->feedbackreviewerformat;
2233         if (is_null($current->gradinggrade)) {
2234             $current->gradinggrade = get_string('nullgrade', 'workshop');
2235         }
2236         if (!isset($options['editable'])) {
2237             $editable = true;   // by default
2238         } else {
2239             $editable = (bool)$options['editable'];
2240         }
2242         // prepare wysiwyg editor
2243         $current = file_prepare_standard_editor($current, 'feedbackreviewer', array());
2245         return new workshop_feedbackreviewer_form($actionurl,
2246                 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2247                 'post', '', null, $editable);
2248     }
2250     /**
2251      * Returns the mform the teachers use to put a feedback for the author on their submission
2252      *
2253      * @param moodle_url $actionurl
2254      * @param stdClass $submission
2255      * @param array $options editable
2256      * @return workshop_feedbackauthor_form
2257      */
2258     public function get_feedbackauthor_form(moodle_url $actionurl, stdclass $submission, $options=array()) {
2259         global $CFG;
2260         require_once(dirname(__FILE__) . '/feedbackauthor_form.php');
2262         $current = new stdclass();
2263         $current->submissionid          = $submission->id;
2264         $current->published             = $submission->published;
2265         $current->grade                 = $this->real_grade($submission->grade);
2266         $current->gradeover             = $this->real_grade($submission->gradeover);
2267         $current->feedbackauthor        = $submission->feedbackauthor;
2268         $current->feedbackauthorformat  = $submission->feedbackauthorformat;
2269         if (is_null($current->grade)) {
2270             $current->grade = get_string('nullgrade', 'workshop');
2271         }
2272         if (!isset($options['editable'])) {
2273             $editable = true;   // by default
2274         } else {
2275             $editable = (bool)$options['editable'];
2276         }
2278         // prepare wysiwyg editor
2279         $current = file_prepare_standard_editor($current, 'feedbackauthor', array());
2281         return new workshop_feedbackauthor_form($actionurl,
2282                 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2283                 'post', '', null, $editable);
2284     }
2286     /**
2287      * Returns the information about the user's grades as they are stored in the gradebook
2288      *
2289      * The submission grade is returned for users with the capability mod/workshop:submit and the
2290      * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
2291      * user has the capability to view hidden grades, grades must be visible to be returned. Null
2292      * grades are not returned. If none grade is to be returned, this method returns false.
2293      *
2294      * @param int $userid the user's id
2295      * @return workshop_final_grades|false
2296      */
2297     public function get_gradebook_grades($userid) {
2298         global $CFG;
2299         require_once($CFG->libdir.'/gradelib.php');
2301         if (empty($userid)) {
2302             throw new coding_exception('User id expected, empty value given.');
2303         }
2305         // Read data via the Gradebook API
2306         $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
2308         $grades = new workshop_final_grades();
2310         if (has_capability('mod/workshop:submit', $this->context, $userid)) {
2311             if (!empty($gradebook->items[0]->grades)) {
2312                 $submissiongrade = reset($gradebook->items[0]->grades);
2313                 if (!is_null($submissiongrade->grade)) {
2314                     if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2315                         $grades->submissiongrade = $submissiongrade;
2316                     }
2317                 }
2318             }
2319         }
2321         if (has_capability('mod/workshop:peerassess', $this->context, $userid)) {
2322             if (!empty($gradebook->items[1]->grades)) {
2323                 $assessmentgrade = reset($gradebook->items[1]->grades);
2324                 if (!is_null($assessmentgrade->grade)) {
2325                     if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2326                         $grades->assessmentgrade = $assessmentgrade;
2327                     }
2328                 }
2329             }
2330         }
2332         if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
2333             return $grades;
2334         }
2336         return false;
2337     }
2339     /**
2340      * Return the editor options for the overall feedback for the author.
2341      *
2342      * @return array
2343      */
2344     public function overall_feedback_content_options() {
2345         return array(
2346             'subdirs' => 0,
2347             'maxbytes' => $this->overallfeedbackmaxbytes,
2348             'maxfiles' => $this->overallfeedbackfiles,
2349             'changeformat' => 1,
2350             'context' => $this->context,
2351         );
2352     }
2354     /**
2355      * Return the filemanager options for the overall feedback for the author.
2356      *
2357      * @return array
2358      */
2359     public function overall_feedback_attachment_options() {
2360         return array(
2361             'subdirs' => 1,
2362             'maxbytes' => $this->overallfeedbackmaxbytes,
2363             'maxfiles' => $this->overallfeedbackfiles,
2364             'return_types' => FILE_INTERNAL,
2365         );
2366     }
2368     ////////////////////////////////////////////////////////////////////////////////
2369     // Internal methods (implementation details)                                  //
2370     ////////////////////////////////////////////////////////////////////////////////
2372     /**
2373      * Given an array of all assessments of a single submission, calculates the final grade for this submission
2374      *
2375      * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade
2376      * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored.
2377      *
2378      * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
2379      * @return void
2380      */
2381     protected function aggregate_submission_grades_process(array $assessments) {
2382         global $DB;
2384         $submissionid   = null; // the id of the submission being processed
2385         $current        = null; // the grade currently saved in database
2386         $finalgrade     = null; // the new grade to be calculated
2387         $sumgrades      = 0;
2388         $sumweights     = 0;
2390         foreach ($assessments as $assessment) {
2391             if (is_null($submissionid)) {
2392                 // the id is the same in all records, fetch it during the first loop cycle
2393                 $submissionid = $assessment->submissionid;
2394             }
2395             if (is_null($current)) {
2396                 // the currently saved grade is the same in all records, fetch it during the first loop cycle
2397                 $current = $assessment->submissiongrade;
2398             }
2399             if (is_null($assessment->grade)) {
2400                 // this was not assessed yet
2401                 continue;
2402             }
2403             if ($assessment->weight == 0) {
2404                 // this does not influence the calculation
2405                 continue;
2406             }
2407             $sumgrades  += $assessment->grade * $assessment->weight;
2408             $sumweights += $assessment->weight;
2409         }
2410         if ($sumweights > 0 and is_null($finalgrade)) {
2411             $finalgrade = grade_floatval($sumgrades / $sumweights);
2412         }
2413         // check if the new final grade differs from the one stored in the database
2414         if (grade_floats_different($finalgrade, $current)) {
2415             // we need to save new calculation into the database
2416             $record = new stdclass();
2417             $record->id = $submissionid;
2418             $record->grade = $finalgrade;
2419             $record->timegraded = time();
2420             $DB->update_record('workshop_submissions', $record);
2421         }
2422     }
2424     /**
2425      * Given an array of all assessments done by a single reviewer, calculates the final grading grade
2426      *
2427      * This calculates the simple mean of the passed grading grades. If, however, the grading grade
2428      * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored.
2429      *
2430      * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade)
2431      * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time
2432      * @return void
2433      */
2434     protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
2435         global $DB;
2437         $reviewerid = null; // the id of the reviewer being processed
2438         $current    = null; // the gradinggrade currently saved in database
2439         $finalgrade = null; // the new grade to be calculated
2440         $agid       = null; // aggregation id
2441         $sumgrades  = 0;
2442         $count      = 0;
2444         if (is_null($timegraded)) {
2445             $timegraded = time();
2446         }
2448         foreach ($assessments as $assessment) {
2449             if (is_null($reviewerid)) {
2450                 // the id is the same in all records, fetch it during the first loop cycle
2451                 $reviewerid = $assessment->reviewerid;
2452             }
2453             if (is_null($agid)) {
2454                 // the id is the same in all records, fetch it during the first loop cycle
2455                 $agid = $assessment->aggregationid;
2456             }
2457             if (is_null($current)) {
2458                 // the currently saved grade is the same in all records, fetch it during the first loop cycle
2459                 $current = $assessment->aggregatedgrade;
2460             }
2461             if (!is_null($assessment->gradinggradeover)) {
2462                 // the grading grade for this assessment is overridden by a teacher
2463                 $sumgrades += $assessment->gradinggradeover;
2464                 $count++;
2465             } else {
2466                 if (!is_null($assessment->gradinggrade)) {
2467                     $sumgrades += $assessment->gradinggrade;
2468                     $count++;
2469                 }
2470             }
2471         }
2472         if ($count > 0) {
2473             $finalgrade = grade_floatval($sumgrades / $count);
2474         }
2476         // Event information.
2477         $params = array(
2478             'context' => $this->context,
2479             'courseid' => $this->course->id,
2480             'relateduserid' => $reviewerid
2481         );
2483         // check if the new final grade differs from the one stored in the database
2484         if (grade_floats_different($finalgrade, $current)) {
2485             $params['other'] = array(
2486                 'currentgrade' => $current,
2487                 'finalgrade' => $finalgrade
2488             );
2490             // we need to save new calculation into the database
2491             if (is_null($agid)) {
2492                 // no aggregation record yet
2493                 $record = new stdclass();
2494                 $record->workshopid = $this->id;
2495                 $record->userid = $reviewerid;
2496                 $record->gradinggrade = $finalgrade;
2497                 $record->timegraded = $timegraded;
2498                 $record->id = $DB->insert_record('workshop_aggregations', $record);
2499                 $params['objectid'] = $record->id;
2500                 $event = \mod_workshop\event\assessment_evaluated::create($params);
2501                 $event->trigger();
2502             } else {
2503                 $record = new stdclass();
2504                 $record->id = $agid;
2505                 $record->gradinggrade = $finalgrade;
2506                 $record->timegraded = $timegraded;
2507                 $DB->update_record('workshop_aggregations', $record);
2508                 $params['objectid'] = $agid;
2509                 $event = \mod_workshop\event\assessment_reevaluated::create($params);
2510                 $event->trigger();
2511             }
2512         }
2513     }
2515     /**
2516      * Returns SQL to fetch all enrolled users with the given capability in the current workshop
2517      *
2518      * The returned array consists of string $sql and the $params array. Note that the $sql can be
2519      * empty if a grouping is selected and it has no groups.
2520      *
2521      * The list is automatically restricted according to any availability restrictions
2522      * that apply to user lists (e.g. group, grouping restrictions).
2523      *
2524      * @param string $capability the name of the capability
2525      * @param bool $musthavesubmission ff true, return only users who have already submitted
2526      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2527      * @return array of (string)sql, (array)params
2528      */
2529     protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) {
2530         global $CFG;
2531         /** @var int static counter used to generate unique parameter holders */
2532         static $inc = 0;
2533         $inc++;
2535         // If the caller requests all groups and we are using a selected grouping,
2536         // recursively call this function for each group in the grouping (this is
2537         // needed because get_enrolled_sql only supports a single group).
2538         if (empty($groupid) and $this->cm->groupingid) {
2539             $groupingid = $this->cm->groupingid;
2540             $groupinggroupids = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
2541             $sql = array();
2542             $params = array();
2543             foreach ($groupinggroupids as $groupinggroupid) {
2544                 if ($groupinggroupid > 0) { // just in case in order not to fall into the endless loop
2545                     list($gsql, $gparams) = $this->get_users_with_capability_sql($capability, $musthavesubmission, $groupinggroupid);
2546                     $sql[] = $gsql;
2547                     $params = array_merge($params, $gparams);
2548                 }
2549             }
2550             $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql);
2551             return array($sql, $params);
2552         }
2554         list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true);
2556         $userfields = user_picture::fields('u');
2558         $sql = "SELECT $userfields
2559                   FROM {user} u
2560                   JOIN ($esql) je ON (je.id = u.id AND u.deleted = 0) ";
2562         if ($musthavesubmission) {
2563             $sql .= " JOIN {workshop_submissions} ws ON (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid{$inc}) ";
2564             $params['workshopid'.$inc] = $this->id;
2565         }
2567         // If the activity is restricted so that only certain users should appear
2568         // in user lists, integrate this into the same SQL.
2569         $info = new \core_availability\info_module($this->cm);
2570         list ($listsql, $listparams) = $info->get_user_list_sql(false);
2571         if ($listsql) {
2572             $sql .= " JOIN ($listsql) restricted ON restricted.id = u.id ";
2573             $params = array_merge($params, $listparams);
2574         }
2576         return array($sql, $params);
2577     }
2579     /**
2580      * Returns SQL statement that can be used to fetch all actively enrolled participants in the workshop
2581      *
2582      * @param bool $musthavesubmission if true, return only users who have already submitted
2583      * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2584      * @return array of (string)sql, (array)params
2585      */
2586     protected function get_participants_sql($musthavesubmission=false, $groupid=0) {
2588         list($sql1, $params1) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
2589         list($sql2, $params2) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
2591         if (empty($sql1) or empty($sql2)) {
2592             if (empty($sql1) and empty($sql2)) {
2593                 return array('', array());
2594             } else if (empty($sql1)) {
2595                 $sql = $sql2;
2596                 $params = $params2;
2597             } else {
2598                 $sql = $sql1;
2599                 $params = $params1;
2600             }
2601         } else {
2602             $sql = $sql1.PHP_EOL." UNION ".PHP_EOL.$sql2;
2603             $params = array_merge($params1, $params2);
2604         }
2606         return array($sql, $params);
2607     }
2609     /**
2610      * @return array of available workshop phases
2611      */
2612     protected function available_phases_list() {
2613         return array(
2614             self::PHASE_SETUP       => true,
2615             self::PHASE_SUBMISSION  => true,
2616             self::PHASE_ASSESSMENT  => true,
2617             self::PHASE_EVALUATION  => true,
2618             self::PHASE_CLOSED      => true,
2619         );
2620     }
2622     /**
2623      * Converts absolute URL to relative URL needed by {@see add_to_log()}
2624      *
2625      * @param moodle_url $url absolute URL
2626      * @return string
2627      */
2628     protected function log_convert_url(moodle_url $fullurl) {
2629         static $baseurl;
2631         if (!isset($baseurl)) {
2632             $baseurl = new moodle_url('/mod/workshop/');
2633             $baseurl = $baseurl->out();
2634         }
2636         return substr($fullurl->out(), strlen($baseurl));
2637     }
2638     
2639     /**
2640      * Resets this activity's content
2641      * @param array The reset data object.
2642      * @return bool True if the reset was successful, false if there was an error
2643      */
2644     public function reset_userdata($data) {
2645         $componentstr = get_string('modulenameplural', 'workshop');
2646         $status = array();
2647         $this->reset_submissions();
2648         $delaggregations = $DB->delete_records('workshop_aggregations', array('workshopid' => $this->id));
2649         $this->reset_allocators();
2650         $this->reset_evaluators();
2651         $this->reset_strategies();
2653         $events = $DB->get_records('event', array('modulename' => 'workshop', 'instance' => $this->id));\r
2654         foreach ($events as $event) {
2655             $event = calendar_event::load($event);
2656             $event->delete();\r
2657         }
2659         // Set the phase.
2660         // $DB->set_field('workshop', 'phase', 0, array('id' => $workshop->id));    // Left in to give option to switch back after discussion.
2661         $this->switch_phase(self::PHASE_SETUP);    // Use the API but we may not want to raise events about this....
2663         $status[] = array('component' => $componentstr, 'item' => get_string('resetworkshopall', 'workshop'), 'error' => false);
2664         return $status;
2665     }
2667     /**
2668      * Remove user content, including grades
2669      */
2670     protected function reset_submissions() {
2671         $submissions = $this->get_submissions();\r
2672         foreach ($submissions as $submission) {\r
2673             $this->delete_submission($submission);\r
2674         }
2675         // Clean up submission files.
2676         $fs = get_file_storage();
2677         $files = $fs->get_area_files($this->context, 'mod_workshop', 'submission_attachment', false);
2678         $numberfilestodelete = count($files);
2679         $numfilesdeleted = 0;
2680         foreach ($files as $file) {
2681              try {
2682                 $file->delete();
2683                 $numfilesdeleted += 1;
2684             }
2685             catch (Exception $exception) {
2686                 // The delete can fail if necessary it just leaves an orphan in the DB. The record its attached to will have rady been removed.
2687             }
2688         }
2689     }
2690     
2691     protected function reset_allocators() {
2692         $allocators = core_component::get_plugin_list('workshopallocation');
2693         foreach ($allocators as $allocator => $path) {\r
2694             require_once($path.'/lib.php');\r
2695             $classname = 'workshop_'.$allocator.'_allocator';\r
2696             call_user_func($classname.'::reset_user_data', $this->id);\r
2697         }
2698     }
2700     protected function reset_strategies() {
2701         $evaluators = core_component::get_plugin_list('workshopeval');
2702         foreach ($evaluators as $evaluator => $path) {\r
2703             require_once($path.'/lib.php');\r
2704             $classname = 'workshop_'.$evaluator.'_evaluation';\r
2705             call_user_func($classname.'::reset_user_data', $this->id);\r
2706         }
2707     }
2709     protected function reset_evaluators() {
2710         $evaluators = core_component::get_plugin_list('workshopeval');\r
2711         foreach ($evaluators as $evaluator => $path) {\r
2712             require_once($path.'/lib.php');\r
2713             $classname = 'workshop_'.$evaluator.'_evaluation';\r
2714             call_user_func($classname.'::reset_user_data', $this->id);\r
2715         }
2716     }
2719 ////////////////////////////////////////////////////////////////////////////////
2720 // Renderable components
2721 ////////////////////////////////////////////////////////////////////////////////
2723 /**
2724  * Represents the user planner tool
2725  *
2726  * Planner contains list of phases. Each phase contains list of tasks. Task is a simple object with
2727  * title, link and completed (true/false/null logic).
2728  */
2729 class workshop_user_plan implements renderable {
2731     /** @var int id of the user this plan is for */
2732     public $userid;
2733     /** @var workshop */
2734     public $workshop;
2735     /** @var array of (stdclass)tasks */
2736     public $phases = array();
2737     /** @var null|array of example submissions to be assessed by the planner owner */
2738     protected $examples = null;
2740     /**
2741      * Prepare an individual workshop plan for the given user.
2742      *
2743      * @param workshop $workshop instance
2744      * @param int $userid whom the plan is prepared for
2745      */
2746     public function __construct(workshop $workshop, $userid) {
2747         global $DB;
2749         $this->workshop = $workshop;
2750         $this->userid   = $userid;
2752         //---------------------------------------------------------
2753         // * SETUP | submission | assessment | evaluation | closed
2754         //---------------------------------------------------------
2755         $phase = new stdclass();
2756         $phase->title = get_string('phasesetup', 'workshop');
2757         $phase->tasks = array();
2758         if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2759             $task = new stdclass();
2760             $task->title = get_string('taskintro', 'workshop');
2761             $task->link = $workshop->updatemod_url();
2762             $task->completed = !(trim($workshop->intro) == '');
2763             $phase->tasks['intro'] = $task;
2764         }
2765         if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2766             $task = new stdclass();
2767             $task->title = get_string('taskinstructauthors', 'workshop');
2768             $task->link = $workshop->updatemod_url();
2769             $task->completed = !(trim($workshop->instructauthors) == '');
2770             $phase->tasks['instructauthors'] = $task;
2771         }
2772         if (has_capability('mod/workshop:editdimensions', $workshop->context, $userid)) {
2773             $task = new stdclass();
2774             $task->title = get_string('editassessmentform', 'workshop');
2775             $task->link = $workshop->editform_url();
2776             if ($workshop->grading_strategy_instance()->form_ready()) {
2777                 $task->completed = true;
2778             } elseif ($workshop->phase > workshop::PHASE_SETUP) {
2779                 $task->completed = false;
2780             }
2781             $phase->tasks['editform'] = $task;
2782         }
2783         if ($workshop->useexamples and has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2784             $task = new stdclass();
2785             $task->title = get_string('prepareexamples', 'workshop');
2786             if ($DB->count_records('workshop_submissions', array('example' => 1, 'workshopid' => $workshop->id)) > 0) {
2787                 $task->completed = true;
2788             } elseif ($workshop->phase > workshop::PHASE_SETUP) {
2789                 $task->completed = false;
2790             }
2791             $phase->tasks['prepareexamples'] = $task;
2792         }
2793         if (empty($phase->tasks) and $workshop->phase == workshop::PHASE_SETUP) {
2794             // if we are in the setup phase and there is no task (typical for students), let us
2795             // display some explanation what is going on
2796             $task = new stdclass();
2797             $task->title = get_string('undersetup', 'workshop');
2798             $task->completed = 'info';
2799             $phase->tasks['setupinfo'] = $task;
2800         }
2801         $this->phases[workshop::PHASE_SETUP] = $phase;
2803         //---------------------------------------------------------
2804         // setup | * SUBMISSION | assessment | evaluation | closed
2805         //---------------------------------------------------------
2806         $phase = new stdclass();
2807         $phase->title = get_string('phasesubmission', 'workshop');
2808         $phase->tasks = array();
2809         if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
2810             $task = new stdclass();
2811             $task->title = get_string('taskinstructreviewers', 'workshop');
2812             $task->link = $workshop->updatemod_url();
2813             if (trim($workshop->instructreviewers)) {
2814                 $task->completed = true;
2815             } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2816                 $task->completed = false;
2817             }
2818             $phase->tasks['instructreviewers'] = $task;
2819         }
2820         if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION
2821                 and has_capability('mod/workshop:submit', $workshop->context, $userid, false)
2822                     and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2823             $task = new stdclass();
2824             $task->title = get_string('exampleassesstask', 'workshop');
2825             $examples = $this->get_examples();
2826             $a = new stdclass();
2827             $a->expected = count($examples);
2828             $a->assessed = 0;
2829             foreach ($examples as $exampleid => $example) {
2830                 if (!is_null($example->grade)) {
2831                     $a->assessed++;
2832                 }
2833             }
2834             $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
2835             if ($a->assessed == $a->expected) {
2836                 $task->completed = true;
2837             } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2838                 $task->completed = false;
2839             }
2840             $phase->tasks['examples'] = $task;
2841         }
2842         if (has_capability('mod/workshop:submit', $workshop->context, $userid, false)) {
2843             $task = new stdclass();
2844             $task->title = get_string('tasksubmit', 'workshop');
2845             $task->link = $workshop->submission_url();
2846             if ($DB->record_exists('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0, 'authorid'=>$userid))) {
2847                 $task->completed = true;
2848             } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
2849                 $task->completed = false;
2850             } else {
2851                 $task->completed = null;    // still has a chance to submit
2852             }
2853             $phase->tasks['submit'] = $task;
2854         }
2855         if (has_capability('mod/workshop:allocate', $workshop->context, $userid)) {
2856             if ($workshop->phaseswitchassessment) {
2857                 $task = new stdClass();
2858                 $allocator = $DB->get_record('workshopallocation_scheduled', array('workshopid' => $workshop->id));
2859                 if (empty($allocator)) {
2860                     $task->completed = false;
2861                 } else if ($allocator->enabled and is_null($allocator->resultstatus)) {
2862                     $task->completed = true;
2863                 } else if ($workshop->submissionend > time()) {
2864                     $task->completed = null;
2865                 } else {
2866                     $task->completed = false;
2867                 }
2868                 $task->title = get_string('setup', 'workshopallocation_scheduled');
2869                 $task->link = $workshop->allocation_url('scheduled');
2870                 $phase->tasks['allocatescheduled'] = $task;
2871             }
2872             $task = new stdclass();
2873             $task->title = get_string('allocate', 'workshop');
2874             $task->link = $workshop->allocation_url();
2875             $numofauthors = $workshop->count_potential_authors(false);
2876             $numofsubmissions = $DB->count_records('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0));
2877             $sql = 'SELECT COUNT(s.id) AS nonallocated
2878                       FROM {workshop_submissions} s
2879                  LEFT JOIN {workshop_assessments} a ON (a.submissionid=s.id)
2880                      WHERE s.workshopid = :workshopid AND s.example=0 AND a.submissionid IS NULL';
2881             $params['workshopid'] = $workshop->id;
2882             $numnonallocated = $DB->count_records_sql($sql, $params);
2883             if ($numofsubmissions == 0) {
2884                 $task->completed = null;
2885             } elseif ($numnonallocated == 0) {
2886                 $task->completed = true;
2887             } elseif ($workshop->phase > workshop::PHASE_SUBMISSION) {
2888                 $task->completed = false;
2889             } else {
2890                 $task->completed = null;    // still has a chance to allocate
2891             }
2892             $a = new stdclass();
2893             $a->expected    = $numofauthors;
2894             $a->submitted   = $numofsubmissions;
2895             $a->allocate    = $numnonallocated;
2896             $task->details  = get_string('allocatedetails', 'workshop', $a);
2897             unset($a);
2898             $phase->tasks['allocate'] = $task;
2900             if ($numofsubmissions < $numofauthors and $workshop->phase >= workshop::PHASE_SUBMISSION) {
2901                 $task = new stdclass();
2902                 $task->title = get_string('someuserswosubmission', 'workshop');
2903                 $task->completed = 'info';
2904                 $phase->tasks['allocateinfo'] = $task;
2905             }
2907         }
2908         if ($workshop->submissionstart) {
2909             $task = new stdclass();
2910             $task->title = get_string('submissionstartdatetime', 'workshop', workshop::timestamp_formats($workshop->submissionstart));
2911             $task->completed = 'info';
2912             $phase->tasks['submissionstartdatetime'] = $task;
2913         }
2914         if ($workshop->submissionend) {
2915             $task = new stdclass();
2916             $task->title = get_string('submissionenddatetime', 'workshop', workshop::timestamp_formats($workshop->submissionend));
2917             $task->completed = 'info';
2918             $phase->tasks['submissionenddatetime'] = $task;
2919         }
2920         if (($workshop->submissionstart < time()) and $workshop->latesubmissions) {
2921             $task = new stdclass();
2922             $task->title = get_string('latesubmissionsallowed', 'workshop');
2923             $task->completed = 'info';
2924             $phase->tasks['latesubmissionsallowed'] = $task;
2925         }
2926         if (isset($phase->tasks['submissionstartdatetime']) or isset($phase->tasks['submissionenddatetime'])) {
2927             if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
2928                 $task = new stdclass();
2929                 $task->title = get_string('deadlinesignored', 'workshop');
2930                 $task->completed = 'info';
2931                 $phase->tasks['deadlinesignored'] = $task;
2932             }
2933         }
2934         $this->phases[workshop::PHASE_SUBMISSION] = $phase;
2936         //---------------------------------------------------------
2937         // setup | submission | * ASSESSMENT | evaluation | closed
2938         //---------------------------------------------------------
2939         $phase = new stdclass();
2940         $phase->title = get_string('phaseassessment', 'workshop');
2941         $phase->tasks = array();
2942         $phase->isreviewer = has_capability('mod/workshop:peerassess', $workshop->context, $userid);
2943         if ($workshop->phase == workshop::PHASE_SUBMISSION and $workshop->phaseswitchassessment
2944                 and has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
2945             $task = new stdClass();
2946             $task->title = get_string('switchphase30auto', 'mod_workshop', workshop::timestamp_formats($workshop->submissionend));
2947             $task->completed = 'info';
2948             $phase->tasks['autoswitchinfo'] = $task;
2949         }
2950         if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_ASSESSMENT
2951                 and $phase->isreviewer and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
2952             $task = new stdclass();
2953             $task->title = get_string('exampleassesstask', 'workshop');
2954             $examples = $workshop->get_examples_for_reviewer($userid);
2955             $a = new stdclass();
2956             $a->expected = count($examples);
2957             $a->assessed = 0;
2958             foreach ($examples as $exampleid => $example) {
2959                 if (!is_null($example->grade)) {
2960                     $a->assessed++;
2961                 }
2962             }
2963             $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
2964             if ($a->assessed == $a->expected) {
2965                 $task->completed = true;
2966             } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
2967                 $task->completed = false;
2968             }
2969             $phase->tasks['examples'] = $task;
2970         }
2971         if (empty($phase->tasks['examples']) or !empty($phase->tasks['examples']->completed)) {
2972             $phase->assessments = $workshop->get_assessments_by_reviewer($userid);
2973             $numofpeers     = 0;    // number of allocated peer-assessments
2974             $numofpeerstodo = 0;    // number of peer-assessments to do
2975             $numofself      = 0;    // number of allocated self-assessments - should be 0 or 1
2976             $numofselftodo  = 0;    // number of self-assessments to do - should be 0 or 1
2977             foreach ($phase->assessments as $a) {
2978                 if ($a->authorid == $userid) {
2979                     $numofself++;
2980                     if (is_null($a->grade)) {
2981                         $numofselftodo++;
2982                     }
2983                 } else {
2984                     $numofpeers++;
2985                     if (is_null($a->grade)) {
2986                         $numofpeerstodo++;
2987                     }
2988                 }
2989             }
2990             unset($a);
2991             if ($numofpeers) {
2992                 $task = new stdclass();
2993                 if ($numofpeerstodo == 0) {
2994                     $task->completed = true;
2995                 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
2996                     $task->completed = false;
2997                 }
2998                 $a = new stdclass();
2999                 $a->total = $numofpeers;
3000                 $a->todo  = $numofpeerstodo;
3001                 $task->title = get_string('taskassesspeers', 'workshop');
3002                 $task->details = get_string('taskassesspeersdetails', 'workshop', $a);
3003                 unset($a);
3004                 $phase->tasks['assesspeers'] = $task;
3005             }
3006             if ($workshop->useselfassessment and $numofself) {
3007                 $task = new stdclass();
3008                 if ($numofselftodo == 0) {
3009                     $task->completed = true;
3010                 } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3011                     $task->completed = false;
3012                 }
3013                 $task->title = get_string('taskassessself', 'workshop');
3014                 $phase->tasks['assessself'] = $task;
3015             }
3016         }
3017         if ($workshop->assessmentstart) {
3018             $task = new stdclass();
3019             $task->title = get_string('assessmentstartdatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentstart));
3020             $task->completed = 'info';
3021             $phase->tasks['assessmentstartdatetime'] = $task;
3022         }
3023         if ($workshop->assessmentend) {
3024             $task = new stdclass();
3025             $task->title = get_string('assessmentenddatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentend));
3026             $task->completed = 'info';
3027             $phase->tasks['assessmentenddatetime'] = $task;
3028         }
3029         if (isset($phase->tasks['assessmentstartdatetime']) or isset($phase->tasks['assessmentenddatetime'])) {
3030             if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
3031                 $task = new stdclass();
3032                 $task->title = get_string('deadlinesignored', 'workshop');
3033                 $task->completed = 'info';
3034                 $phase->tasks['deadlinesignored'] = $task;
3035             }
3036         }
3037         $this->phases[workshop::PHASE_ASSESSMENT] = $phase;
3039         //---------------------------------------------------------
3040         // setup | submission | assessment | * EVALUATION | closed
3041         //---------------------------------------------------------
3042         $phase = new stdclass();
3043         $phase->title = get_string('phaseevaluation', 'workshop');
3044         $phase->tasks = array();
3045         if (has_capability('mod/workshop:overridegrades', $workshop->context)) {
3046             $expected = $workshop->count_potential_authors(false);
3047             $calculated = $DB->count_records_select('workshop_submissions',
3048                     'workshopid = ? AND (grade IS NOT NULL OR gradeover IS NOT NULL)', array($workshop->id));
3049             $task = new stdclass();
3050             $task->title = get_string('calculatesubmissiongrades', 'workshop');
3051             $a = new stdclass();
3052             $a->expected    = $expected;
3053             $a->calculated  = $calculated;
3054             $task->details  = get_string('calculatesubmissiongradesdetails', 'workshop', $a);
3055             if ($calculated >= $expected) {
3056                 $task->completed = true;
3057             } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
3058                 $task->completed = false;
3059             }
3060             $phase->tasks['calculatesubmissiongrade'] = $task;
3062             $expected = $workshop->count_potential_reviewers(false);
3063             $calculated = $DB->count_records_select('workshop_aggregations',
3064                     'workshopid = ? AND gradinggrade IS NOT NULL', array($workshop->id));
3065             $task = new stdclass();
3066             $task->title = get_string('calculategradinggrades', 'workshop');
3067             $a = new stdclass();
3068             $a->expected    = $expected;
3069             $a->calculated  = $calculated;
3070             $task->details  = get_string('calculategradinggradesdetails', 'workshop', $a);
3071             if ($calculated >= $expected) {
3072                 $task->completed = true;
3073             } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
3074                 $task->completed = false;
3075             }
3076             $phase->tasks['calculategradinggrade'] = $task;
3078         } elseif ($workshop->phase == workshop::PHASE_EVALUATION) {
3079             $task = new stdclass();
3080             $task->title = get_string('evaluategradeswait', 'workshop');
3081             $task->completed = 'info';
3082             $phase->tasks['evaluateinfo'] = $task;
3083         }
3085         if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3086             $task = new stdclass();
3087             $task->title = get_string('taskconclusion', 'workshop');
3088             $task->link = $workshop->updatemod_url();
3089             if (trim($workshop->conclusion)) {
3090                 $task->completed = true;
3091             } elseif ($workshop->phase >= workshop::PHASE_EVALUATION) {
3092                 $task->completed = false;
3093             }
3094             $phase->tasks['conclusion'] = $task;
3095         }
3097         $this->phases[workshop::PHASE_EVALUATION] = $phase;
3099         //---------------------------------------------------------
3100         // setup | submission | assessment | evaluation | * CLOSED
3101         //---------------------------------------------------------
3102         $phase = new stdclass();
3103         $phase->title = get_string('phaseclosed', 'workshop');
3104         $phase->tasks = array();
3105         $this->phases[workshop::PHASE_CLOSED] = $phase;
3107         // Polish data, set default values if not done explicitly
3108         foreach ($this->phases as $phasecode => $phase) {
3109             $phase->title       = isset($phase->title)      ? $phase->title     : '';
3110             $phase->tasks       = isset($phase->tasks)      ? $phase->tasks     : array();
3111             if ($phasecode == $workshop->phase) {
3112                 $phase->active = true;
3113             } else {
3114                 $phase->active = false;
3115             }
3116             if (!isset($phase->actions)) {
3117                 $phase->actions = array();
3118             }
3120             foreach ($phase->tasks as $taskcode => $task) {
3121                 $task->title        = isset($task->title)       ? $task->title      : '';
3122                 $task->link         = isset($task->link)        ? $task->link       : null;
3123                 $task->details      = isset($task->details)     ? $task->details    : '';
3124                 $task->completed    = isset($task->completed)   ? $task->completed  : null;
3125             }
3126         }
3128         // Add phase switching actions
3129         if (has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
3130             foreach ($this->phases as $phasecode => $phase) {
3131                 if (! $phase->active) {
3132                     $action = new stdclass();
3133                     $action->type = 'switchphase';
3134                     $action->url  = $workshop->switchphase_url($phasecode);
3135                     $phase->actions[] = $action;
3136                 }
3137             }
3138         }
3139     }
3141     /**
3142      * Returns example submissions to be assessed by the owner of the planner
3143      *
3144      * This is here to cache the DB query because the same list is needed later in view.php
3145      *
3146      * @see workshop::get_examples_for_reviewer() for the format of returned value
3147      * @return array
3148      */
3149     public function get_examples() {
3150         if (is_null($this->examples)) {
3151             $this->examples = $this->workshop->get_examples_for_reviewer($this->userid);
3152         }
3153         return $this->examples;
3154     }
3157 /**
3158  * Common base class for submissions and example submissions rendering
3159  *
3160  * Subclasses of this class convert raw submission record from
3161  * workshop_submissions table (as returned by {@see workshop::get_submission_by_id()}
3162  * for example) into renderable objects.
3163  */
3164 abstract class workshop_submission_base {
3166     /** @var bool is the submission anonymous (i.e. contains author information) */
3167     protected $anonymous;
3169     /* @var array of columns from workshop_submissions that are assigned as properties */
3170     protected $fields = array();
3172     /** @var workshop */
3173     protected $workshop;
3175     /**
3176      * Copies the properties of the given database record into properties of $this instance
3177      *
3178      * @param workshop $workshop
3179      * @param stdClass $submission full record
3180      * @param bool $showauthor show the author-related information
3181      * @param array $options additional properties
3182      */
3183     public function __construct(workshop $workshop, stdClass $submission, $showauthor = false) {
3185         $this->workshop = $workshop;
3187         foreach ($this->fields as $field) {
3188             if (!property_exists($submission, $field)) {
3189                 throw new coding_exception('Submission record must provide public property ' . $field);
3190             }
3191             if (!property_exists($this, $field)) {
3192                 throw new coding_exception('Renderable component must accept public property ' . $field);
3193             }
3194             $this->{$field} = $submission->{$field};
3195         }
3197         if ($showauthor) {
3198             $this->anonymous = false;
3199         } else {
3200             $this->anonymize();
3201         }
3202     }
3204     /**
3205      * Unsets all author-related properties so that the renderer does not have access to them
3206      *
3207      * Usually this is called by the contructor but can be called explicitely, too.
3208      */
3209     public function anonymize() {
3210         $authorfields = explode(',', user_picture::fields());
3211         foreach ($authorfields as $field) {
3212             $prefixedusernamefield = 'author' . $field;
3213             unset($this->{$prefixedusernamefield});
3214         }
3215         $this->anonymous = true;
3216     }
3218     /**
3219      * Does the submission object contain author-related information?
3220      *
3221      * @return null|boolean
3222      */
3223     public function is_anonymous() {
3224         return $this->anonymous;
3225     }
3228 /**
3229  * Renderable object containing a basic set of information needed to display the submission summary
3230  *
3231  * @see workshop_renderer::render_workshop_submission_summary
3232  */
3233 class workshop_submission_summary extends workshop_submission_base implements renderable {
3235     /** @var int */
3236     public $id;
3237     /** @var string */
3238     public $title;
3239     /** @var string graded|notgraded */
3240     public $status;
3241     /** @var int */
3242     public $timecreated;
3243     /** @var int */
3244     public $timemodified;
3245     /** @var int */
3246     public $authorid;
3247     /** @var string */
3248     public $authorfirstname;
3249     /** @var string */
3250     public $authorlastname;
3251     /** @var string */
3252     public $authorfirstnamephonetic;
3253     /** @var string */
3254     public $authorlastnamephonetic;
3255     /** @var string */
3256     public $authormiddlename;
3257     /** @var string */
3258     public $authoralternatename;
3259     /** @var int */
3260     public $authorpicture;
3261     /** @var string */
3262     public $authorimagealt;
3263     /** @var string */
3264     public $authoremail;
3265     /** @var moodle_url to display submission */
3266     public $url;
3268     /**
3269      * @var array of columns from workshop_submissions that are assigned as properties
3270      * of instances of this class
3271      */
3272     protected $fields = array(
3273         'id', 'title', 'timecreated', 'timemodified',
3274         'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
3275         'authormiddlename', 'authoralternatename', 'authorpicture',
3276         'authorimagealt', 'authoremail');
3279 /**
3280  * Renderable object containing all the information needed to display the submission
3281  *
3282  * @see workshop_renderer::render_workshop_submission()
3283  */
3284 class workshop_submission extends workshop_submission_summary implements renderable {
3286     /** @var string */
3287     public $content;
3288     /** @var int */
3289     public $contentformat;
3290     /** @var bool */
3291     public $contenttrust;
3292     /** @var array */
3293     public $attachment;
3295     /**
3296      * @var array of columns from workshop_submissions that are assigned as properties
3297      * of instances of this class
3298      */
3299     protected $fields = array(
3300         'id', 'title', 'timecreated', 'timemodified', 'content', 'contentformat', 'contenttrust',
3301         'attachment', 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
3302         'authormiddlename', 'authoralternatename', 'authorpicture', 'authorimagealt', 'authoremail');
3305 /**
3306  * Renderable object containing a basic set of information needed to display the example submission summary
3307  *
3308  * @see workshop::prepare_example_summary()
3309  * @see workshop_renderer::render_workshop_example_submission_summary()
3310  */
3311 class workshop_example_submission_summary extends workshop_submission_base implements renderable {
3313     /** @var int */
3314     public $id;
3315     /** @var string */
3316     public $title;
3317     /** @var string graded|notgraded */
3318     public $status;
3319     /** @var stdClass */
3320     public $gradeinfo;
3321     /** @var moodle_url */
3322     public $url;
3323     /** @var moodle_url */
3324     public $editurl;
3325     /** @var string */
3326     public $assesslabel;
3327     /** @var moodle_url */
3328     public $assessurl;
3329     /** @var bool must be set explicitly by the caller */
3330     public $editable = false;
3332     /**
3333      * @var array of columns from workshop_submissions that are assigned as properties
3334      * of instances of this class
3335      */
3336     protected $fields = array('id', 'title');
3338     /**
3339      * Example submissions are always anonymous
3340      *
3341      * @return true
3342      */
3343     public function is_anonymous() {
3344         return true;
3345     }
3348 /**
3349  * Renderable object containing all the information needed to display the example submission
3350  *
3351  * @see workshop_renderer::render_workshop_example_submission()
3352  */
3353 class workshop_example_submission extends workshop_example_submission_summary implements renderable {
3355     /** @var string */
3356     public $content;
3357     /** @var int */
3358     public $contentformat;
3359     /** @var bool */
3360     public $contenttrust;
3361     /** @var array */
3362     public $attachment;
3364     /**
3365      * @var array of columns from workshop_submissions that are assigned as properties
3366      * of instances of this class
3367      */
3368     protected $fields = array('id', 'title', 'content', 'contentformat', 'contenttrust', 'attachment');
3372 /**
3373  * Common base class for assessments rendering
3374  *
3375  * Subclasses of this class convert raw assessment record from
3376  * workshop_assessments table (as returned by {@see workshop::get_assessment_by_id()}
3377  * for example) into renderable objects.
3378  */
3379 abstract class workshop_assessment_base {
3381     /** @var string the optional title of the assessment */
3382     public $title = '';
3384     /** @var workshop_assessment_form $form as returned by {@link workshop_strategy::get_assessment_form()} */
3385     public $form;
3387     /** @var moodle_url */
3388     public $url;
3390     /** @var float|null the real received grade */
3391     public $realgrade = null;
3393     /** @var float the real maximum grade */
3394     public $maxgrade;
3396     /** @var stdClass|null reviewer user info */
3397     public $reviewer = null;
3399     /** @var stdClass|null assessed submission's author user info */
3400     public $author = null;
3402     /** @var array of actions */
3403     public $actions = array();
3405     /* @var array of columns that are assigned as properties */
3406     protected $fields = array();
3408     /** @var workshop */
3409     protected $workshop;
3411     /**
3412      * Copies the properties of the given database record into properties of $this instance
3413      *
3414      * The $options keys are: showreviewer, showauthor
3415      * @param workshop $workshop
3416      * @param stdClass $assessment full record
3417      * @param array $options additional properties
3418      */
3419     public function __construct(workshop $workshop, stdClass $record, array $options = array()) {
3421         $this->workshop = $workshop;
3422         $this->validate_raw_record($record);
3424         foreach ($this->fields as $field) {
3425             if (!property_exists($record, $field)) {
3426                 throw new coding_exception('Assessment record must provide public property ' . $field);
3427             }
3428             if (!property_exists($this, $field)) {
3429                 throw new coding_exception('Renderable component must accept public property ' . $field);
3430             }
3431             $this->{$field} = $record->{$field};
3432         }
3434         if (!empty($options['showreviewer'])) {
3435             $this->reviewer = user_picture::unalias($record, null, 'revieweridx', 'reviewer');
3436         }
3438         if (!empty($options['showauthor'])) {
3439             $this->author = user_picture::unalias($record, null, 'authorid', 'author');
3440         }
3441     }
3443     /**
3444      * Adds a new action
3445      *
3446      * @param moodle_url $url action URL
3447      * @param string $label action label
3448      * @param string $method get|post
3449      */
3450     public function add_action(moodle_url $url, $label, $method = 'get') {
3452         $action = new stdClass();
3453         $action->url = $url;
3454         $action->label = $label;
3455         $action->method = $method;
3457         $this->actions[] = $action;
3458     }
3460     /**
3461      * Makes sure that we can cook the renderable component from the passed raw database record
3462      *
3463      * @param stdClass $assessment full assessment record
3464      * @throws coding_exception if the caller passed unexpected data
3465      */
3466     protected function validate_raw_record(stdClass $record) {
3467         // nothing to do here
3468     }
3472 /**
3473  * Represents a rendarable full assessment
3474  */
3475 class workshop_assessment extends workshop_assessment_base implements renderable {
3477     /** @var int */
3478     public $id;
3480     /** @var int */
3481     public $submissionid;
3483     /** @var int */
3484     public $weight;
3486     /** @var int */
3487     public $timecreated;
3489     /** @var int */
3490     public $timemodified;
3492     /** @var float */
3493     public $grade;
3495     /** @var float */
3496     public $gradinggrade;
3498     /** @var float */
3499     public $gradinggradeover;
3501     /** @var string */
3502     public $feedbackauthor;
3504     /** @var int */
3505     public $feedbackauthorformat;
3507     /** @var int */
3508     public $feedbackauthorattachment;
3510     /** @var array */
3511     protected $fields = array('id', 'submissionid', 'weight', 'timecreated',
3512         'timemodified', 'grade', 'gradinggrade', 'gradinggradeover', 'feedbackauthor',
3513         'feedbackauthorformat', 'feedbackauthorattachment');
3515     /**
3516      * Format the overall feedback text content
3517      *
3518      * False is returned if the overall feedback feature is disabled. Null is returned
3519      * if the overall feedback content has not been found. Otherwise, string with
3520      * formatted feedback text is returned.
3521      *
3522      * @return string|bool|null
3523      */
3524     public function get_overall_feedback_content() {
3526         if ($this->workshop->overallfeedbackmode == 0) {
3527             return false;
3528         }
3530         if (trim($this->feedbackauthor) === '') {
3531             return null;
3532         }
3534         $content = file_rewrite_pluginfile_urls($this->feedbackauthor, 'pluginfile.php', $this->workshop->context->id,
3535             'mod_workshop', 'overallfeedback_content', $this->id);
3536         $content = format_text($content, $this->feedbackauthorformat,
3537             array('overflowdiv' => true, 'context' => $this->workshop->context));
3539         return $content;
3540     }
3542     /**
3543      * Prepares the list of overall feedback attachments
3544      *
3545      * Returns false if overall feedback attachments are not allowed. Otherwise returns
3546      * list of attachments (may be empty).
3547      *
3548      * @return bool|array of stdClass
3549      */
3550     public function get_overall_feedback_attachments() {
3552         if ($this->workshop->overallfeedbackmode == 0) {
3553             return false;
3554         }
3556         if ($this->workshop->overallfeedbackfiles == 0) {
3557             return false;
3558         }
3560         if (empty($this->feedbackauthorattachment)) {
3561             return array();
3562         }
3564         $attachments = array();
3565         $fs = get_file_storage();
3566         $files = $fs->get_area_files($this->workshop->context->id, 'mod_workshop', 'overallfeedback_attachment', $this->id);
3567         foreach ($files as $file) {
3568             if ($file->is_directory()) {
3569                 continue;
3570             }
3571             $filepath = $file->get_filepath();
3572             $filename = $file->get_filename();
3573             $fileurl = moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop',
3574                 'overallfeedback_attachment', $this->id, $filepath, $filename, true);
3575             $previewurl = new moodle_url(moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop',
3576                 'overallfeedback_attachment', $this->id, $filepath, $filename, false), array('preview' => 'bigthumb'));
3577             $attachments[] = (object)array(
3578                 'filepath' => $filepath,
3579                 'filename' => $filename,
3580                 'fileurl' => $fileurl,
3581                 'previewurl' => $previewurl,
3582                 'mimetype' => $file->get_mimetype(),
3584             );
3585         }
3587         return $attachments;
3588     }
3592 /**
3593  * Represents a renderable training assessment of an example submission
3594  */
3595 class workshop_example_assessment extends workshop_assessment implements renderable {
3597     /**
3598      * @see parent::validate_raw_record()
3599      */
3600     protected function validate_raw_record(stdClass $record) {
3601         if ($record->weight != 0) {
3602             throw new coding_exception('Invalid weight of example submission assessment');
3603         }
3604         parent::validate_raw_record($record);
3605     }
3609 /**
3610  * Represents a renderable reference assessment of an example submission
3611  */
3612 class workshop_example_reference_assessment extends workshop_assessment implements renderable {
3614     /**
3615      * @see parent::validate_raw_record()
3616      */
3617     protected function validate_raw_record(stdClass $record) {
3618         if ($record->weight != 1) {
3619             throw new coding_exception('Invalid weight of the reference example submission assessment');
3620         }
3621         parent::validate_raw_record($record);
3622     }
3626 /**
3627  * Renderable message to be displayed to the user
3628  *
3629  * Message can contain an optional action link with a label that is supposed to be rendered
3630  * as a button or a link.
3631  *
3632  * @see workshop::renderer::render_workshop_message()
3633  */
3634 class workshop_message implements renderable {
3636     const TYPE_INFO     = 10;
3637     const TYPE_OK       = 20;
3638     const TYPE_ERROR    = 30;
3640     /** @var string */
3641     protected $text = '';
3642     /** @var int */
3643     protected $type = self::TYPE_INFO;
3644     /** @var moodle_url */
3645     protected $actionurl = null;
3646     /** @var string */
3647     protected $actionlabel = '';
3649     /**
3650      * @param string $text short text to be displayed
3651      * @param string $type optional message type info|ok|error
3652      */
3653     public function __construct($text = null, $type = self::TYPE_INFO) {
3654         $this->set_text($text);
3655         $this->set_type($type);
3656     }
3658     /**
3659      * Sets the message text
3660      *
3661      * @param string $text short text to be displayed
3662      */
3663     public function set_text($text) {
3664         $this->text = $text;
3665     }
3667     /**
3668      * Sets the message type
3669      *
3670      * @param int $type
3671      */
3672     public function set_type($type = self::TYPE_INFO) {
3673         if (in_array($type, array(self::TYPE_OK, self::TYPE_ERROR, self::TYPE_INFO))) {
3674             $this->type = $type;
3675         } else {
3676             throw new coding_exception('Unknown message type.');
3677         }
3678     }
3680     /**
3681      * Sets the optional message action
3682      *
3683      * @param moodle_url $url to follow on action
3684      * @param string $label action label
3685      */
3686     public function set_action(moodle_url $url, $label) {
3687         $this->actionurl    = $url;
3688         $this->actionlabel  = $label;
3689     }
3691     /**
3692      * Returns message text with HTML tags quoted
3693      *
3694      * @return string
3695      */
3696     public function get_message() {
3697         return s($this->text);
3698     }
3700     /**
3701      * Returns message type
3702      *
3703      * @return int
3704      */
3705     public function get_type() {
3706         return $this->type;
3707     }
3709     /**
3710      * Returns action URL
3711      *
3712      * @return moodle_url|null
3713      */
3714     public function get_action_url() {
3715         return $this->actionurl;
3716     }
3718     /**
3719      * Returns action label
3720      *
3721      * @return string
3722      */
3723     public function get_action_label() {
3724         return $this->actionlabel;
3725     }
3729 /**
3730  * Renderable component containing all the data needed to display the grading report
3731  */
3732 class workshop_grading_report implements renderable {
3734     /** @var stdClass returned by {@see workshop::prepare_grading_report_data()} */
3735     protected $data;
3736     /** @var stdClass rendering options */
3737     protected $options;
3739     /**
3740      * Grades in $data must be already rounded to the set number of decimals or must be null
3741      * (in which later case, the [mod_workshop,nullgrade] string shall be displayed)
3742      *
3743      * @param stdClass $data prepared by {@link workshop::prepare_grading_report_data()}
3744      * @param stdClass $options display options (showauthornames, showreviewernames, sortby, sorthow, showsubmissiongrade, showgradinggrade)
3745      */
3746     public function __construct(stdClass $data, stdClass $options) {
3747         $this->data     = $data;
3748         $this->options  = $options;
3749     }
3751     /**
3752      * @return stdClass grading report data
3753      */
3754     public function get_data() {
3755         return $this->data;
3756     }
3758     /**
3759      * @return stdClass rendering options
3760      */
3761     public function get_options() {
3762         return $this->options;
3763     }
3767 /**
3768  * Base class for renderable feedback for author and feedback for reviewer
3769  */
3770 abstract class workshop_feedback {
3772     /** @var stdClass the user info */
3773     protected $provider = null;
3775     /** @var string the feedback text */
3776     protected $content = null;
3778     /** @var int format of the feedback text */
3779     protected $format = null;
3781     /**
3782      * @return stdClass the user info
3783      */
3784     public function get_provider() {
3786         if (is_null($this->provider)) {
3787             throw new coding_exception('Feedback provider not set');
3788         }
3790         return $this->provider;
3791     }
3793     /**
3794      * @return string the feedback text
3795      */
3796     public function get_content() {
3798         if (is_null($this->content)) {
3799             throw new coding_exception('Feedback content not set');
3800         }
3802         return $this->content;
3803     }
3805     /**
3806      * @return int format of the feedback text
3807      */
3808     public function get_format() {
3810         if (is_null($this->format)) {
3811             throw new coding_exception('Feedback text format not set');
3812         }
3814         return $this->format;
3815     }
3819 /**
3820  * Renderable feedback for the author of submission
3821  */
3822 class workshop_feedback_author extends workshop_feedback implements renderable {
3824     /**
3825      * Extracts feedback from the given submission record
3826      *
3827      * @param stdClass $submission record as returned by {@see self::get_submission_by_id()}
3828      */
3829     public function __construct(stdClass $submission) {
3831         $this->provider = user_picture::unalias($submission, null, 'gradeoverbyx', 'gradeoverby');
3832         $this->content  = $submission->feedbackauthor;
3833         $this->format   = $submission->feedbackauthorformat;
3834     }
3838 /**
3839  * Renderable feedback for the reviewer
3840  */
3841 class workshop_feedback_reviewer extends workshop_feedback implements renderable {
3843     /**
3844      * Extracts feedback from the given assessment record
3845      *
3846      * @param stdClass $assessment record as returned by eg {@see self::get_assessment_by_id()}
3847      */
3848     public function __construct(stdClass $assessment) {
3850         $this->provider = user_picture::unalias($assessment, null, 'gradinggradeoverbyx', 'overby');
3851         $this->content  = $assessment->feedbackreviewer;
3852         $this->format   = $assessment->feedbackreviewerformat;
3853     }
3857 /**
3858  * Holds the final grades for the activity as are stored in the gradebook
3859  */
3860 class workshop_final_grades implements renderable {
3862     /** @var object the info from the gradebook about the grade for submission */
3863     public $submissiongrade = null;
3865     /** @var object the infor from the gradebook about the grade for assessment */
3866     public $assessmentgrade = null;