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