MDL-59252 mod_workshop: Move assessment evaluation code to API
[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
3f08cfc5
JL
889 /**
890 * Returns submissions from this workshop that are viewable by the current user (except example submissions).
891 *
892 * @param mixed $authorid int|array If set to [array of] integer, return submission[s] of the given user[s] only
893 * @param int $groupid If non-zero, return only submissions by authors in the specified group. 0 for all groups.
894 * @param int $limitfrom Return a subset of records, starting at this point (optional)
895 * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
896 * @return array of records and the total submissions count
897 * @since Moodle 3.4
898 */
899 public function get_visible_submissions($authorid = 0, $groupid = 0, $limitfrom = 0, $limitnum = 0) {
900 global $DB, $USER;
901
902 $submissions = array();
903 $select = "SELECT s.*";
904 $selectcount = "SELECT COUNT(s.id)";
905 $from = " FROM {workshop_submissions} s";
906 $params = array('workshopid' => $this->id);
907
908 // Check if the passed group (or all groups when groupid is 0) is visible by the current user.
909 if (!groups_group_visible($groupid, $this->course, $this->cm)) {
910 return array($submissions, 0);
911 }
912
913 if ($groupid) {
914 $from .= " JOIN {groups_members} gm ON (gm.userid = s.authorid AND gm.groupid = :groupid)";
915 $params['groupid'] = $groupid;
916 }
917 $where = " WHERE s.workshopid = :workshopid AND s.example = 0";
918
919 if (!has_capability('mod/workshop:viewallsubmissions', $this->context)) {
920 // Check published submissions.
921 $workshopclosed = $this->phase == self::PHASE_CLOSED;
922 $canviewpublished = has_capability('mod/workshop:viewpublishedsubmissions', $this->context);
923 if ($workshopclosed && $canviewpublished) {
924 $published = " OR s.published = 1";
925 } else {
926 $published = '';
927 }
928
929 // Always get submissions I did or I provided feedback to.
930 $where .= " AND (s.authorid = :authorid OR s.gradeoverby = :graderid $published)";
931 $params['authorid'] = $USER->id;
932 $params['graderid'] = $USER->id;
933 }
934
935 // Now, user filtering.
936 if (!empty($authorid)) {
937 list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
938 $where .= " AND s.authorid $usql";
939 $params = array_merge($params, $uparams);
940 }
941
942 $order = " ORDER BY s.timecreated";
943
944 $totalcount = $DB->count_records_sql($selectcount.$from.$where, $params);
945 if ($totalcount) {
946 $submissions = $DB->get_records_sql($select.$from.$where.$order, $params, $limitfrom, $limitnum);
947 }
948 return array($submissions, $totalcount);
949 }
950
951
51508f25
DM
952 /**
953 * Returns a submission record with the author's data
954 *
955 * @param int $id submission id
7a789aa8 956 * @return stdclass
51508f25
DM
957 */
958 public function get_submission_by_id($id) {
959 global $DB;
960
29dc43e7
DM
961 // we intentionally check the workshopid here, too, so the workshop can't touch submissions
962 // from other instances
0dfb4bad
DM
963 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
964 $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
965 $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
51508f25 966 FROM {workshop_submissions} s
00aca3c1 967 INNER JOIN {user} u ON (s.authorid = u.id)
0dfb4bad
DM
968 LEFT JOIN {user} g ON (s.gradeoverby = g.id)
969 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.id = :id";
51508f25
DM
970 $params = array('workshopid' => $this->id, 'id' => $id);
971 return $DB->get_record_sql($sql, $params, MUST_EXIST);
972 }
973
53fad4b9 974 /**
3dc78e5b 975 * Returns a submission submitted by the given author
53fad4b9 976 *
3dc78e5b 977 * @param int $id author id
7a789aa8 978 * @return stdclass|false
53fad4b9 979 */
00aca3c1 980 public function get_submission_by_author($authorid) {
e9b0f0ab
DM
981 global $DB;
982
00aca3c1 983 if (empty($authorid)) {
53fad4b9
DM
984 return false;
985 }
0dfb4bad
DM
986 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
987 $gradeoverbyfields = user_picture::fields('g', null, 'gradeoverbyx', 'gradeoverby');
988 $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
3dc78e5b 989 FROM {workshop_submissions} s
00aca3c1 990 INNER JOIN {user} u ON (s.authorid = u.id)
0dfb4bad
DM
991 LEFT JOIN {user} g ON (s.gradeoverby = g.id)
992 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.authorid = :authorid";
00aca3c1 993 $params = array('workshopid' => $this->id, 'authorid' => $authorid);
3dc78e5b 994 return $DB->get_record_sql($sql, $params);
53fad4b9 995 }
6e309973 996
00bc77ee
DM
997 /**
998 * Returns published submissions with their authors data
999 *
1000 * @return array of stdclass
1001 */
1002 public function get_published_submissions($orderby='finalgrade DESC') {
1003 global $DB;
1004
0dfb4bad 1005 $authorfields = user_picture::fields('u', null, 'authoridx', 'author');
00bc77ee
DM
1006 $sql = "SELECT s.id, s.authorid, s.timecreated, s.timemodified,
1007 s.title, s.grade, s.gradeover, COALESCE(s.gradeover,s.grade) AS finalgrade,
0dfb4bad 1008 $authorfields
00bc77ee
DM
1009 FROM {workshop_submissions} s
1010 INNER JOIN {user} u ON (s.authorid = u.id)
1011 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.published = 1
1012 ORDER BY $orderby";
1013 $params = array('workshopid' => $this->id);
1014 return $DB->get_records_sql($sql, $params);
1015 }
1016
81eccf0a
DM
1017 /**
1018 * Returns full record of the given example submission
1019 *
1020 * @param int $id example submission od
1021 * @return object
1022 */
1023 public function get_example_by_id($id) {
1024 global $DB;
1025 return $DB->get_record('workshop_submissions',
1026 array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST);
1027 }
1028
cbf87967
DM
1029 /**
1030 * Returns the list of example submissions in this workshop with reference assessments attached
1031 *
1032 * @return array of objects or an empty array
1033 * @see workshop::prepare_example_summary()
1034 */
1035 public function get_examples_for_manager() {
1036 global $DB;
1037
1038 $sql = 'SELECT s.id, s.title,
81b22887 1039 a.id AS assessmentid, a.grade, a.gradinggrade
cbf87967
DM
1040 FROM {workshop_submissions} s
1041 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.weight = 1)
1042 WHERE s.example = 1 AND s.workshopid = :workshopid
1043 ORDER BY s.title';
1044 return $DB->get_records_sql($sql, array('workshopid' => $this->id));
1045 }
1046
1047 /**
1048 * Returns the list of all example submissions in this workshop with the information of assessments done by the given user
1049 *
1050 * @param int $reviewerid user id
1051 * @return array of objects, indexed by example submission id
1052 * @see workshop::prepare_example_summary()
1053 */
1054 public function get_examples_for_reviewer($reviewerid) {
1055 global $DB;
1056
1057 if (empty($reviewerid)) {
1058 return false;
1059 }
1060 $sql = 'SELECT s.id, s.title,
81b22887 1061 a.id AS assessmentid, a.grade, a.gradinggrade
cbf87967
DM
1062 FROM {workshop_submissions} s
1063 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.reviewerid = :reviewerid AND a.weight = 0)
1064 WHERE s.example = 1 AND s.workshopid = :workshopid
1065 ORDER BY s.title';
1066 return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid));
1067 }
1068
1069 /**
81b22887
DM
1070 * Prepares renderable submission component
1071 *
1072 * @param stdClass $record required by {@see workshop_submission}
1073 * @param bool $showauthor show the author-related information
1074 * @return workshop_submission
1075 */
1076 public function prepare_submission(stdClass $record, $showauthor = false) {
1077
77d746a2 1078 $submission = new workshop_submission($this, $record, $showauthor);
81b22887
DM
1079 $submission->url = $this->submission_url($record->id);
1080
1081 return $submission;
1082 }
1083
1084 /**
1085 * Prepares renderable submission summary component
1086 *
1087 * @param stdClass $record required by {@see workshop_submission_summary}
1088 * @param bool $showauthor show the author-related information
1089 * @return workshop_submission_summary
1090 */
1091 public function prepare_submission_summary(stdClass $record, $showauthor = false) {
1092
77d746a2 1093 $summary = new workshop_submission_summary($this, $record, $showauthor);
81b22887
DM
1094 $summary->url = $this->submission_url($record->id);
1095
1096 return $summary;
1097 }
1098
1099 /**
1100 * Prepares renderable example submission component
1101 *
1102 * @param stdClass $record required by {@see workshop_example_submission}
1103 * @return workshop_example_submission
1104 */
1105 public function prepare_example_submission(stdClass $record) {
1106
77d746a2 1107 $example = new workshop_example_submission($this, $record);
81b22887
DM
1108
1109 return $example;
1110 }
1111
1112 /**
1113 * Prepares renderable example submission summary component
1114 *
1115 * If the example is editable, the caller must set the 'editable' flag explicitly.
cbf87967 1116 *
5924db72 1117 * @param stdClass $example as returned by {@link workshop::get_examples_for_manager()} or {@link workshop::get_examples_for_reviewer()}
81b22887 1118 * @return workshop_example_submission_summary to be rendered
cbf87967 1119 */
81b22887
DM
1120 public function prepare_example_summary(stdClass $example) {
1121
77d746a2 1122 $summary = new workshop_example_submission_summary($this, $example);
cbf87967 1123
cbf87967 1124 if (is_null($example->grade)) {
81b22887
DM
1125 $summary->status = 'notgraded';
1126 $summary->assesslabel = get_string('assess', 'workshop');
cbf87967 1127 } else {
81b22887
DM
1128 $summary->status = 'graded';
1129 $summary->assesslabel = get_string('reassess', 'workshop');
cbf87967
DM
1130 }
1131
7a789aa8 1132 $summary->gradeinfo = new stdclass();
cbf87967
DM
1133 $summary->gradeinfo->received = $this->real_grade($example->grade);
1134 $summary->gradeinfo->max = $this->real_grade(100);
1135
81b22887
DM
1136 $summary->url = new moodle_url($this->exsubmission_url($example->id));
1137 $summary->editurl = new moodle_url($this->exsubmission_url($example->id), array('edit' => 'on'));
1138 $summary->assessurl = new moodle_url($this->exsubmission_url($example->id), array('assess' => 'on', 'sesskey' => sesskey()));
cbf87967
DM
1139
1140 return $summary;
1141 }
1142
38504a44
DM
1143 /**
1144 * Prepares renderable assessment component
1145 *
1146 * The $options array supports the following keys:
1147 * showauthor - should the author user info be available for the renderer
1148 * showreviewer - should the reviewer user info be available for the renderer
1149 * showform - show the assessment form if it is available
e30f6ff3 1150 * showweight - should the assessment weight be available for the renderer
38504a44
DM
1151 *
1152 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1153 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1154 * @param array $options
1155 * @return workshop_assessment
1156 */
1157 public function prepare_assessment(stdClass $record, $form, array $options = array()) {
1158
77d746a2 1159 $assessment = new workshop_assessment($this, $record, $options);
38504a44
DM
1160 $assessment->url = $this->assess_url($record->id);
1161 $assessment->maxgrade = $this->real_grade(100);
1162
1163 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1164 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1165 }
1166
1167 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1168 $assessment->form = $form;
1169 }
1170
1171 if (empty($options['showweight'])) {
1172 $assessment->weight = null;
1173 }
1174
1175 if (!is_null($record->grade)) {
1176 $assessment->realgrade = $this->real_grade($record->grade);
1177 }
1178
1179 return $assessment;
1180 }
1181
e30f6ff3
DM
1182 /**
1183 * Prepares renderable example submission's assessment component
1184 *
1185 * The $options array supports the following keys:
1186 * showauthor - should the author user info be available for the renderer
1187 * showreviewer - should the reviewer user info be available for the renderer
1188 * showform - show the assessment form if it is available
1189 *
1190 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1191 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1192 * @param array $options
1193 * @return workshop_example_assessment
1194 */
1195 public function prepare_example_assessment(stdClass $record, $form = null, array $options = array()) {
1196
77d746a2 1197 $assessment = new workshop_example_assessment($this, $record, $options);
e30f6ff3
DM
1198 $assessment->url = $this->exassess_url($record->id);
1199 $assessment->maxgrade = $this->real_grade(100);
1200
1201 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1202 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1203 }
1204
1205 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1206 $assessment->form = $form;
1207 }
1208
1209 if (!is_null($record->grade)) {
1210 $assessment->realgrade = $this->real_grade($record->grade);
1211 }
1212
1213 $assessment->weight = null;
1214
1215 return $assessment;
1216 }
1217
1218 /**
1219 * Prepares renderable example submission's reference assessment component
1220 *
1221 * The $options array supports the following keys:
1222 * showauthor - should the author user info be available for the renderer
1223 * showreviewer - should the reviewer user info be available for the renderer
1224 * showform - show the assessment form if it is available
1225 *
1226 * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1227 * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1228 * @param array $options
1229 * @return workshop_example_reference_assessment
1230 */
1231 public function prepare_example_reference_assessment(stdClass $record, $form = null, array $options = array()) {
1232
77d746a2 1233 $assessment = new workshop_example_reference_assessment($this, $record, $options);
e30f6ff3
DM
1234 $assessment->maxgrade = $this->real_grade(100);
1235
1236 if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1237 debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1238 }
1239
1240 if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1241 $assessment->form = $form;
1242 }
1243
1244 if (!is_null($record->grade)) {
1245 $assessment->realgrade = $this->real_grade($record->grade);
1246 }
1247
1248 $assessment->weight = null;
1249
1250 return $assessment;
1251 }
1252
81eccf0a
DM
1253 /**
1254 * Removes the submission and all relevant data
1255 *
5924db72 1256 * @param stdClass $submission record to delete
81eccf0a
DM
1257 * @return void
1258 */
7a789aa8 1259 public function delete_submission(stdclass $submission) {
81eccf0a 1260 global $DB;
f2639dca 1261
81eccf0a
DM
1262 $assessments = $DB->get_records('workshop_assessments', array('submissionid' => $submission->id), '', 'id');
1263 $this->delete_assessment(array_keys($assessments));
4a44c660
DM
1264
1265 $fs = get_file_storage();
1266 $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_content', $submission->id);
1267 $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
1268
81eccf0a 1269 $DB->delete_records('workshop_submissions', array('id' => $submission->id));
e1fcba99
JL
1270
1271 // Event information.
1272 $params = array(
1273 'context' => $this->context,
1274 'courseid' => $this->course->id,
1275 'relateduserid' => $submission->authorid,
1276 'other' => array(
1277 'submissiontitle' => $submission->title
1278 )
1279 );
1280 $params['objectid'] = $submission->id;
1281 $event = \mod_workshop\event\submission_deleted::create($params);
1282 $event->add_record_snapshot('workshop', $this->dbrecord);
1283 $event->trigger();
81eccf0a
DM
1284 }
1285
6e309973 1286 /**
3dc78e5b 1287 * Returns the list of all assessments in the workshop with some data added
6e309973
DM
1288 *
1289 * Fetches data from {workshop_assessments} and adds some useful information from other
de6aaa72 1290 * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory
3dc78e5b
DM
1291 * lack issues.
1292 *
7a789aa8 1293 * @return array [assessmentid] => assessment stdclass
6e309973 1294 */
3dc78e5b 1295 public function get_all_assessments() {
6e309973 1296 global $DB;
53fad4b9 1297
38504a44
DM
1298 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1299 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
f68648e9 1300 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
9695ff81 1301 list($sort, $params) = users_order_by_sql('reviewer');
38504a44 1302 $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified,
3dc78e5b 1303 a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby,
f68648e9 1304 $reviewerfields, $authorfields, $overbyfields,
38504a44 1305 s.title
3d2924e9 1306 FROM {workshop_assessments} a
00aca3c1 1307 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
3d2924e9 1308 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
00aca3c1 1309 INNER JOIN {user} author ON (s.authorid = author.id)
f68648e9 1310 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
3dc78e5b 1311 WHERE s.workshopid = :workshopid AND s.example = 0
9695ff81
TH
1312 ORDER BY $sort";
1313 $params['workshopid'] = $this->id;
3d2924e9 1314
3dc78e5b 1315 return $DB->get_records_sql($sql, $params);
53fad4b9
DM
1316 }
1317
1318 /**
3dc78e5b 1319 * Get the complete information about the given assessment
53fad4b9
DM
1320 *
1321 * @param int $id Assessment ID
5a372494 1322 * @return stdclass
53fad4b9
DM
1323 */
1324 public function get_assessment_by_id($id) {
3dc78e5b
DM
1325 global $DB;
1326
38504a44
DM
1327 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1328 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
f68648e9
DM
1329 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1330 $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
3dc78e5b 1331 FROM {workshop_assessments} a
00aca3c1 1332 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
3dc78e5b 1333 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
00aca3c1 1334 INNER JOIN {user} author ON (s.authorid = author.id)
f68648e9 1335 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
38504a44 1336 WHERE a.id = :id AND s.workshopid = :workshopid";
3dc78e5b
DM
1337 $params = array('id' => $id, 'workshopid' => $this->id);
1338
1339 return $DB->get_record_sql($sql, $params, MUST_EXIST);
53fad4b9
DM
1340 }
1341
5a372494
DM
1342 /**
1343 * Get the complete information about the user's assessment of the given submission
1344 *
1345 * @param int $sid submission ID
1346 * @param int $uid user ID of the reviewer
1347 * @return false|stdclass false if not found, stdclass otherwise
1348 */
1349 public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
1350 global $DB;
1351
38504a44
DM
1352 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1353 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
f68648e9
DM
1354 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1355 $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
5a372494
DM
1356 FROM {workshop_assessments} a
1357 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1358 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1359 INNER JOIN {user} author ON (s.authorid = author.id)
f68648e9 1360 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
38504a44 1361 WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid";
5a372494
DM
1362 $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id);
1363
1364 return $DB->get_record_sql($sql, $params, IGNORE_MISSING);
1365 }
1366
1367 /**
1368 * Get the complete information about all assessments of the given submission
1369 *
1370 * @param int $submissionid
1371 * @return array
1372 */
1373 public function get_assessments_of_submission($submissionid) {
1374 global $DB;
1375
38504a44 1376 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
f68648e9 1377 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
9695ff81 1378 list($sort, $params) = users_order_by_sql('reviewer');
f68648e9 1379 $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields
5a372494
DM
1380 FROM {workshop_assessments} a
1381 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1382 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
f68648e9 1383 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
38504a44 1384 WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid
9695ff81
TH
1385 ORDER BY $sort";
1386 $params['submissionid'] = $submissionid;
1387 $params['workshopid'] = $this->id;
5a372494
DM
1388
1389 return $DB->get_records_sql($sql, $params);
1390 }
1391
53fad4b9 1392 /**
3dc78e5b 1393 * Get the complete information about all assessments allocated to the given reviewer
53fad4b9 1394 *
00aca3c1 1395 * @param int $reviewerid
3dc78e5b 1396 * @return array
53fad4b9 1397 */
00aca3c1 1398 public function get_assessments_by_reviewer($reviewerid) {
3dc78e5b
DM
1399 global $DB;
1400
38504a44
DM
1401 $reviewerfields = user_picture::fields('reviewer', null, 'revieweridx', 'reviewer');
1402 $authorfields = user_picture::fields('author', null, 'authorid', 'author');
f68648e9
DM
1403 $overbyfields = user_picture::fields('overby', null, 'gradinggradeoverbyx', 'overby');
1404 $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields,
ddb59c77 1405 s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated,
38504a44 1406 s.timemodified AS submissionmodified
3dc78e5b 1407 FROM {workshop_assessments} a
00aca3c1 1408 INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
3dc78e5b 1409 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
00aca3c1 1410 INNER JOIN {user} author ON (s.authorid = author.id)
f68648e9 1411 LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
38504a44 1412 WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid";
00aca3c1 1413 $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id);
3dc78e5b
DM
1414
1415 return $DB->get_records_sql($sql, $params);
53fad4b9 1416 }
6e309973 1417
0001eea6
DM
1418 /**
1419 * Get allocated assessments not graded yet by the given reviewer
1420 *
1421 * @see self::get_assessments_by_reviewer()
1422 * @param int $reviewerid the reviewer id
1423 * @param null|int|array $exclude optional assessment id (or list of them) to be excluded
1424 * @return array
1425 */
1426 public function get_pending_assessments_by_reviewer($reviewerid, $exclude = null) {
1427
1428 $assessments = $this->get_assessments_by_reviewer($reviewerid);
1429
1430 foreach ($assessments as $id => $assessment) {
1431 if (!is_null($assessment->grade)) {
1432 unset($assessments[$id]);
1433 continue;
1434 }
1435 if (!empty($exclude)) {
1436 if (is_array($exclude) and in_array($id, $exclude)) {
1437 unset($assessments[$id]);
1438 continue;
1439 } else if ($id == $exclude) {
1440 unset($assessments[$id]);
1441 continue;
1442 }
1443 }
1444 }
1445
1446 return $assessments;
1447 }
1448
6e309973
DM
1449 /**
1450 * Allocate a submission to a user for review
53fad4b9 1451 *
5924db72 1452 * @param stdClass $submission Submission object with at least id property
6e309973 1453 * @param int $reviewerid User ID
becec954 1454 * @param int $weight of the new assessment, from 0 to 16
67ae13d9 1455 * @param bool $bulk repeated inserts into DB expected
31cea236 1456 * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists
6e309973 1457 */
67ae13d9 1458 public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
6e309973
DM
1459 global $DB;
1460
00aca3c1 1461 if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
b761e6d9 1462 return self::ALLOCATION_EXISTS;
6e309973
DM
1463 }
1464
67ae13d9
DM
1465 $weight = (int)$weight;
1466 if ($weight < 0) {
1467 $weight = 0;
1468 }
1469 if ($weight > 16) {
1470 $weight = 16;
1471 }
1472
6e309973 1473 $now = time();
7a789aa8 1474 $assessment = new stdclass();
e554671d
DM
1475 $assessment->submissionid = $submission->id;
1476 $assessment->reviewerid = $reviewerid;
7a5f4be0 1477 $assessment->timecreated = $now; // do not set timemodified here
becec954 1478 $assessment->weight = $weight;
c6a793d5 1479 $assessment->feedbackauthorformat = editors_get_preferred_format();
884482fb 1480 $assessment->feedbackreviewerformat = editors_get_preferred_format();
6e309973 1481
235b31c8 1482 return $DB->insert_record('workshop_assessments', $assessment, true, $bulk);
6e309973
DM
1483 }
1484
6e309973 1485 /**
4a44c660
DM
1486 * Delete assessment record or records.
1487 *
1488 * Removes associated records from the workshop_grades table, too.
6e309973 1489 *
4a44c660
DM
1490 * @param int|array $id assessment id or array of assessments ids
1491 * @todo Give grading strategy plugins a chance to clean up their data, too.
1492 * @return bool true
6e309973
DM
1493 */
1494 public function delete_assessment($id) {
1495 global $DB;
1496
4a44c660
DM
1497 if (empty($id)) {
1498 return true;
1499 }
1500
1501 $fs = get_file_storage();
6e309973 1502
53fad4b9 1503 if (is_array($id)) {
4a44c660
DM
1504 $DB->delete_records_list('workshop_grades', 'assessmentid', $id);
1505 foreach ($id as $itemid) {
1506 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $itemid);
1507 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $itemid);
1508 }
1509 $DB->delete_records_list('workshop_assessments', 'id', $id);
1510
3d2924e9 1511 } else {
4a44c660
DM
1512 $DB->delete_records('workshop_grades', array('assessmentid' => $id));
1513 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $id);
1514 $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $id);
1515 $DB->delete_records('workshop_assessments', array('id' => $id));
53fad4b9 1516 }
4a44c660
DM
1517
1518 return true;
53fad4b9 1519 }
6e309973
DM
1520
1521 /**
1522 * Returns instance of grading strategy class
53fad4b9 1523 *
7a789aa8 1524 * @return stdclass Instance of a grading strategy
6e309973
DM
1525 */
1526 public function grading_strategy_instance() {
3d2924e9
DM
1527 global $CFG; // because we require other libs here
1528
3fd2b0e1 1529 if (is_null($this->strategyinstance)) {
1fcf0ca8 1530 $strategylib = __DIR__ . '/form/' . $this->strategy . '/lib.php';
6e309973
DM
1531 if (is_readable($strategylib)) {
1532 require_once($strategylib);
1533 } else {
f05c168d 1534 throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
6e309973 1535 }
0dc47fb9 1536 $classname = 'workshop_' . $this->strategy . '_strategy';
3fd2b0e1
DM
1537 $this->strategyinstance = new $classname($this);
1538 if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) {
b761e6d9 1539 throw new coding_exception($classname . ' does not implement workshop_strategy interface');
6e309973
DM
1540 }
1541 }
3fd2b0e1 1542 return $this->strategyinstance;
6e309973
DM
1543 }
1544
a93dc3ec
DM
1545 /**
1546 * Sets the current evaluation method to the given plugin.
1547 *
1548 * @param string $method the name of the workshopeval subplugin
1549 * @return bool true if successfully set
1550 * @throws coding_exception if attempting to set a non-installed evaluation method
1551 */
1552 public function set_grading_evaluation_method($method) {
1553 global $DB;
1554
1fcf0ca8 1555 $evaluationlib = __DIR__ . '/eval/' . $method . '/lib.php';
a93dc3ec
DM
1556
1557 if (is_readable($evaluationlib)) {
1558 $this->evaluationinstance = null;
1559 $this->evaluation = $method;
1560 $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id));
1561 return true;
1562 }
1563
1564 throw new coding_exception('Attempt to set a non-existing evaluation method.');
1565 }
1566
45d24d39
DM
1567 /**
1568 * Returns instance of grading evaluation class
1569 *
7a789aa8 1570 * @return stdclass Instance of a grading evaluation
45d24d39
DM
1571 */
1572 public function grading_evaluation_instance() {
1573 global $CFG; // because we require other libs here
1574
1575 if (is_null($this->evaluationinstance)) {
4f115176
DM
1576 if (empty($this->evaluation)) {
1577 $this->evaluation = 'best';
1578 }
1fcf0ca8 1579 $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
45d24d39
DM
1580 if (is_readable($evaluationlib)) {
1581 require_once($evaluationlib);
1582 } else {
4f115176
DM
1583 // Fall back in case the subplugin is not available.
1584 $this->evaluation = 'best';
1fcf0ca8 1585 $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
4f115176
DM
1586 if (is_readable($evaluationlib)) {
1587 require_once($evaluationlib);
1588 } else {
1589 // Fall back in case the subplugin is not available any more.
1590 throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
1591 }
45d24d39
DM
1592 }
1593 $classname = 'workshop_' . $this->evaluation . '_evaluation';
1594 $this->evaluationinstance = new $classname($this);
4f115176
DM
1595 if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) {
1596 throw new coding_exception($classname . ' does not extend workshop_evaluation class');
45d24d39
DM
1597 }
1598 }
1599 return $this->evaluationinstance;
1600 }
1601
66c9894d
DM
1602 /**
1603 * Returns instance of submissions allocator
53fad4b9 1604 *
130ae619 1605 * @param string $method The name of the allocation method, must be PARAM_ALPHA
7a789aa8 1606 * @return stdclass Instance of submissions allocator
66c9894d
DM
1607 */
1608 public function allocator_instance($method) {
3d2924e9
DM
1609 global $CFG; // because we require other libs here
1610
1fcf0ca8 1611 $allocationlib = __DIR__ . '/allocation/' . $method . '/lib.php';
66c9894d
DM
1612 if (is_readable($allocationlib)) {
1613 require_once($allocationlib);
1614 } else {
f05c168d 1615 throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
66c9894d
DM
1616 }
1617 $classname = 'workshop_' . $method . '_allocator';
1618 return new $classname($this);
1619 }
1620
b8ead2e6 1621 /**
454e8dd9 1622 * @return moodle_url of this workshop's view page
b8ead2e6
DM
1623 */
1624 public function view_url() {
1625 global $CFG;
a6855934 1626 return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
b8ead2e6
DM
1627 }
1628
1629 /**
454e8dd9 1630 * @return moodle_url of the page for editing this workshop's grading form
b8ead2e6
DM
1631 */
1632 public function editform_url() {
1633 global $CFG;
a6855934 1634 return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
b8ead2e6
DM
1635 }
1636
1637 /**
454e8dd9 1638 * @return moodle_url of the page for previewing this workshop's grading form
b8ead2e6
DM
1639 */
1640 public function previewform_url() {
1641 global $CFG;
a6855934 1642 return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
b8ead2e6
DM
1643 }
1644
1645 /**
1646 * @param int $assessmentid The ID of assessment record
454e8dd9 1647 * @return moodle_url of the assessment page
b8ead2e6 1648 */
a39d7d87 1649 public function assess_url($assessmentid) {
b8ead2e6 1650 global $CFG;
454e8dd9 1651 $assessmentid = clean_param($assessmentid, PARAM_INT);
a6855934 1652 return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
b8ead2e6
DM
1653 }
1654
becec954
DM
1655 /**
1656 * @param int $assessmentid The ID of assessment record
1657 * @return moodle_url of the example assessment page
1658 */
1659 public function exassess_url($assessmentid) {
1660 global $CFG;
1661 $assessmentid = clean_param($assessmentid, PARAM_INT);
a6855934 1662 return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
becec954
DM
1663 }
1664
39861053 1665 /**
67cd00ba 1666 * @return moodle_url of the page to view a submission, defaults to the own one
39861053 1667 */
67cd00ba 1668 public function submission_url($id=null) {
39861053 1669 global $CFG;
a6855934 1670 return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
39861053
DM
1671 }
1672
81eccf0a
DM
1673 /**
1674 * @param int $id example submission id
1675 * @return moodle_url of the page to view an example submission
1676 */
becec954 1677 public function exsubmission_url($id) {
81eccf0a 1678 global $CFG;
a6855934 1679 return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
81eccf0a
DM
1680 }
1681
cbf87967
DM
1682 /**
1683 * @param int $sid submission id
1684 * @param array $aid of int assessment ids
1685 * @return moodle_url of the page to compare assessments of the given submission
1686 */
1687 public function compare_url($sid, array $aids) {
1688 global $CFG;
1689
a6855934 1690 $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
cbf87967
DM
1691 $i = 0;
1692 foreach ($aids as $aid) {
1693 $url->param("aid{$i}", $aid);
1694 $i++;
1695 }
1696 return $url;
1697 }
1698
1699 /**
1700 * @param int $sid submission id
1701 * @param int $aid assessment id
1702 * @return moodle_url of the page to compare the reference assessments of the given example submission
1703 */
1704 public function excompare_url($sid, $aid) {
1705 global $CFG;
a6855934 1706 return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
cbf87967
DM
1707 }
1708
da0b1f70 1709 /**
454e8dd9 1710 * @return moodle_url of the mod_edit form
da0b1f70
DM
1711 */
1712 public function updatemod_url() {
1713 global $CFG;
a6855934 1714 return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
da0b1f70
DM
1715 }
1716
454e8dd9 1717 /**
08af32af 1718 * @param string $method allocation method
454e8dd9
DM
1719 * @return moodle_url to the allocation page
1720 */
08af32af 1721 public function allocation_url($method=null) {
da0b1f70 1722 global $CFG;
08af32af
DM
1723 $params = array('cmid' => $this->cm->id);
1724 if (!empty($method)) {
1725 $params['method'] = $method;
1726 }
1727 return new moodle_url('/mod/workshop/allocation.php', $params);
da0b1f70
DM
1728 }
1729
454e8dd9
DM
1730 /**
1731 * @param int $phasecode The internal phase code
1732 * @return moodle_url of the script to change the current phase to $phasecode
1733 */
1734 public function switchphase_url($phasecode) {
1735 global $CFG;
1736 $phasecode = clean_param($phasecode, PARAM_INT);
a6855934 1737 return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
454e8dd9
DM
1738 }
1739
89c1aa97
DM
1740 /**
1741 * @return moodle_url to the aggregation page
1742 */
1743 public function aggregate_url() {
1744 global $CFG;
a6855934 1745 return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
89c1aa97
DM
1746 }
1747
32c78bc3
DM
1748 /**
1749 * @return moodle_url of this workshop's toolbox page
1750 */
1751 public function toolbox_url($tool) {
1752 global $CFG;
1753 return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
1754 }
1755
5450f7b6
DM
1756 /**
1757 * Workshop wrapper around {@see add_to_log()}
1a219fb6 1758 * @deprecated since 2.7 Please use the provided event classes for logging actions.
5450f7b6
DM
1759 *
1760 * @param string $action to be logged
1761 * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends
1762 * @param mixed $info additional info, usually id in a table
cbf4b0e6
FM
1763 * @param bool $return true to return the arguments for add_to_log.
1764 * @return void|array array of arguments for add_to_log if $return is true
5450f7b6 1765 */
cbf4b0e6 1766 public function log($action, moodle_url $url = null, $info = null, $return = false) {
1a219fb6 1767 debugging('The log method is now deprecated, please use event classes instead', DEBUG_DEVELOPER);
5450f7b6
DM
1768
1769 if (is_null($url)) {
1770 $url = $this->view_url();
1771 }
1772
1773 if (is_null($info)) {
1774 $info = $this->id;
1775 }
1776
1777 $logurl = $this->log_convert_url($url);
cbf4b0e6
FM
1778 $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
1779 if ($return) {
1780 return $args;
1781 }
1782 call_user_func_array('add_to_log', $args);
5450f7b6
DM
1783 }
1784
b8ead2e6 1785 /**
9ddff589 1786 * Is the given user allowed to create their submission?
407b1e91 1787 *
9ddff589 1788 * @param int $userid
407b1e91 1789 * @return bool
b8ead2e6 1790 */
9ddff589
DM
1791 public function creating_submission_allowed($userid) {
1792
2f289d36 1793 $now = time();
9ddff589 1794 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
2f289d36
DM
1795
1796 if ($this->latesubmissions) {
1797 if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) {
1798 // late submissions are allowed in the submission and assessment phase only
1799 return false;
1800 }
9ddff589 1801 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
2f289d36
DM
1802 // late submissions are not allowed before the submission start
1803 return false;
1804 }
1805 return true;
1806
1807 } else {
1808 if ($this->phase != self::PHASE_SUBMISSION) {
1809 // submissions are allowed during the submission phase only
1810 return false;
1811 }
9ddff589 1812 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
2f289d36
DM
1813 // if enabled, submitting is not allowed before the date/time defined in the mod_form
1814 return false;
1815 }
9ddff589 1816 if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) {
2f289d36
DM
1817 // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed
1818 return false;
1819 }
1820 return true;
1821 }
1822 }
1823
1824 /**
9ddff589 1825 * Is the given user allowed to modify their existing submission?
2f289d36 1826 *
9ddff589 1827 * @param int $userid
2f289d36
DM
1828 * @return bool
1829 */
9ddff589
DM
1830 public function modifying_submission_allowed($userid) {
1831
2f289d36 1832 $now = time();
9ddff589 1833 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
2f289d36 1834
74bf8a94 1835 if ($this->phase != self::PHASE_SUBMISSION) {
2f289d36 1836 // submissions can be edited during the submission phase only
74bf8a94
DM
1837 return false;
1838 }
9ddff589 1839 if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
c1ab2b10 1840 // if enabled, re-submitting is not allowed before the date/time defined in the mod_form
74bf8a94
DM
1841 return false;
1842 }
c1ab2b10
DM
1843 if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) {
1844 // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed
74bf8a94
DM
1845 return false;
1846 }
407b1e91 1847 return true;
b8ead2e6
DM
1848 }
1849
c1e883bb 1850 /**
9ddff589 1851 * Is the given reviewer allowed to create/edit their assessments?
c1e883bb 1852 *
9ddff589 1853 * @param int $userid
c1e883bb
DM
1854 * @return bool
1855 */
9ddff589
DM
1856 public function assessing_allowed($userid) {
1857
74bf8a94 1858 if ($this->phase != self::PHASE_ASSESSMENT) {
4affa724
DM
1859 // assessing is allowed in the assessment phase only, unless the user is a teacher
1860 // providing additional assessment during the evaluation phase
1861 if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) {
1862 return false;
1863 }
74bf8a94 1864 }
9ddff589 1865
74bf8a94 1866 $now = time();
9ddff589
DM
1867 $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1868
1869 if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) {
74bf8a94
DM
1870 // if enabled, assessing is not allowed before the date/time defined in the mod_form
1871 return false;
1872 }
9ddff589 1873 if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) {
74bf8a94
DM
1874 // if enabled, assessing is not allowed after the date/time defined in the mod_form
1875 return false;
1876 }
1877 // here we go, assessing is allowed
c1e883bb
DM
1878 return true;
1879 }
1880
becec954
DM
1881 /**
1882 * Are reviewers allowed to create/edit their assessments of the example submissions?
1883 *
514d8c22
DM
1884 * Returns null if example submissions are not enabled in this workshop. Otherwise returns
1885 * true or false. Note this does not check other conditions like the number of already
1886 * assessed examples, examples mode etc.
becec954 1887 *
74bf8a94 1888 * @return null|bool
becec954
DM
1889 */
1890 public function assessing_examples_allowed() {
74bf8a94
DM
1891 if (empty($this->useexamples)) {
1892 return null;
1893 }
1894 if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
1895 return true;
1896 }
1897 if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
1898 return true;
1899 }
1900 if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
1901 return true;
1902 }
1903 return false;
becec954 1904 }
407b1e91 1905
3dc78e5b
DM
1906 /**
1907 * Are the peer-reviews available to the authors?
1908 *
3dc78e5b
DM
1909 * @return bool
1910 */
1911 public function assessments_available() {
5a372494 1912 return $this->phase == self::PHASE_CLOSED;
3dc78e5b
DM
1913 }
1914
454e8dd9
DM
1915 /**
1916 * Switch to a new workshop phase
1917 *
1918 * Modifies the underlying database record. You should terminate the script shortly after calling this.
1919 *
1920 * @param int $newphase new phase code
1921 * @return bool true if success, false otherwise
1922 */
1923 public function switch_phase($newphase) {
1924 global $DB;
1925
365c2cc2 1926 $known = $this->available_phases_list();
454e8dd9
DM
1927 if (!isset($known[$newphase])) {
1928 return false;
1929 }
f6e8b318
DM
1930
1931 if (self::PHASE_CLOSED == $newphase) {
f27b70fb 1932 // push the grades into the gradebook
7a789aa8 1933 $workshop = new stdclass();
10bc4bce
DM
1934 foreach ($this as $property => $value) {
1935 $workshop->{$property} = $value;
1936 }
1937 $workshop->course = $this->course->id;
1938 $workshop->cmidnumber = $this->cm->id;
1939 $workshop->modname = 'workshop';
1940 workshop_update_grades($workshop);
f6e8b318
DM
1941 }
1942
454e8dd9 1943 $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
9260bb3c 1944 $this->phase = $newphase;
1a219fb6
AG
1945 $eventdata = array(
1946 'objectid' => $this->id,
1947 'context' => $this->context,
1948 'other' => array(
1949 'workshopphase' => $this->phase
1950 )
1951 );
1952 $event = \mod_workshop\event\phase_switched::create($eventdata);
1953 $event->trigger();
454e8dd9
DM
1954 return true;
1955 }
ddb59c77
DM
1956
1957 /**
1958 * Saves a raw grade for submission as calculated from the assessment form fields
1959 *
1960 * @param array $assessmentid assessment record id, must exists
00aca3c1 1961 * @param mixed $grade raw percentual grade from 0.00000 to 100.00000
ddb59c77
DM
1962 * @return false|float the saved grade
1963 */
1964 public function set_peer_grade($assessmentid, $grade) {
1965 global $DB;
1966
1967 if (is_null($grade)) {
1968 return false;
1969 }
7a789aa8 1970 $data = new stdclass();
ddb59c77
DM
1971 $data->id = $assessmentid;
1972 $data->grade = $grade;
7a5f4be0 1973 $data->timemodified = time();
ddb59c77
DM
1974 $DB->update_record('workshop_assessments', $data);
1975 return $grade;
1976 }
6516b9e9 1977
29dc43e7
DM
1978 /**
1979 * Prepares data object with all workshop grades to be rendered
1980 *
5e71cefb 1981 * @param int $userid the user we are preparing the report for
dda42a19 1982 * @param int $groupid if non-zero, prepare the report for the given group only
29dc43e7 1983 * @param int $page the current page (for the pagination)
5e71cefb 1984 * @param int $perpage participants per page (for the pagination)
f27b70fb 1985 * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
5e71cefb 1986 * @param string $sorthow ASC|DESC
7a789aa8 1987 * @return stdclass data for the renderer
29dc43e7 1988 */
dda42a19 1989 public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
29dc43e7
DM
1990 global $DB;
1991
d895c6aa 1992 $canviewall = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
8741ebb0 1993 $isparticipant = $this->is_participant($userid);
29dc43e7
DM
1994
1995 if (!$canviewall and !$isparticipant) {
1996 // who the hell is this?
1997 return array();
1998 }
1999
a81b4cab
DM
2000 if (!in_array($sortby, array('lastname', 'firstname', 'submissiontitle', 'submissionmodified',
2001 'submissiongrade', 'gradinggrade'))) {
5e71cefb
DM
2002 $sortby = 'lastname';
2003 }
2004
2005 if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
2006 $sorthow = 'ASC';
2007 }
2008
2009 // get the list of user ids to be displayed
29dc43e7 2010 if ($canviewall) {
dda42a19 2011 $participants = $this->get_participants(false, $groupid);
29dc43e7
DM
2012 } else {
2013 // this is an ordinary workshop participant (aka student) - display the report just for him/her
2014 $participants = array($userid => (object)array('id' => $userid));
2015 }
2016
5e71cefb 2017 // we will need to know the number of all records later for the pagination purposes
29dc43e7
DM
2018 $numofparticipants = count($participants);
2019
deea6e7a
DM
2020 if ($numofparticipants > 0) {
2021 // load all fields which can be used for sorting and paginate the records
2022 list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
2023 $params['workshopid1'] = $this->id;
2024 $params['workshopid2'] = $this->id;
20e7fd83
DM
2025 $sqlsort = array();
2026 $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
2027 foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
2028 $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
2029 }
2030 $sqlsort = implode(',', $sqlsort);
a327f25e 2031 $picturefields = user_picture::fields('u', array(), 'userid');
bfde810a 2032 $sql = "SELECT $picturefields, s.title AS submissiontitle, s.timemodified AS submissionmodified,
a81b4cab 2033 s.grade AS submissiongrade, ag.gradinggrade
deea6e7a
DM
2034 FROM {user} u
2035 LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)
2036 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)
2037 WHERE u.id $participantids
2038 ORDER BY $sqlsort";
2039 $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
2040 } else {
2041 $participants = array();
2042 }
29dc43e7
DM
2043
2044 // this will hold the information needed to display user names and pictures
5e71cefb
DM
2045 $userinfo = array();
2046
2047 // get the user details for all participants to display
a327f25e 2048 $additionalnames = get_all_user_name_fields();
5e71cefb
DM
2049 foreach ($participants as $participant) {
2050 if (!isset($userinfo[$participant->userid])) {
7a789aa8 2051 $userinfo[$participant->userid] = new stdclass();
5e71cefb 2052 $userinfo[$participant->userid]->id = $participant->userid;
5e71cefb
DM
2053 $userinfo[$participant->userid]->picture = $participant->picture;
2054 $userinfo[$participant->userid]->imagealt = $participant->imagealt;
3a11c09f 2055 $userinfo[$participant->userid]->email = $participant->email;
a327f25e
AG
2056 foreach ($additionalnames as $addname) {
2057 $userinfo[$participant->userid]->$addname = $participant->$addname;
2058 }
5e71cefb
DM
2059 }
2060 }
29dc43e7 2061
5e71cefb 2062 // load the submissions details
29dc43e7 2063 $submissions = $this->get_submissions(array_keys($participants));
5e71cefb
DM
2064
2065 // get the user details for all moderators (teachers) that have overridden a submission grade
29dc43e7 2066 foreach ($submissions as $submission) {
29dc43e7 2067 if (!isset($userinfo[$submission->gradeoverby])) {
7a789aa8 2068 $userinfo[$submission->gradeoverby] = new stdclass();
29dc43e7 2069 $userinfo[$submission->gradeoverby]->id = $submission->gradeoverby;
29dc43e7
DM
2070 $userinfo[$submission->gradeoverby]->picture = $submission->overpicture;
2071 $userinfo[$submission->gradeoverby]->imagealt = $submission->overimagealt;
3a11c09f 2072 $userinfo[$submission->gradeoverby]->email = $submission->overemail;
a327f25e
AG
2073 foreach ($additionalnames as $addname) {
2074 $temp = 'over' . $addname;
2075 $userinfo[$submission->gradeoverby]->$addname = $submission->$temp;
2076 }
29dc43e7
DM
2077 }
2078 }
2079
5e71cefb 2080 // get the user details for all reviewers of the displayed participants
29dc43e7 2081 $reviewers = array();
a327f25e 2082
29dc43e7
DM
2083 if ($submissions) {
2084 list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
9695ff81 2085 list($sort, $sortparams) = users_order_by_sql('r');
a327f25e 2086 $picturefields = user_picture::fields('r', array(), 'reviewerid');
581878b8 2087 $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,
a327f25e 2088 $picturefields, s.id AS submissionid, s.authorid
29dc43e7
DM
2089 FROM {workshop_assessments} a
2090 JOIN {user} r ON (a.reviewerid = r.id)
0324b6f1 2091 JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
c6b784f0 2092 WHERE a.submissionid $submissionids
9695ff81
TH
2093 ORDER BY a.weight DESC, $sort";
2094 $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
29dc43e7
DM
2095 foreach ($reviewers as $reviewer) {
2096 if (!isset($userinfo[$reviewer->reviewerid])) {
7a789aa8 2097 $userinfo[$reviewer->reviewerid] = new stdclass();
29dc43e7 2098 $userinfo[$reviewer->reviewerid]->id = $reviewer->reviewerid;
29dc43e7
DM
2099 $userinfo[$reviewer->reviewerid]->picture = $reviewer->picture;
2100 $userinfo[$reviewer->reviewerid]->imagealt = $reviewer->imagealt;
3a11c09f 2101 $userinfo[$reviewer->reviewerid]->email = $reviewer->email;
a327f25e
AG
2102 foreach ($additionalnames as $addname) {
2103 $userinfo[$reviewer->reviewerid]->$addname = $reviewer->$addname;
2104 }
29dc43e7
DM
2105 }
2106 }
2107 }
2108
5e71cefb 2109 // get the user details for all reviewees of the displayed participants
934329e5
DM
2110 $reviewees = array();
2111 if ($participants) {
2112 list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
9695ff81 2113 list($sort, $sortparams) = users_order_by_sql('e');
934329e5 2114 $params['workshopid'] = $this->id;
a327f25e 2115 $picturefields = user_picture::fields('e', array(), 'authorid');
581878b8 2116 $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,
a327f25e 2117 s.id AS submissionid, $picturefields
934329e5
DM
2118 FROM {user} u
2119 JOIN {workshop_assessments} a ON (a.reviewerid = u.id)
0324b6f1 2120 JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
934329e5 2121 JOIN {user} e ON (s.authorid = e.id)
c6b784f0 2122 WHERE u.id $participantids AND s.workshopid = :workshopid
9695ff81 2123 ORDER BY a.weight DESC, $sort";
462b4c12 2124 $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
934329e5
DM
2125 foreach ($reviewees as $reviewee) {
2126 if (!isset($userinfo[$reviewee->authorid])) {
7a789aa8 2127 $userinfo[$reviewee->authorid] = new stdclass();
934329e5 2128 $userinfo[$reviewee->authorid]->id = $reviewee->authorid;
934329e5
DM
2129 $userinfo[$reviewee->authorid]->picture = $reviewee->picture;
2130 $userinfo[$reviewee->authorid]->imagealt = $reviewee->imagealt;
3a11c09f 2131 $userinfo[$reviewee->authorid]->email = $reviewee->email;
a327f25e
AG
2132 foreach ($additionalnames as $addname) {
2133 $userinfo[$reviewee->authorid]->$addname = $reviewee->$addname;
2134 }
934329e5 2135 }
29dc43e7
DM
2136 }
2137 }
2138
5e71cefb
DM
2139 // finally populate the object to be rendered
2140 $grades = $participants;
29dc43e7
DM
2141
2142 foreach ($participants as $participant) {
2143 // set up default (null) values
d183140d
DM
2144 $grades[$participant->userid]->submissionid = null;
2145 $grades[$participant->userid]->submissiontitle = null;
2146 $grades[$participant->userid]->submissiongrade = null;
2147 $grades[$participant->userid]->submissiongradeover = null;
2148 $grades[$participant->userid]->submissiongradeoverby = null;
232175e4 2149 $grades[$participant->userid]->submissionpublished = null;
5e71cefb
DM
2150 $grades[$participant->userid]->reviewedby = array();
2151 $grades[$participant->userid]->reviewerof = array();
29dc43e7
DM
2152 }
2153 unset($participants);
2154 unset($participant);
2155
2156 foreach ($submissions as $submission) {
2157 $grades[$submission->authorid]->submissionid = $submission->id;
2158 $grades[$submission->authorid]->submissiontitle = $submission->title;
b4857acb
DM
2159 $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
2160 $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
29dc43e7 2161 $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
232175e4 2162 $grades[$submission->authorid]->submissionpublished = $submission->published;
29dc43e7
DM
2163 }
2164 unset($submissions);
2165 unset($submission);
2166
2167 foreach($reviewers as $reviewer) {
7a789aa8 2168 $info = new stdclass();
29dc43e7
DM
2169 $info->userid = $reviewer->reviewerid;
2170 $info->assessmentid = $reviewer->assessmentid;
2171 $info->submissionid = $reviewer->submissionid;
b4857acb
DM
2172 $info->grade = $this->real_grade($reviewer->grade);
2173 $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
2174 $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
581878b8 2175 $info->weight = $reviewer->weight;
29dc43e7
DM
2176 $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
2177 }
2178 unset($reviewers);
2179 unset($reviewer);
2180
2181 foreach($reviewees as $reviewee) {
7a789aa8 2182 $info = new stdclass();
29dc43e7
DM
2183 $info->userid = $reviewee->authorid;
2184 $info->assessmentid = $reviewee->assessmentid;
2185 $info->submissionid = $reviewee->submissionid;
b4857acb
DM
2186 $info->grade = $this->real_grade($reviewee->grade);
2187 $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
2188 $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
581878b8 2189 $info->weight = $reviewee->weight;
29dc43e7
DM
2190 $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
2191 }
2192 unset($reviewees);
2193 unset($reviewee);
2194
b4857acb
DM
2195 foreach ($grades as $grade) {
2196 $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
b4857acb
DM
2197 }
2198
7a789aa8 2199 $data = new stdclass();
29dc43e7
DM
2200 $data->grades = $grades;
2201 $data->userinfo = $userinfo;
2202 $data->totalcount = $numofparticipants;
b4857acb
DM
2203 $data->maxgrade = $this->real_grade(100);
2204 $data->maxgradinggrade = $this->real_grading_grade(100);
29dc43e7
DM
2205 return $data;
2206 }
2207
29dc43e7 2208 /**
b4857acb 2209 * Calculates the real value of a grade
29dc43e7 2210 *
b4857acb
DM
2211 * @param float $value percentual value from 0 to 100
2212 * @param float $max the maximal grade
2213 * @return string
2214 */
2215 public function real_grade_value($value, $max) {
2216 $localized = true;
557a1100 2217 if (is_null($value) or $value === '') {
b4857acb
DM
2218 return null;
2219 } elseif ($max == 0) {
2220 return 0;
2221 } else {
2222 return format_float($max * $value / 100, $this->gradedecimals, $localized);
2223 }
2224 }
2225
e554671d
DM
2226 /**
2227 * Calculates the raw (percentual) value from a real grade
2228 *
2229 * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save
2230 * this value in a raw percentual form into DB
2231 * @param float $value given grade
2232 * @param float $max the maximal grade
2233 * @return float suitable to be stored as numeric(10,5)
2234 */
2235 public function raw_grade_value($value, $max) {
557a1100 2236 if (is_null($value) or $value === '') {
e554671d
DM
2237 return null;
2238 }
2239 if ($max == 0 or $value < 0) {
2240 return 0;
2241 }
2242 $p = $value / $max * 100;
2243 if ($p > 100) {
2244 return $max;
2245 }
2246 return grade_floatval($p);
2247 }
2248
b4857acb
DM
2249 /**
2250 * Calculates the real value of grade for submission
2251 *
2252 * @param float $value percentual value from 0 to 100
2253 * @return string
2254 */
2255 public function real_grade($value) {
2256 return $this->real_grade_value($value, $this->grade);
2257 }
2258
2259 /**
2260 * Calculates the real value of grade for assessment
2261 *
2262 * @param float $value percentual value from 0 to 100
2263 * @return string
2264 */
2265 public function real_grading_grade($value) {
2266 return $this->real_grade_value($value, $this->gradinggrade);
29dc43e7
DM
2267 }
2268
e706b9c3
DM
2269 /**
2270 * Sets the given grades and received grading grades to null
2271 *
2272 * This does not clear the information about how the peers filled the assessment forms, but
2273 * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess
2274 * the allocated submissions.
2275 *
2276 * @return void
2277 */
2278 public function clear_assessments() {
2279 global $DB;
2280
2281 $submissions = $this->get_submissions();
2282 if (empty($submissions)) {
2283 // no money, no love
2284 return;
2285 }
2286 $submissions = array_keys($submissions);
2287 list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED);
2288 $sql = "submissionid $sql";
2289 $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params);
2290 $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params);
2291 }
2292
32c78bc3
DM
2293 /**
2294 * Sets the grades for submission to null
2295 *
2296 * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2297 * @return void
2298 */
2299 public function clear_submission_grades($restrict=null) {
2300 global $DB;
2301
2302 $sql = "workshopid = :workshopid AND example = 0";
2303 $params = array('workshopid' => $this->id);
2304
2305 if (is_null($restrict)) {
2306 // update all users - no more conditions
2307 } elseif (!empty($restrict)) {
2308 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2309 $sql .= " AND authorid $usql";
2310 $params = array_merge($params, $uparams);
2311 } else {
2312 throw new coding_exception('Empty value is not a valid parameter here');
2313 }
2314
2315 $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
2316 }
2317
89c1aa97 2318 /**
e9a90e69 2319 * Calculates grades for submission for the given participant(s) and updates it in the database
89c1aa97
DM
2320 *
2321 * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2322 * @return void
2323 */
8a1ba8ac 2324 public function aggregate_submission_grades($restrict=null) {
89c1aa97
DM
2325 global $DB;
2326
2327 // fetch a recordset with all assessments to process
1696f36c 2328 $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
89c1aa97
DM
2329 a.weight, a.grade
2330 FROM {workshop_submissions} s
2331 LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id)
2332 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2333 $params = array('workshopid' => $this->id);
2334
2335 if (is_null($restrict)) {
2336 // update all users - no more conditions
2337 } elseif (!empty($restrict)) {
2338 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2339 $sql .= " AND s.authorid $usql";
2340 $params = array_merge($params, $uparams);
2341 } else {
2342 throw new coding_exception('Empty value is not a valid parameter here');
2343 }
2344
2345 $sql .= ' ORDER BY s.id'; // this is important for bulk processing
89c1aa97 2346
e9a90e69
DM
2347 $rs = $DB->get_recordset_sql($sql, $params);
2348 $batch = array(); // will contain a set of all assessments of a single submission
2349 $previous = null; // a previous record in the recordset
2350
89c1aa97
DM
2351 foreach ($rs as $current) {
2352 if (is_null($previous)) {
2353 // we are processing the very first record in the recordset
2354 $previous = $current;
89c1aa97 2355 }
e9a90e69 2356 if ($current->submissionid == $previous->submissionid) {
89c1aa97 2357 // we are still processing the current submission
e9a90e69
DM
2358 $batch[] = $current;
2359 } else {
2360 // process all the assessments of a sigle submission
2361 $this->aggregate_submission_grades_process($batch);
2362 // and then start to process another submission
2363 $batch = array($current);
2364 $previous = $current;
89c1aa97
DM
2365 }
2366 }
e9a90e69
DM
2367 // do not forget to process the last batch!
2368 $this->aggregate_submission_grades_process($batch);
89c1aa97
DM
2369 $rs->close();
2370 }
2371
32c78bc3
DM
2372 /**
2373 * Sets the aggregated grades for assessment to null
2374 *
2375 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2376 * @return void
2377 */
2378 public function clear_grading_grades($restrict=null) {
2379 global $DB;
2380
2381 $sql = "workshopid = :workshopid";
2382 $params = array('workshopid' => $this->id);
2383
2384 if (is_null($restrict)) {
2385 // update all users - no more conditions
2386 } elseif (!empty($restrict)) {
2387 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2388 $sql .= " AND userid $usql";
2389 $params = array_merge($params, $uparams);
2390 } else {
2391 throw new coding_exception('Empty value is not a valid parameter here');
2392 }
2393
2394 $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
2395 }
2396
89c1aa97
DM
2397 /**
2398 * Calculates grades for assessment for the given participant(s)
2399 *
39411930
DM
2400 * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator.
2401 * The assessment weight is not taken into account here.
89c1aa97
DM
2402 *
2403 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2404 * @return void
2405 */
8a1ba8ac 2406 public function aggregate_grading_grades($restrict=null) {
89c1aa97
DM
2407 global $DB;
2408
39411930
DM
2409 // fetch a recordset with all assessments to process
2410 $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover,
2411 ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade
2412 FROM {workshop_assessments} a
2413 INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
2414 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid)
2415 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2416 $params = array('workshopid' => $this->id);
2417
2418 if (is_null($restrict)) {
2419 // update all users - no more conditions
2420 } elseif (!empty($restrict)) {
2421 list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2422 $sql .= " AND a.reviewerid $usql";
2423 $params = array_merge($params, $uparams);
2424 } else {
2425 throw new coding_exception('Empty value is not a valid parameter here');
2426 }
2427
2428 $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing
2429
2430 $rs = $DB->get_recordset_sql($sql, $params);
2431 $batch = array(); // will contain a set of all assessments of a single submission
2432 $previous = null; // a previous record in the recordset
2433
2434 foreach ($rs as $current) {
2435 if (is_null($previous)) {
2436 // we are processing the very first record in the recordset
2437 $previous = $current;
2438 }
2439 if ($current->reviewerid == $previous->reviewerid) {
2440 // we are still processing the current reviewer
2441 $batch[] = $current;
2442 } else {
2443 // process all the assessments of a sigle submission
2444 $this->aggregate_grading_grades_process($batch);
2445 // and then start to process another reviewer
2446 $batch = array($current);
2447 $previous = $current;
2448 }
2449 }
2450 // do not forget to process the last batch!
2451 $this->aggregate_grading_grades_process($batch);
2452 $rs->close();
89c1aa97
DM
2453 }
2454
77f43e7d 2455 /**
f6e8b318 2456 * Returns the mform the teachers use to put a feedback for the reviewer
77f43e7d 2457 *
c6b784f0 2458 * @param moodle_url $actionurl
5924db72 2459 * @param stdClass $assessment
c6b784f0 2460 * @param array $options editable, editableweight, overridablegradinggrade
f6e8b318 2461 * @return workshop_feedbackreviewer_form
77f43e7d 2462 */
c6b784f0 2463 public function get_feedbackreviewer_form(moodle_url $actionurl, stdclass $assessment, $options=array()) {
77f43e7d 2464 global $CFG;
1fcf0ca8 2465 require_once(__DIR__ . '/feedbackreviewer_form.php');
77f43e7d 2466
7a789aa8 2467 $current = new stdclass();
e554671d 2468 $current->asid = $assessment->id;
c6b784f0 2469 $current->weight = $assessment->weight;
e554671d
DM
2470 $current->gradinggrade = $this->real_grading_grade($assessment->gradinggrade);
2471 $current->gradinggradeover = $this->real_grading_grade($assessment->gradinggradeover);
2472 $current->feedbackreviewer = $assessment->feedbackreviewer;
2473 $current->feedbackreviewerformat = $assessment->feedbackreviewerformat;
2474 if (is_null($current->gradinggrade)) {
2475 $current->gradinggrade = get_string('nullgrade', 'workshop');
2476 }
c6b784f0
DM
2477 if (!isset($options['editable'])) {
2478 $editable = true; // by default
2479 } else {
2480 $editable = (bool)$options['editable'];
2481 }
e554671d
DM
2482
2483 // prepare wysiwyg editor
2484 $current = file_prepare_standard_editor($current, 'feedbackreviewer', array());
2485
77f43e7d 2486 return new workshop_feedbackreviewer_form($actionurl,
c6b784f0 2487 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
77f43e7d
DM
2488 'post', '', null, $editable);
2489 }
2490
67cd00ba
DM
2491 /**
2492 * Returns the mform the teachers use to put a feedback for the author on their submission
2493 *
c6b784f0 2494 * @param moodle_url $actionurl
5924db72 2495 * @param stdClass $submission
c6b784f0 2496 * @param array $options editable
67cd00ba
DM
2497 * @return workshop_feedbackauthor_form
2498 */
c6b784f0 2499 public function get_feedbackauthor_form(moodle_url $actionurl, stdclass $submission, $options=array()) {
67cd00ba 2500 global $CFG;
1fcf0ca8 2501 require_once(__DIR__ . '/feedbackauthor_form.php');
67cd00ba 2502
7a789aa8 2503 $current = new stdclass();
67cd00ba 2504 $current->submissionid = $submission->id;
232175e4 2505 $current->published = $submission->published;
557a1100
DM
2506 $current->grade = $this->real_grade($submission->grade);
2507 $current->gradeover = $this->real_grade($submission->gradeover);
2508 $current->feedbackauthor = $submission->feedbackauthor;
2509 $current->feedbackauthorformat = $submission->feedbackauthorformat;
67cd00ba
DM
2510 if (is_null($current->grade)) {
2511 $current->grade = get_string('nullgrade', 'workshop');
2512 }
c6b784f0
DM
2513 if (!isset($options['editable'])) {
2514 $editable = true; // by default
2515 } else {
2516 $editable = (bool)$options['editable'];
2517 }
67cd00ba
DM
2518
2519 // prepare wysiwyg editor
2520 $current = file_prepare_standard_editor($current, 'feedbackauthor', array());
2521
2522 return new workshop_feedbackauthor_form($actionurl,
232175e4 2523 array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
67cd00ba
DM
2524 'post', '', null, $editable);
2525 }
2526
3cb4ce45
DM
2527 /**
2528 * Returns the information about the user's grades as they are stored in the gradebook
2529 *
2530 * The submission grade is returned for users with the capability mod/workshop:submit and the
2531 * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
2532 * user has the capability to view hidden grades, grades must be visible to be returned. Null
2533 * grades are not returned. If none grade is to be returned, this method returns false.
2534 *
2535 * @param int $userid the user's id
2536 * @return workshop_final_grades|false
2537 */
2538 public function get_gradebook_grades($userid) {
2539 global $CFG;
2540 require_once($CFG->libdir.'/gradelib.php');
2541
2542 if (empty($userid)) {
2543 throw new coding_exception('User id expected, empty value given.');
2544 }
2545
2546 // Read data via the Gradebook API
2547 $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
2548
2549 $grades = new workshop_final_grades();
2550
2551 if (has_capability('mod/workshop:submit', $this->context, $userid)) {
2552 if (!empty($gradebook->items[0]->grades)) {
2553 $submissiongrade = reset($gradebook->items[0]->grades);
2554 if (!is_null($submissiongrade->grade)) {
2555 if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2556 $grades->submissiongrade = $submissiongrade;
2557 }
2558 }
2559 }
2560 }
2561
d34ea7dc 2562 if (has_capability('mod/workshop:peerassess', $this->context, $userid)) {
3cb4ce45
DM
2563 if (!empty($gradebook->items[1]->grades)) {
2564 $assessmentgrade = reset($gradebook->items[1]->grades);
2565 if (!is_null($assessmentgrade->grade)) {
2566 if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2567 $grades->assessmentgrade = $assessmentgrade;
2568 }
2569 }
2570 }
2571 }
2572
2573 if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
2574 return $grades;
2575 }
2576
2577 return false;
2578 }
2579
996f7e82
DM
2580 /**
2581 * Return the editor options for the submission content field.
2582 *
2583 * @return array
2584 */
2585 public function submission_content_options() {
21d49a3f
DM
2586 global $CFG;
2587 require_once($CFG->dirroot.'/repository/lib.php');
2588
996f7e82
DM
2589 return array(
2590 'trusttext' => true,
2591 'subdirs' => false,
2592 'maxfiles' => $this->nattachments,
2593 'maxbytes' => $this->maxbytes,
2594 'context' => $this->context,
2595 'return_types' => FILE_INTERNAL | FILE_EXTERNAL,
2596 );
2597 }
2598
2599 /**
2600 * Return the filemanager options for the submission attachments field.
2601 *
2602 * @return array
2603 */
2604 public function submission_attachment_options() {
21d49a3f
DM
2605 global $CFG;
2606 require_once($CFG->dirroot.'/repository/lib.php');
996f7e82
DM
2607
2608 $options = array(
2609 'subdirs' => true,
2610 'maxfiles' => $this->nattachments,
2611 'maxbytes' => $this->maxbytes,
151b0f94 2612 'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
996f7e82
DM
2613 );
2614
5a0865a1 2615 $filetypesutil = new \core_form\filetypes_util();
afa6deec 2616 $options['accepted_types'] = $filetypesutil->normalize_file_types($this->submissionfiletypes);
996f7e82
DM
2617
2618 return $options;
2619 }
2620
77d746a2
DM
2621 /**
2622 * Return the editor options for the overall feedback for the author.
2623 *
2624 * @return array
2625 */
2626 public function overall_feedback_content_options() {
21d49a3f
DM
2627 global $CFG;
2628 require_once($CFG->dirroot.'/repository/lib.php');
2629
77d746a2
DM
2630 return array(
2631 'subdirs' => 0,
2632 'maxbytes' => $this->overallfeedbackmaxbytes,
2633 'maxfiles' => $this->overallfeedbackfiles,
2634 'changeformat' => 1,
2635 'context' => $this->context,
21d49a3f 2636 'return_types' => FILE_INTERNAL,
77d746a2
DM
2637 );
2638 }
2639
2640 /**
2641 * Return the filemanager options for the overall feedback for the author.
2642 *
2643 * @return array
2644 */
2645 public function overall_feedback_attachment_options() {
21d49a3f
DM
2646 global $CFG;
2647 require_once($CFG->dirroot.'/repository/lib.php');
996f7e82
DM
2648
2649 $options = array(
77d746a2
DM
2650 'subdirs' => 1,
2651 'maxbytes' => $this->overallfeedbackmaxbytes,
2652 'maxfiles' => $this->overallfeedbackfiles,
151b0f94 2653 'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
77d746a2 2654 );
996f7e82 2655
5a0865a1
DM
2656 $filetypesutil = new \core_form\filetypes_util();
2657 $options['accepted_types'] = $filetypesutil->normalize_file_types($this->overallfeedbackfiletypes);
996f7e82
DM
2658
2659 return $options;
77d746a2
DM
2660 }
2661
f2639dca
DM
2662 /**
2663 * Performs the reset of this workshop instance.
2664 *
2665 * @param stdClass $data The actual course reset settings.
2666 * @return array List of results, each being array[(string)component, (string)item, (string)error]
2667 */
2668 public function reset_userdata(stdClass $data) {
2669
2670 $componentstr = get_string('pluginname', 'workshop').': '.format_string($this->name);
2671 $status = array();
2672
2673 if (!empty($data->reset_workshop_assessments) or !empty($data->reset_workshop_submissions)) {
2674 // Reset all data related to assessments, including assessments of
2675 // example submissions.
2676 $result = $this->reset_userdata_assessments($data);
2677 if ($result === true) {
2678 $status[] = array(
2679 'component' => $componentstr,
2680 'item' => get_string('resetassessments', 'mod_workshop'),
2681 'error' => false,
2682 );
2683 } else {
2684 $status[] = array(
2685 'component' => $componentstr,
2686 'item' => get_string('resetassessments', 'mod_workshop'),
2687 'error' => $result,
2688 );
2689 }
2690 }
2691
2692 if (!empty($data->reset_workshop_submissions)) {
2693 // Reset all remaining data related to submissions.
2694 $result = $this->reset_userdata_submissions($data);
2695 if ($result === true) {
2696 $status[] = array(
2697 'component' => $componentstr,
2698 'item' => get_string('resetsubmissions', 'mod_workshop'),
2699 'error' => false,
2700 );
2701 } else {
2702 $status[] = array(
2703 'component' => $componentstr,
2704 'item' => get_string('resetsubmissions', 'mod_workshop'),
2705 'error' => $result,
2706 );
2707 }
2708 }
2709
2710 if (!empty($data->reset_workshop_phase)) {
2711 // Do not use the {@link workshop::switch_phase()} here, we do not
2712 // want to trigger events.
2713 $this->reset_phase();
2714 $status[] = array(
2715 'component' => $componentstr,
2716 'item' => get_string('resetsubmissions', 'mod_workshop'),
2717 'error' => false,
2718 );
2719 }
2720
2721 return $status;
2722 }
2723
931bba60
DM
2724 /**
2725 * Check if the current user can access the other user's group.
2726 *
2727 * This is typically used for teacher roles that have permissions like
2728 * 'view all submissions'. Even with such a permission granted, we have to
2729 * check the workshop activity group mode.
2730 *
2731 * If the workshop is not in a group mode, or if it is in the visible group
2732 * mode, this method returns true. This is consistent with how the
2733 * {@link groups_get_activity_allowed_groups()} behaves.
2734 *
2735 * If the workshop is in a separate group mode, the current user has to
2736 * have the 'access all groups' permission, or share at least one
2737 * accessible group with the other user.
2738 *
2739 * @param int $otheruserid The ID of the other user, e.g. the author of a submission.
2740 * @return bool False if the current user cannot access the other user's group.
2741 */
2742 public function check_group_membership($otheruserid) {
2743 global $USER;
2744
2745 if (groups_get_activity_groupmode($this->cm) != SEPARATEGROUPS) {
2746 // The workshop is not in a group mode, or it is in a visible group mode.
2747 return true;
2748
2749 } else if (has_capability('moodle/site:accessallgroups', $this->context)) {
2750 // The current user can access all groups.
2751 return true;
2752
2753 } else {
2754 $thisusersgroups = groups_get_all_groups($this->course->id, $USER->id, $this->cm->groupingid, 'g.id');
2755 $otherusersgroups = groups_get_all_groups($this->course->id, $otheruserid, $this->cm->groupingid, 'g.id');
2756 $commongroups = array_intersect_key($thisusersgroups, $otherusersgroups);
2757
2758 if (empty($commongroups)) {
2759 // The current user has no group common with the other user.
2760 return false;
2761
2762 } else {
2763 // The current user has a group common with the other user.
2764 return true;
2765 }
2766 }
2767 }
f2639dca 2768
4c776cae 2769 /**
86928d2a 2770 * Check whether the given user has assessed all his required examples before submission.
4c776cae
JL
2771 *
2772 * @param int $userid the user to check
2773 * @return bool false if there are examples missing assessment, true otherwise.
2774 * @since Moodle 3.4
2775 */
86928d2a 2776 public function check_examples_assessed_before_submission($userid) {
4c776cae
JL
2777
2778 if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_SUBMISSION
2779 and !has_capability('mod/workshop:manageexamples', $this->context)) {
2780
2781 // Check that all required examples have been assessed by the user.
2782 $examples = $this->get_examples_for_reviewer($userid);
2783 foreach ($examples as $exampleid => $example) {
2784 if (is_null($example->assessmentid)) {
2785 $examples[$exampleid]->assessmentid = $this->add_allocation($example, $userid, 0);
2786 }
2787 if (is_null($example->grade)) {
2788 return false;
2789 }
2790 }
2791 }
2792 return true;
2793 }
2794
86928d2a
JL
2795 /**
2796 * Check that all required examples have been assessed by the given user.
2797 *
2798 * @param stdClass $userid the user (reviewer) to check
2799 * @return mixed bool|state false and notice code if there are examples missing assessment, true otherwise.
2800 * @since Moodle 3.4
2801 */
2802 public function check_examples_assessed_before_assessment($userid) {
2803
2804 if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_ASSESSMENT
2805 and !has_capability('mod/workshop:manageexamples', $this->context)) {
2806
2807 // The reviewer must have submitted their own submission.
2808 $reviewersubmission = $this->get_submission_by_author($userid);
2809 if (!$reviewersubmission) {
2810 // No money, no love.
2811 return array(false, 'exampleneedsubmission');
2812 } else {
2813 $examples = $this->get_examples_for_reviewer($userid);
2814 foreach ($examples as $exampleid => $example) {
2815 if (is_null($example->grade)) {
2816 return array(false, 'exampleneedassessed');
2817 }
2818 }
2819 }
2820 }
2821 return array(true, null);
2822 }
2823
31496dde
JL
2824 /**
2825 * Trigger module viewed event and set the module viewed for completion.
2826 *
2827 * @since Moodle 3.4
2828 */
2829 public function set_module_viewed() {
2830 global $CFG;
2831 require_once($CFG->libdir . '/completionlib.php');
2832
2833 // Mark viewed.
2834 $completion = new completion_info($this->course);
2835 $completion->set_module_viewed($this->cm);
2836
2837 $eventdata = array();
2838 $eventdata['objectid'] = $this->id;
2839 $eventdata['context'] = $this->context;
2840
2841 // Trigger module viewed event.
2842 $event = \mod_workshop\event\course_module_viewed::create($eventdata);
2843 $event->add_record_snapshot('course', $this->course);
2844 $event->add_record_snapshot('workshop', $this->dbrecord);
2845 $event->add_record_snapshot('course_modules', $this->cm);
2846 $event->trigger();
2847 }
2848
4c776cae
JL
2849 /**
2850 * Validates the submission form or WS data.
2851 *
2852 * @param array $data the data to be validated
2853 * @return array the validation errors (if any)
2854 * @since Moodle 3.4
2855 */
2856 public function validate_submission_data($data) {
2857 global $DB, $USER;
2858
2859 $errors = array();
2860 if (empty($data['id']) and empty($data['example'])) {
2861 // Make sure there is no submission saved meanwhile from another browser window.
2862 $sql = "SELECT COUNT(s.id)
2863 FROM {workshop_submissions} s
2864 JOIN {workshop} w ON (s.workshopid = w.id)
2865 JOIN {course_modules} cm ON (w.id = cm.instance)
2866 JOIN {modules} m ON (m.name = 'workshop' AND m.id = cm.module)
2867 WHERE cm.id = ? AND s.authorid = ? AND s.example = 0";
2868
2869 if ($DB->count_records_sql($sql, array($data['cmid'], $USER->id))) {
2870 $errors['title'] = get_string('err_multiplesubmissions', 'mod_workshop');
2871 }
2872 }
2873
2874 $getfiles = file_get_drafarea_files($data['attachment_filemanager']);
2875 if (empty($getfiles->list) and html_is_blank($data['content_editor']['text'])) {
2876 $errors['content_editor'] = get_string('submissionrequiredcontent', 'mod_workshop');
2877 $errors['attachment_filemanager'] = get_string('submissionrequiredfile', 'mod_workshop');
2878 }
2879
2880 return $errors;
2881 }
2882
2883 /**
2884 * Adds or updates a submission.
2885 *
2886 * @param stdClass $submission The submissin data (via form or via WS).
2887 * @return the new or updated submission id.
2888 * @since Moodle 3.4
2889 */
2890 public function edit_submission($submission) {
2891 global $USER, $DB;
2892
2893 if ($submission->example == 0) {
2894 // This was used just for validation, it must be set to zero when dealing with normal submissions.
2895 unset($submission->example);
2896 } else {
2897 throw new coding_exception('Invalid submission form data value: example');
2898 }
2899 $timenow = time();
2900 if (is_null($submission->id)) {
2901 $submission->workshopid = $this->id;
2902 $submission->example = 0;
2903 $submission->authorid = $USER->id;
2904 $submission->timecreated = $timenow;
2905 $submission->feedbackauthorformat = editors_get_preferred_format();
2906 }
2907 $submission->timemodified = $timenow;
2908 $submission->title = trim($submission->title);
2909 $submission->content = ''; // Updated later.
2910 $submission->contentformat = FORMAT_HTML; // Updated later.
2911 $submission->contenttrust = 0; // Updated later.
2912 $submission->late = 0x0; // Bit mask.
2913 if (!empty($this->submissionend) and ($this->submissionend < time())) {
2914 $submission->late = $submission->late | 0x1;
2915 }
2916 if ($this->phase == self::PHASE_ASSESSMENT) {
2917 $submission->late = $submission->late | 0x2;
2918 }
2919
2920 // Event information.
2921 $params = array(
2922 'context' => $this->context,
2923 'courseid' => $this->course->id,
2924 'other' => array(
2925 'submissiontitle' => $submission->title
2926 )
2927 );
2928 $logdata = null;
2929 if (is_null($submission->id)) {
2930 $submission->id = $DB->insert_record('workshop_submissions', $submission);
2931 $params['objectid'] = $submission->id;
2932 $event = \mod_workshop\event\submission_created::create($params);
2933 $event->trigger();
2934 } else {
2935 if (empty($submission->id) or empty($submission->id) or ($submission->id != $submission->id)) {
2936 throw new moodle_exception('err_submissionid', 'workshop');
2937 }
2938 }
2939 $params['objectid'] = $submission->id;
2940
2941 // Save and relink embedded images and save attachments.
2942 $submission = file_postupdate_standard_editor($submission, 'content', $this->submission_content_options(),
2943 $this->context, 'mod_workshop', 'submission_content', $submission->id);
2944
2945 $submission = file_postupdate_standard_filemanager($submission, 'attachment', $this->submission_attachment_options(),
2946 $this->context, 'mod_workshop', 'submission_attachment', $submission->id);
2947
2948 if (empty($submission->attachment)) {
2949 // Explicit cast to zero integer.
2950 $submission->attachment = 0;
2951 }
2952 // Store the updated values or re-save the new submission (re-saving needed because URLs are now rewritten).
2953 $DB->update_record('workshop_submissions', $submission);
2954 $event = \mod_workshop\event\submission_updated::create($params);
2955 $event->add_record_snapshot('workshop', $this->dbrecord);
2956 $event->trigger();
2957
2958 // Send submitted content for plagiarism detection.
2959 $fs = get_file_storage();
2960 $files = $fs->get_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
2961
2962 $params['other']['content'] = $submission->content;
2963 $params['other']['pathnamehashes'] = array_keys($files);
2964
2965 $event = \mod_workshop\event\assessable_uploaded::create($params);
2966 $event->set_legacy_logdata($logdata);
2967 $event->trigger();
2968
2969 return $submission->id;
2970 }
2971
b1e896cf
JL
2972 /**
2973 * Helper method for validating if the current user can view the given assessment.
2974 *
2975 * @param stdClass $assessment assessment object
2976 * @param stdClass $submission submission object
2977 * @return void
2978 * @throws moodle_exception
2979 * @since Moodle 3.4
2980 */
2981 public function check_view_assessment($assessment, $submission) {
2982 global $USER;
2983
2984 $isauthor = $submission->authorid == $USER->id;
2985 $isreviewer = $assessment->reviewerid == $USER->id;
2986 $canviewallassessments = has_capability('mod/workshop:viewallassessments', $this->context);
2987 $canviewallsubmissions = has_capability('mod/workshop:viewallsubmissions', $this->context);
2988
2989 $canviewallsubmissions = $canviewallsubmissions && $this->check_group_membership($submission->authorid);
2990
2991 if (!$isreviewer and !$isauthor and !($canviewallassessments and $canviewallsubmissions)) {
2992 print_error('nopermissions', 'error', $this->view_url(), 'view this assessment');
2993 }
2994
2995 if ($isauthor and !$isreviewer and !$canviewallassessments and $this->phase != self::PHASE_CLOSED) {
2996 // Authors can see assessments of their work at the end of workshop only.
2997 print_error('nopermissions', 'error', $this->view_url(), 'view assessment of own work before workshop is closed');
2998 }
2999 }
3000
46f5e9a0
JL
3001 /**
3002 * Helper method for validating if the current user can edit the given assessment.
3003 *
3004 * @param stdClass $assessment assessment object
3005 * @param stdClass $submission submission object
3006 * @return void
3007 * @throws moodle_exception
3008 * @since Moodle 3.4
3009 */
3010 public function check_edit_assessment($assessment, $submission) {
3011 global $USER;
3012
3013 $this->check_view_assessment($assessment, $submission);
3014 // Further checks.
3015 $isreviewer = ($USER->id == $assessment->reviewerid);
3016
3017 $assessmenteditable = $isreviewer && $this->assessing_allowed($USER->id);
3018 if (!$assessmenteditable) {
3019 throw new moodle_exception('nopermissions', 'error', '', 'edit assessments');
3020 }
3021
3022 list($assessed, $notice) = $this->check_examples_assessed_before_assessment($assessment->reviewerid);
3023 if (!$assessed) {
3024 throw new moodle_exception($notice, 'mod_workshop');
3025 }
3026 }
3027
57f44fba
JL
3028 /**
3029 * Adds information to an allocated assessment (function used the first time a review is done or when updating an existing one).
3030 *
3031 * @param stdClass $assessment the assessment
3032 * @param stdClass $submission the submission
3033 * @param stdClass $data the assessment data to be added or Updated
3034 * @param stdClass $strategy the strategy instance
3035 * @return float|null Raw percentual grade (0.00000 to 100.00000) for submission
3036 * @since Moodle 3.4
3037 */
3038 public function edit_assessment($assessment, $submission, $data, $strategy) {
3039 global $DB;
3040
3041 $cansetassessmentweight = has_capability('mod/workshop:allocate', $this->context);
3042
3043 // Let the grading strategy subplugin save its data.
3044 $rawgrade = $strategy->save_assessment($assessment, $data);
3045
3046 // Store the data managed by the workshop core.
3047 $coredata = (object)array('id' => $assessment->id);
3048 if (isset($data->feedbackauthor_editor)) {
3049 $coredata->feedbackauthor_editor = $data->feedbackauthor_editor;
3050 $coredata = file_postupdate_standard_editor($coredata, 'feedbackauthor', $this->overall_feedback_content_options(),
3051 $this->context, 'mod_workshop', 'overallfeedback_content', $assessment->id);
3052 unset($coredata->feedbackauthor_editor);
3053 }
3054 if (isset($data->feedbackauthorattachment_filemanager)) {
3055 $coredata->feedbackauthorattachment_filemanager = $data->feedbackauthorattachment_filemanager;
3056 $coredata = file_postupdate_standard_filemanager($coredata, 'feedbackauthorattachment',
3057 $this->overall_feedback_attachment_options(), $this->context, 'mod_workshop', 'overallfeedback_attachment',
3058 $assessment->id);
3059 unset($coredata->feedbackauthorattachment_filemanager);
3060 if (empty($coredata->feedbackauthorattachment)) {
3061 $coredata->feedbackauthorattachment = 0;
3062 }
3063 }
3064 if (isset($data->weight) and $cansetassessmentweight) {
3065 $coredata->weight = $data->weight;
3066 }
3067 // Update the assessment data if there is something other than just the 'id'.
3068 if (count((array)$coredata) > 1 ) {
3069 $DB->update_record('workshop_assessments', $coredata);
3070 $params = array(
3071 'relateduserid' => $submission->authorid,
3072 'objectid' => $assessment->id,
3073 'context' => $this->context,
3074 'other' => array(
3075 'workshopid' => $this->id,
3076 'submissionid' => $assessment->submissionid
3077 )
3078 );
3079
3080 if (is_null($assessment->grade)) {
3081 // All workshop_assessments are created when allocations are made. The create event is of more use located here.
3082 $event = \mod_workshop\event\submission_assessed::create($params);
3083 $event->trigger();
3084 } else {
3085 $params['other']['grade'] = $assessment->grade;
3086 $event = \mod_workshop\event\submission_reassessed::create($params);
3087 $event->trigger();
3088 }
3089 }
3090 return $rawgrade;
3091 }
3092
981f511a
JL
3093 /**
3094 * Evaluates an assessment.
3095 *
3096 * @param stdClass $assessment the assessment
3097 * @param stdClass $data the assessment data to be updated
3098 * @param bool $cansetassessmentweight whether the user can change the assessment weight
3099 * @param bool $canoverridegrades whether the user can override the assessment grades
3100 * @return void
3101 * @since Moodle 3.4
3102 */
3103 public function evaluate_assessment($assessment, $data, $cansetassessmentweight, $canoverridegrades) {
3104 global $DB, $USER;
3105
3106 $data = file_postupdate_standard_editor($data, 'feedbackreviewer', array(), $this->context);
3107 $record = new stdclass();
3108 $record->id = $assessment->id;
3109 if ($cansetassessmentweight) {
3110 $record->weight = $data->weight;
3111 }
3112 if ($canoverridegrades) {
3113 $record->gradinggradeover = $this->raw_grade_value($data->gradinggradeover, $this->gradinggrade);
3114 $record->gradinggradeoverby = $USER->id;
3115 $record->feedbackreviewer = $data->feedbackreviewer;
3116 $record->feedbackreviewerformat = $data->feedbackreviewerformat;
3117 }
3118 $DB->update_record('workshop_assessments', $record);
3119 }
3120
aa40adbf
DM
3121 ////////////////////////////////////////////////////////////////////////////////
3122 // Internal methods (implementation details) //
3123 ////////////////////////////////////////////////////////////////////////////////
6516b9e9 3124
e9a90e69
DM
3125 /**
3126 * Given an array of all assessments of a single submission, calculates the final grade for this submission
3127 *
3128 * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade
3129 * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored.
3130 *
7a789aa8 3131 * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
1fed6ce3 3132 * @return void
e9a90e69
DM
3133 */
3134 protected function aggregate_submission_grades_process(array $assessments) {
3135 global $DB;
3136
3137 $submissionid = null; // the id of the submission being processed
3138 $current = null; // the grade currently saved in database
3139 $finalgrade = null; // the new grade to be calculated
3140 $sumgrades = 0;
3141 $sumweights = 0;
3142
3143 foreach ($assessments as $assessment) {
3144 if (is_null($submissionid)) {
3145 // the id is the same in all records, fetch it during the first loop cycle
3146 $submissionid = $assessment->submissionid;
3147 }
3148 if (is_null($current)) {
3149 // the currently saved grade is the same in all records, fetch it during the first loop cycle
3150 $current = $assessment->submissiongrade;
3151 }
e9a90e69
DM
3152 if (is_null($assessment->grade)) {
3153 // this was not assessed yet
3154 continue;
3155 }
3156 if ($assessment->weight == 0) {
3157 // this does not influence the calculation
3158 continue;
3159 }
3160 $sumgrades += $assessment->grade * $assessment->weight;
3161 $sumweights += $assessment->weight;
3162 }
3163 if ($sumweights > 0 and is_null($finalgrade)) {
3164 $finalgrade = grade_floatval($sumgrades / $sumweights);
3165 }
3166 // check if the new final grade differs from the one stored in the database
3167 if (grade_floats_different($finalgrade, $current)) {
3168 // we need to save new calculation into the database
7a789aa8 3169 $record = new stdclass();
10bc4bce
DM
3170 $record->id = $submissionid;
3171 $record->grade = $finalgrade;
3172 $record->timegraded = time();
3173 $DB->update_record('workshop_submissions', $record);
e9a90e69
DM
3174 }
3175 }
3176
39411930
DM
3177 /**
3178 * Given an array of all assessments done by a single reviewer, calculates the final grading grade
3179 *
3180 * This calculates the simple mean of the passed grading grades. If, however, the grading grade
3181 * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored.
3182 *
7a789aa8 3183 * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade)
a1373126 3184 * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time
1fed6ce3 3185 * @return void
39411930 3186 */
a1373126 3187 protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
39411930
DM
3188 global $DB;
3189
3190 $reviewerid = null; // the id of the reviewer being processed
3191 $current = null; // the gradinggrade currently saved in database
3192 $finalgrade = null; // the new grade to be calculated
3193 $agid = null; // aggregation id
3194 $sumgrades = 0;
3195 $count = 0;
3196
a1373126
DM
3197 if (is_null($timegraded)) {
3198 $timegraded = time();
3199 }
3200
39411930
DM
3201 foreach ($assessments as $assessment) {
3202 if (is_null($reviewerid)) {
3203 // the id is the same in all records, fetch it during the first loop cycle
3204 $reviewerid = $assessment->reviewerid;
3205 }
3206 if (is_null($agid)) {
3207 // the id is the same in all records, fetch it during the first loop cycle
3208 $agid = $assessment->aggregationid;
3209 }
3210 if (is_null($current)) {
3211 // the currently saved grade is the same in all records, fetch it during the first loop cycle
3212 $current = $assessment->aggregatedgrade;
3213 }
3214 if (!is_null($assessment->gradinggradeover)) {
5924db72 3215 // the grading grade for this assessment is overridden by a teacher
39411930
DM
3216 $sumgrades += $assessment->gradinggradeover;
3217 $count++;
3218 } else {
3219 if (!is_null($assessment->gradinggrade)) {
3220 $sumgrades += $assessment->gradinggrade;
3221 $count++;
3222 }
3223 }
3224 }
3225 if ($count > 0) {
3226 $finalgrade = grade_floatval($sumgrades / $count);
3227 }
1f013271
AG
3228
3229 // Event information.
3230 $params = array(
3231 'context' => $this->context,
3232 'courseid' => $this->course->id,
3233 'relateduserid' => $reviewerid
3234 );
3235
39411930
DM
3236 // check if the new final grade differs from the one stored in the database
3237 if (grade_floats_different($finalgrade, $current)) {
1f013271
AG
3238 $params['other'] = array(
3239 'currentgrade' => $current,
3240 'finalgrade' => $finalgrade
3241 );
3242
39411930
DM
3243 // we need to save new calculation into the database
3244 if (is_null($agid)) {
3245 // no aggregation record yet
7a789aa8 3246 $record = new stdclass();
39411930
DM
3247 $record->workshopid = $this->id;
3248 $record->userid = $reviewerid;
3249 $record->gradinggrade = $finalgrade;
a1373126 3250 $record->timegraded = $timegraded;
1f013271
AG
3251 $record->id = $DB->insert_record('workshop_aggregations', $record);
3252 $params['objectid'] = $record->id;
3253 $event = \mod_workshop\event\assessment_evaluated::create($params);
3254 $event->trigger();
39411930 3255 } else {
7a789aa8 3256 $record = new stdclass();
10bc4bce
DM
3257 $record->id = $agid;
3258 $record->gradinggrade = $finalgrade;
a1373126 3259 $record->timegraded = $timegraded;
10bc4bce 3260 $DB->update_record('workshop_aggregations', $record);
1f013271
AG
3261 $params['objectid'] = $agid;
3262 $event = \mod_workshop\event\assessment_reevaluated::create($params);
3263 $event->trigger();
39411930
DM
3264 }
3265 }
3266 }
3267
6516b9e9 3268 /**
21f58287 3269 * Returns SQL to fetch all enrolled users with the given capability in the current workshop
aa40adbf 3270 *
9691e2b1 3271 * The returned array consists of string $sql and the $params array. Note that the $sql can be
45ab2d9a 3272 * empty if a grouping is selected and it has no groups.
3273 *
3274 * The list is automatically restricted according to any availability restrictions
3275 * that apply to user lists (e.g. group, grouping restrictions).
9691e2b1 3276 *
21f58287
DM
3277 * @param string $capability the name of the capability
3278 * @param bool $musthavesubmission ff true, return only users who have already submitted
3279 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3280 * @return array of (string)sql, (array)params
6516b9e9 3281 */
21f58287 3282 protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) {
8741ebb0 3283 global $CFG;
9691e2b1
DM
3284 /** @var int static counter used to generate unique parameter holders */
3285 static $inc = 0;
3286 $inc++;
3287
45ab2d9a 3288 // If the caller requests all groups and we are using a selected grouping,
3289 // recursively call this function for each group in the grouping (this is
3290 // needed because get_enrolled_sql only supports a single group).
3291 if (empty($groupid) and $this->cm->groupingid) {
9691e2b1
DM
3292 $groupingid = $this->cm->groupingid;
3293 $groupinggroupids = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
3294 $sql = array();
3295 $params = array();
3296 foreach ($groupinggroupids as $groupinggroupid) {
3297 if ($groupinggroupid > 0) { // just in case in order not to fall into the endless loop
3298 list($gsql, $gparams) = $this->get_users_with_capability_sql($capability, $musthavesubmission, $groupinggroupid);
3299 $sql[] = $gsql;
3300 $params = array_merge($params, $gparams);
3301 }
3302 }
3303 $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql);
3304 return array($sql, $params);
3305 }
aa40adbf 3306
21f58287
DM
3307 list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true);
3308
3309 $userfields = user_picture::fields('u');
3310
3311 $sql = "SELECT $userfields
3312 FROM {user} u
9691e2b1 3313 JOIN ($esql) je ON (je.id = u.id AND u.deleted = 0) ";
21f58287
DM
3314
3315 if ($musthavesubmission) {
9691e2b1
DM
3316 $sql .= " JOIN {workshop_submissions} ws ON (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid{$inc}) ";
3317 $params['workshopid'.$inc] = $this->id;
aa40adbf
DM
3318 }