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