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