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