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