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