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