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