Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Library of internal classes and functions for module workshop
19
 *
20
 * All the workshop specific functions, needed to implement the module
21
 * logic, should go to here. Instead of having bunch of function named
22
 * workshop_something() taking the workshop instance as the first
23
 * parameter, we use a class workshop that provides all methods.
24
 *
25
 * @package    mod_workshop
26
 * @copyright  2009 David Mudrak <david.mudrak@gmail.com>
27
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28
 */
29
 
30
defined('MOODLE_INTERNAL') || die();
31
 
32
require_once(__DIR__.'/lib.php');     // we extend this library here
33
require_once($CFG->libdir . '/gradelib.php');   // we use some rounding and comparing routines here
34
require_once($CFG->libdir . '/filelib.php');
35
 
36
/**
37
 * Full-featured workshop API
38
 *
39
 * This wraps the workshop database record with a set of methods that are called
40
 * from the module itself. The class should be initialized right after you get
41
 * $workshop, $cm and $course records at the begining of the script.
42
 */
43
class workshop {
44
 
45
    /** error status of the {@link self::add_allocation()} */
46
    const ALLOCATION_EXISTS             = -9999;
47
 
48
    /** the internal code of the workshop phases as are stored in the database */
49
    const PHASE_SETUP                   = 10;
50
    const PHASE_SUBMISSION              = 20;
51
    const PHASE_ASSESSMENT              = 30;
52
    const PHASE_EVALUATION              = 40;
53
    const PHASE_CLOSED                  = 50;
54
 
55
    /** the internal code of the examples modes as are stored in the database */
56
    const EXAMPLES_VOLUNTARY            = 0;
57
    const EXAMPLES_BEFORE_SUBMISSION    = 1;
58
    const EXAMPLES_BEFORE_ASSESSMENT    = 2;
59
 
60
    /** @var stdclass workshop record from database */
61
    public $dbrecord;
62
 
63
    /** @var cm_info course module record */
64
    public $cm;
65
 
66
    /** @var stdclass course record */
67
    public $course;
68
 
69
    /** @var stdclass context object */
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 (deprecated, consider always enabled) */
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
 
120
    /** @var string the name of the evaluation plugin to use for grading grades calculation */
121
    public $evaluation;
122
 
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 string list of allowed file types that are allowed to be embedded into submission */
130
    public $submissionfiletypes = null;
131
 
132
    /** @var bool allow submitting the work after the deadline */
133
    public $latesubmissions;
134
 
135
    /** @var int maximum size of the one attached file in bytes */
136
    public $maxbytes;
137
 
138
    /** @var int mode of example submissions support, for example {@link workshop::EXAMPLES_VOLUNTARY} */
139
    public $examplesmode;
140
 
141
    /** @var int if greater than 0 then the submission is not allowed before this timestamp */
142
    public $submissionstart;
143
 
144
    /** @var int if greater than 0 then the submission is not allowed after this timestamp */
145
    public $submissionend;
146
 
147
    /** @var int if greater than 0 then the peer assessment is not allowed before this timestamp */
148
    public $assessmentstart;
149
 
150
    /** @var int if greater than 0 then the peer assessment is not allowed after this timestamp */
151
    public $assessmentend;
152
 
153
    /** @var bool automatically switch to the assessment phase after the submissions deadline */
154
    public $phaseswitchassessment;
155
 
156
    /** @var string conclusion text to be displayed at the end of the activity */
157
    public $conclusion;
158
 
159
    /** @var int format of the conclusion text */
160
    public $conclusionformat;
161
 
162
    /** @var int the mode of the overall feedback */
163
    public $overallfeedbackmode;
164
 
165
    /** @var int maximum number of overall feedback attachments */
166
    public $overallfeedbackfiles;
167
 
168
    /** @var string list of allowed file types that can be attached to the overall feedback */
169
    public $overallfeedbackfiletypes = null;
170
 
171
    /** @var int maximum size of one file attached to the overall feedback */
172
    public $overallfeedbackmaxbytes;
173
 
174
    /** @var int Should the submission form show the text field? */
175
    public $submissiontypetext;
176
 
177
    /** @var int Should the submission form show the file attachment field? */
178
    public $submissiontypefile;
179
 
180
    /**
181
     * @var workshop_strategy grading strategy instance
182
     * Do not use directly, get the instance using {@link workshop::grading_strategy_instance()}
183
     */
184
    protected $strategyinstance = null;
185
 
186
    /**
187
     * @var workshop_evaluation grading evaluation instance
188
     * Do not use directly, get the instance using {@link workshop::grading_evaluation_instance()}
189
     */
190
    protected $evaluationinstance = null;
191
 
192
    /**
193
     * @var array It gets initialised in init_initial_bar, and may have keys 'i_first' and 'i_last' depending on what is selected.
194
     */
195
    protected $initialbarprefs = [];
196
 
197
    /**
198
     * Initializes the workshop API instance using the data from DB
199
     *
200
     * Makes deep copy of all passed records properties.
201
     *
202
     * For unit testing only, $cm and $course may be set to null. This is so that
203
     * you can test without having any real database objects if you like. Not all
204
     * functions will work in this situation.
205
     *
206
     * @param stdClass $dbrecord Workshop instance data from {workshop} table
207
     * @param stdClass|cm_info $cm Course module record
208
     * @param stdClass $course Course record from {course} table
209
     * @param stdClass $context The context of the workshop instance
210
     */
1441 ariadna 211
    public function __construct(stdclass $dbrecord, $cm, $course, ?stdclass $context=null) {
1 efrain 212
        $this->dbrecord = $dbrecord;
213
        foreach ($this->dbrecord as $field => $value) {
214
            if (property_exists('workshop', $field)) {
215
                $this->{$field} = $value;
216
            }
217
        }
218
 
219
        $this->strategy = clean_param($this->strategy, PARAM_PLUGIN);
220
        $this->evaluation = clean_param($this->evaluation, PARAM_PLUGIN);
221
 
222
        if (is_null($cm) || is_null($course)) {
223
            throw new coding_exception('Must specify $cm and $course');
224
        }
225
        $this->course = $course;
226
        if ($cm instanceof cm_info) {
227
            $this->cm = $cm;
228
        } else {
229
            $modinfo = get_fast_modinfo($course);
230
            $this->cm = $modinfo->get_cm($cm->id);
231
        }
232
        if (is_null($context)) {
233
            $this->context = context_module::instance($this->cm->id);
234
        } else {
235
            $this->context = $context;
236
        }
237
    }
238
 
239
    ////////////////////////////////////////////////////////////////////////////////
240
    // Static methods                                                             //
241
    ////////////////////////////////////////////////////////////////////////////////
242
 
243
    /**
244
     * Return list of available allocation methods
245
     *
246
     * @return array Array ['string' => 'string'] of localized allocation method names
247
     */
248
    public static function installed_allocators() {
249
        $installed = core_component::get_plugin_list('workshopallocation');
250
        $forms = array();
251
        foreach ($installed as $allocation => $allocationpath) {
252
            if (file_exists($allocationpath . '/lib.php')) {
253
                $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation);
254
            }
255
        }
256
        // usability - make sure that manual allocation appears the first
257
        if (isset($forms['manual'])) {
258
            $m = array('manual' => $forms['manual']);
259
            unset($forms['manual']);
260
            $forms = array_merge($m, $forms);
261
        }
262
        return $forms;
263
    }
264
 
265
    /**
266
     * Returns an array of options for the editors that are used for submitting and assessing instructions
267
     *
268
     * @param stdClass $context
269
     * @uses EDITOR_UNLIMITED_FILES hard-coded value for the 'maxfiles' option
270
     * @return array
271
     */
272
    public static function instruction_editors_options(stdclass $context) {
273
        return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => -1,
274
                     'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0);
275
    }
276
 
277
    /**
278
     * Given the percent and the total, returns the number
279
     *
280
     * @param float $percent from 0 to 100
281
     * @param float $total   the 100% value
282
     * @return float
283
     */
284
    public static function percent_to_value($percent, $total) {
285
        if ($percent < 0 or $percent > 100) {
286
            throw new coding_exception('The percent can not be less than 0 or higher than 100');
287
        }
288
 
289
        return $total * $percent / 100;
290
    }
291
 
292
    /**
293
     * Returns an array of numeric values that can be used as maximum grades
294
     *
295
     * @return array Array of integers
296
     */
297
    public static function available_maxgrades_list() {
298
        $grades = array();
299
        for ($i=100; $i>=0; $i--) {
300
            $grades[$i] = $i;
301
        }
302
        return $grades;
303
    }
304
 
305
    /**
306
     * Returns the localized list of supported examples modes
307
     *
308
     * @return array
309
     */
310
    public static function available_example_modes_list() {
311
        $options = array();
312
        $options[self::EXAMPLES_VOLUNTARY]         = get_string('examplesvoluntary', 'workshop');
313
        $options[self::EXAMPLES_BEFORE_SUBMISSION] = get_string('examplesbeforesubmission', 'workshop');
314
        $options[self::EXAMPLES_BEFORE_ASSESSMENT] = get_string('examplesbeforeassessment', 'workshop');
315
        return $options;
316
    }
317
 
318
    /**
319
     * Returns the list of available grading strategy methods
320
     *
321
     * @return array ['string' => 'string']
322
     */
323
    public static function available_strategies_list() {
324
        $installed = core_component::get_plugin_list('workshopform');
325
        $forms = array();
326
        foreach ($installed as $strategy => $strategypath) {
327
            if (file_exists($strategypath . '/lib.php')) {
328
                $forms[$strategy] = get_string('pluginname', 'workshopform_' . $strategy);
329
            }
330
        }
331
        return $forms;
332
    }
333
 
334
    /**
335
     * Returns the list of available grading evaluation methods
336
     *
337
     * @return array of (string)name => (string)localized title
338
     */
339
    public static function available_evaluators_list() {
340
        $evals = array();
341
        foreach (core_component::get_plugin_list_with_file('workshopeval', 'lib.php', false) as $eval => $evalpath) {
342
            $evals[$eval] = get_string('pluginname', 'workshopeval_' . $eval);
343
        }
344
        return $evals;
345
    }
346
 
347
    /**
348
     * Return an array of possible values of assessment dimension weight
349
     *
350
     * @return array of integers 0, 1, 2, ..., 16
351
     */
352
    public static function available_dimension_weights_list() {
353
        $weights = array();
354
        for ($i=16; $i>=0; $i--) {
355
            $weights[$i] = $i;
356
        }
357
        return $weights;
358
    }
359
 
360
    /**
361
     * Return an array of possible values of assessment weight
362
     *
363
     * Note there is no real reason why the maximum value here is 16. It used to be 10 in
364
     * workshop 1.x and I just decided to use the same number as in the maximum weight of
365
     * a single assessment dimension.
366
     * The value looks reasonable, though. Teachers who would want to assign themselves
367
     * higher weight probably do not want peer assessment really...
368
     *
369
     * @return array of integers 0, 1, 2, ..., 16
370
     */
371
    public static function available_assessment_weights_list() {
372
        $weights = array();
373
        for ($i=16; $i>=0; $i--) {
374
            $weights[$i] = $i;
375
        }
376
        return $weights;
377
    }
378
 
379
    /**
380
     * Helper function returning the greatest common divisor
381
     *
382
     * @param int $a
383
     * @param int $b
384
     * @return int
385
     */
386
    public static function gcd($a, $b) {
387
        return ($b == 0) ? ($a):(self::gcd($b, $a % $b));
388
    }
389
 
390
    /**
391
     * Helper function returning the least common multiple
392
     *
393
     * @param int $a
394
     * @param int $b
395
     * @return int
396
     */
397
    public static function lcm($a, $b) {
398
        return ($a / self::gcd($a,$b)) * $b;
399
    }
400
 
401
    /**
402
     * Returns an object suitable for strings containing dates/times
403
     *
404
     * The returned object contains properties date, datefullshort, datetime, ... containing the given
405
     * timestamp formatted using strftimedate, strftimedatefullshort, strftimedatetime, ... from the
406
     * current lang's langconfig.php
407
     * This allows translators and administrators customize the date/time format.
408
     *
409
     * @param int $timestamp the timestamp in UTC
410
     * @return stdclass
411
     */
412
    public static function timestamp_formats($timestamp) {
413
        $formats = array('date', 'datefullshort', 'dateshort', 'datetime',
414
                'datetimeshort', 'daydate', 'daydatetime', 'dayshort', 'daytime',
415
                'monthyear', 'recent', 'recentfull', 'time');
416
        $a = new stdclass();
417
        foreach ($formats as $format) {
418
            $a->{$format} = userdate($timestamp, get_string('strftime'.$format, 'langconfig'));
419
        }
420
        $day = userdate($timestamp, '%Y%m%d', 99, false);
421
        $today = userdate(time(), '%Y%m%d', 99, false);
422
        $tomorrow = userdate(time() + DAYSECS, '%Y%m%d', 99, false);
423
        $yesterday = userdate(time() - DAYSECS, '%Y%m%d', 99, false);
424
        $distance = (int)round(abs(time() - $timestamp) / DAYSECS);
425
        if ($day == $today) {
426
            $a->distanceday = get_string('daystoday', 'workshop');
427
        } elseif ($day == $yesterday) {
428
            $a->distanceday = get_string('daysyesterday', 'workshop');
429
        } elseif ($day < $today) {
430
            $a->distanceday = get_string('daysago', 'workshop', $distance);
431
        } elseif ($day == $tomorrow) {
432
            $a->distanceday = get_string('daystomorrow', 'workshop');
433
        } elseif ($day > $today) {
434
            $a->distanceday = get_string('daysleft', 'workshop', $distance);
435
        }
436
        return $a;
437
    }
438
 
439
    /**
440
     * Converts the argument into an array (list) of file extensions.
441
     *
442
     * The list can be separated by whitespace, end of lines, commas colons and semicolons.
443
     * Empty values are not returned. Values are converted to lowercase.
444
     * Duplicates are removed. Glob evaluation is not supported.
445
     *
446
     * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
447
     * @param string|array $extensions list of file extensions
448
     * @return array of strings
449
     */
450
    public static function normalize_file_extensions($extensions) {
451
 
452
        debugging('The method workshop::normalize_file_extensions() is deprecated.
453
            Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
454
 
455
        if ($extensions === '') {
456
            return array();
457
        }
458
 
459
        if (!is_array($extensions)) {
460
            $extensions = preg_split('/[\s,;:"\']+/', $extensions, -1, PREG_SPLIT_NO_EMPTY);
461
        }
462
 
463
        foreach ($extensions as $i => $extension) {
464
            $extension = str_replace('*.', '', $extension);
465
            $extension = strtolower($extension);
466
            $extension = ltrim($extension, '.');
467
            $extension = trim($extension);
468
            $extensions[$i] = $extension;
469
        }
470
 
471
        foreach ($extensions as $i => $extension) {
472
            if (strpos($extension, '*') !== false or strpos($extension, '?') !== false) {
473
                unset($extensions[$i]);
474
            }
475
        }
476
 
477
        $extensions = array_filter($extensions, 'strlen');
478
        $extensions = array_keys(array_flip($extensions));
479
 
480
        foreach ($extensions as $i => $extension) {
481
            $extensions[$i] = '.'.$extension;
482
        }
483
 
484
        return $extensions;
485
    }
486
 
487
    /**
488
     * Cleans the user provided list of file extensions.
489
     *
490
     * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
491
     * @param string $extensions
492
     * @return string
493
     */
494
    public static function clean_file_extensions($extensions) {
495
 
496
        debugging('The method workshop::clean_file_extensions() is deprecated.
497
            Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
498
 
499
        $extensions = self::normalize_file_extensions($extensions);
500
 
501
        foreach ($extensions as $i => $extension) {
502
            $extensions[$i] = ltrim($extension, '.');
503
        }
504
 
505
        return implode(', ', $extensions);
506
    }
507
 
508
    /**
509
     * Check given file types and return invalid/unknown ones.
510
     *
511
     * Empty allowlist is interpretted as "any extension is valid".
512
     *
513
     * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
514
     * @param string|array $extensions list of file extensions
515
     * @param string|array $allowlist list of valid extensions
516
     * @return array list of invalid extensions not found in the allowlist
517
     */
518
    public static function invalid_file_extensions($extensions, $allowlist) {
519
 
520
        debugging('The method workshop::invalid_file_extensions() is deprecated.
521
            Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
522
 
523
        $extensions = self::normalize_file_extensions($extensions);
524
        $allowlist = self::normalize_file_extensions($allowlist);
525
 
526
        if (empty($extensions) or empty($allowlist)) {
527
            return array();
528
        }
529
 
530
        // Return those items from $extensions that are not present in $allowlist.
531
        return array_keys(array_diff_key(array_flip($extensions), array_flip($allowlist)));
532
    }
533
 
534
    /**
535
     * Is the file have allowed to be uploaded to the workshop?
536
     *
537
     * Empty allowlist is interpretted as "any file type is allowed" rather
538
     * than "no file can be uploaded".
539
     *
540
     * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
541
     * @param string $filename the file name
542
     * @param string|array $allowlist list of allowed file extensions
543
     * @return false
544
     */
545
    public static function is_allowed_file_type($filename, $allowlist) {
546
 
547
        debugging('The method workshop::is_allowed_file_type() is deprecated.
548
            Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
549
 
550
        $allowlist = self::normalize_file_extensions($allowlist);
551
 
552
        if (empty($allowlist)) {
553
            return true;
554
        }
555
 
556
        $haystack = strrev(trim(strtolower($filename)));
557
 
558
        foreach ($allowlist as $extension) {
559
            if (strpos($haystack, strrev($extension)) === 0) {
560
                // The file name ends with the extension.
561
                return true;
562
            }
563
        }
564
 
565
        return false;
566
    }
567
 
568
    ////////////////////////////////////////////////////////////////////////////////
569
    // Workshop API                                                               //
570
    ////////////////////////////////////////////////////////////////////////////////
571
 
572
    /**
573
     * Fetches all enrolled users with the capability mod/workshop:submit in the current workshop
574
     *
575
     * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
576
     * Only users with the active enrolment are returned.
577
     *
578
     * @param bool $musthavesubmission if true, return only users who have already submitted
579
     * @param int $groupid 0 means ignore groups, any other value limits the result by group id
580
     * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
581
     * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
582
     * @return array array[userid] => stdClass
583
     */
584
    public function get_potential_authors($musthavesubmission=true, $groupid=0, $limitfrom=0, $limitnum=0) {
1441 ariadna 585
        return $this->get_users_with_capability(['mod/workshop:submit'], $musthavesubmission, $groupid, $limitfrom, $limitnum);
1 efrain 586
    }
587
 
588
    /**
589
     * Returns the total number of users that would be fetched by {@link self::get_potential_authors()}
590
     *
591
     * @param bool $musthavesubmission if true, count only users who have already submitted
592
     * @param int $groupid 0 means ignore groups, any other value limits the result by group id
593
     * @return int
594
     */
595
    public function count_potential_authors($musthavesubmission=true, $groupid=0) {
1441 ariadna 596
        return count($this->get_users_with_capability(['mod/workshop:submit'], $musthavesubmission, $groupid));
1 efrain 597
    }
598
 
599
    /**
600
     * Fetches all enrolled users with the capability mod/workshop:peerassess in the current workshop
601
     *
602
     * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
603
     * Only users with the active enrolment are returned.
604
     *
605
     * @param bool $musthavesubmission if true, return only users who have already submitted
606
     * @param int $groupid 0 means ignore groups, any other value limits the result by group id
607
     * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
608
     * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
609
     * @return array array[userid] => stdClass
610
     */
611
    public function get_potential_reviewers($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
1441 ariadna 612
        return $this->get_users_with_capability(['mod/workshop:peerassess'], $musthavesubmission, $groupid, $limitfrom, $limitnum);
1 efrain 613
    }
614
 
615
    /**
616
     * Returns the total number of users that would be fetched by {@link self::get_potential_reviewers()}
617
     *
618
     * @param bool $musthavesubmission if true, count only users who have already submitted
619
     * @param int $groupid 0 means ignore groups, any other value limits the result by group id
620
     * @return int
621
     */
622
    public function count_potential_reviewers($musthavesubmission=false, $groupid=0) {
1441 ariadna 623
        return count($this->get_users_with_capability(['mod/workshop:peerassess'], $musthavesubmission, $groupid));
1 efrain 624
 
625
    }
626
 
627
    /**
628
     * Fetches all enrolled users that are authors or reviewers (or both) in the current workshop
629
     *
630
     * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
631
     * Only users with the active enrolment are returned.
632
     *
633
     * @see self::get_potential_authors()
634
     * @see self::get_potential_reviewers()
635
     * @param bool $musthavesubmission if true, return only users who have already submitted
636
     * @param int $groupid 0 means ignore groups, any other value limits the result by group id
637
     * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
638
     * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
639
     * @return array array[userid] => stdClass
640
     */
641
    public function get_participants($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
642
 
1441 ariadna 643
        // Get any users who have either of these 2 capabilities on the activity.
644
        return $this->get_users_with_capability(['mod/workshop:submit', 'mod/workshop:peerassess'],
645
            $musthavesubmission, $groupid, $limitfrom, $limitnum);
1 efrain 646
 
647
    }
648
 
649
    /**
650
     * Returns the total number of records that would be returned by {@link self::get_participants()}
651
     *
652
     * @param bool $musthavesubmission if true, return only users who have already submitted
653
     * @param int $groupid 0 means ignore groups, any other value limits the result by group id
654
     * @return int
655
     */
656
    public function count_participants($musthavesubmission=false, $groupid=0) {
1441 ariadna 657
        return count($this->get_participants($musthavesubmission, $groupid));
1 efrain 658
    }
659
 
660
    /**
661
     * Checks if the given user is an actively enrolled participant in the workshop
662
     *
663
     * @param int $userid, defaults to the current $USER
664
     * @return boolean
665
     */
666
    public function is_participant($userid=null) {
667
 
1441 ariadna 668
        global $USER;
669
 
1 efrain 670
        if (is_null($userid)) {
671
            $userid = $USER->id;
672
        }
673
 
1441 ariadna 674
        // Get the participants on this activity and see if the user exists in that array.
675
        $participants = $this->get_participants();
676
        return (array_key_exists($userid, $participants));
1 efrain 677
 
678
    }
679
 
680
    /**
681
     * Groups the given users by the group membership
682
     *
683
     * This takes the module grouping settings into account. If a grouping is
684
     * set, returns only groups withing the course module grouping. Always
685
     * returns group [0] with all the given users.
686
     *
687
     * @param array $users array[userid] => stdclass{->id ->lastname ->firstname}
688
     * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname}
689
     */
690
    public function get_grouped($users) {
691
        global $DB;
692
        global $CFG;
693
 
694
        $grouped = array();  // grouped users to be returned
695
        if (empty($users)) {
696
            return $grouped;
697
        }
698
        if ($this->cm->groupingid) {
699
            // Group workshop set to specified grouping - only consider groups
700
            // within this grouping, and leave out users who aren't members of
701
            // this grouping.
702
            $groupingid = $this->cm->groupingid;
703
            // All users that are members of at least one group will be
704
            // added into a virtual group id 0
705
            $grouped[0] = array();
706
        } else {
707
            $groupingid = 0;
708
            // there is no need to be member of a group so $grouped[0] will contain
709
            // all users
710
            $grouped[0] = $users;
711
        }
712
        $gmemberships = groups_get_all_groups($this->cm->course, array_keys($users), $groupingid,
713
                            'gm.id,gm.groupid,gm.userid');
714
        foreach ($gmemberships as $gmembership) {
715
            if (!isset($grouped[$gmembership->groupid])) {
716
                $grouped[$gmembership->groupid] = array();
717
            }
718
            $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid];
719
            $grouped[0][$gmembership->userid] = $users[$gmembership->userid];
720
        }
721
        return $grouped;
722
    }
723
 
724
    /**
725
     * Returns the list of all allocations (i.e. assigned assessments) in the workshop
726
     *
727
     * Assessments of example submissions are ignored
728
     *
729
     * @return array
730
     */
731
    public function get_allocations() {
732
        global $DB;
733
 
734
        $sql = 'SELECT a.id, a.submissionid, a.reviewerid, s.authorid
735
                  FROM {workshop_assessments} a
736
            INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
737
                 WHERE s.example = 0 AND s.workshopid = :workshopid';
738
        $params = array('workshopid' => $this->id);
739
 
740
        return $DB->get_records_sql($sql, $params);
741
    }
742
 
743
    /**
744
     * Returns the total number of records that would be returned by {@link self::get_submissions()}
745
     *
746
     * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
747
     * @param int $groupid If non-zero, return only submissions by authors in the specified group
748
     * @return int number of records
749
     */
750
    public function count_submissions($authorid='all', $groupid=0) {
751
        global $DB;
752
 
753
        $params = array('workshopid' => $this->id);
754
        $sql = "SELECT COUNT(s.id)
755
                  FROM {workshop_submissions} s
756
                  JOIN {user} u ON (s.authorid = u.id)";
757
        if ($groupid) {
758
            $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
759
            $params['groupid'] = $groupid;
760
        }
761
        $sql .= " WHERE s.example = 0 AND s.workshopid = :workshopid";
762
 
763
        if ('all' === $authorid) {
764
            // no additional conditions
765
        } elseif (!empty($authorid)) {
766
            list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
767
            $sql .= " AND authorid $usql";
768
            $params = array_merge($params, $uparams);
769
        } else {
770
            // $authorid is empty
771
            return 0;
772
        }
773
 
774
        return $DB->count_records_sql($sql, $params);
775
    }
776
 
1441 ariadna 777
    /**
778
     * Returns the total number of assessments in the workshop.
779
     *
780
     * @param bool $onlygraded If true, count only graded assessments
781
     * @param int|null $groupid If not null, return only assessments by reviewers in the specified group
782
     * @return int Number of assessments
783
     */
784
    public function count_assessments(bool $onlygraded = false, ?int $groupid = null): int {
785
        global $DB;
1 efrain 786
 
1441 ariadna 787
        $params = ['workshopid' => $this->id];
788
        $sql = "SELECT COUNT(s.id)
789
                  FROM {workshop_assessments} s
790
                  JOIN {workshop_submissions} ws ON (s.submissionid = ws.id)
791
                  JOIN {user} u ON (ws.authorid = u.id)
792
                  JOIN {workshop} w ON (ws.workshopid = w.id)";
793
 
794
        if ($groupid) {
795
            $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
796
            $params['groupid'] = $groupid;
797
        }
798
 
799
        if ($onlygraded) {
800
            $sql .= " WHERE s.grade IS NOT NULL AND w.id = :workshopid";
801
        } else {
802
            $sql .= " WHERE w.id = :workshopid";
803
        }
804
 
805
        return $DB->count_records_sql($sql, $params);
806
    }
807
 
808
 
1 efrain 809
    /**
810
     * Returns submissions from this workshop
811
     *
812
     * Fetches data from {workshop_submissions} and adds some useful information from other
813
     * tables. Does not return textual fields to prevent possible memory lack issues.
814
     *
815
     * @see self::count_submissions()
816
     * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
817
     * @param int $groupid If non-zero, return only submissions by authors in the specified group
818
     * @param int $limitfrom Return a subset of records, starting at this point (optional)
819
     * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
820
     * @return array of records or an empty array
821
     */
822
    public function get_submissions($authorid='all', $groupid=0, $limitfrom=0, $limitnum=0) {
823
        global $DB;
824
 
825
        $userfieldsapi = \core_user\fields::for_userpic();
826
        $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects;
827
        $gradeoverbyfields = $userfieldsapi->get_sql('t', false, 'over', 'gradeoverbyx', false)->selects;
828
        $params            = array('workshopid' => $this->id);
829
        $sql = "SELECT s.id, s.workshopid, s.example, s.authorid, s.timecreated, s.timemodified,
830
                       s.title, s.grade, s.gradeover, s.gradeoverby, s.published,
831
                       $authorfields, $gradeoverbyfields
832
                  FROM {workshop_submissions} s
833
                  JOIN {user} u ON (s.authorid = u.id)";
834
        if ($groupid) {
835
            $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
836
            $params['groupid'] = $groupid;
837
        }
838
        $sql .= " LEFT JOIN {user} t ON (s.gradeoverby = t.id)
839
                 WHERE s.example = 0 AND s.workshopid = :workshopid";
840
 
841
        if ('all' === $authorid) {
842
            // no additional conditions
843
        } elseif (!empty($authorid)) {
844
            list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
845
            $sql .= " AND authorid $usql";
846
            $params = array_merge($params, $uparams);
847
        } else {
848
            // $authorid is empty
849
            return array();
850
        }
851
        list($sort, $sortparams) = users_order_by_sql('u');
852
        $sql .= " ORDER BY $sort";
853
 
854
        return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
855
    }
856
 
857
    /**
858
     * Returns submissions from this workshop that are viewable by the current user (except example submissions).
859
     *
860
     * @param mixed $authorid int|array If set to [array of] integer, return submission[s] of the given user[s] only
861
     * @param int $groupid If non-zero, return only submissions by authors in the specified group. 0 for all groups.
862
     * @param int $limitfrom Return a subset of records, starting at this point (optional)
863
     * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
864
     * @return array of records and the total submissions count
865
     * @since  Moodle 3.4
866
     */
867
    public function get_visible_submissions($authorid = 0, $groupid = 0, $limitfrom = 0, $limitnum = 0) {
868
        global $DB, $USER;
869
 
870
        $submissions = array();
871
        $select = "SELECT s.*";
872
        $selectcount = "SELECT COUNT(s.id)";
873
        $from = " FROM {workshop_submissions} s";
874
        $params = array('workshopid' => $this->id);
875
 
876
        // Check if the passed group (or all groups when groupid is 0) is visible by the current user.
877
        if (!groups_group_visible($groupid, $this->course, $this->cm)) {
878
            return array($submissions, 0);
879
        }
880
 
881
        if ($groupid) {
882
            $from .= " JOIN {groups_members} gm ON (gm.userid = s.authorid AND gm.groupid = :groupid)";
883
            $params['groupid'] = $groupid;
884
        }
885
        $where = " WHERE s.workshopid = :workshopid AND s.example = 0";
886
 
887
        if (!has_capability('mod/workshop:viewallsubmissions', $this->context)) {
888
            // Check published submissions.
889
            $workshopclosed = $this->phase == self::PHASE_CLOSED;
890
            $canviewpublished = has_capability('mod/workshop:viewpublishedsubmissions', $this->context);
891
            if ($workshopclosed && $canviewpublished) {
892
                $published = " OR s.published = 1";
893
            } else {
894
                $published = '';
895
            }
896
 
897
            // Always get submissions I did or I provided feedback to.
898
            $where .= " AND (s.authorid = :authorid OR s.gradeoverby = :graderid $published)";
899
            $params['authorid'] = $USER->id;
900
            $params['graderid'] = $USER->id;
901
        }
902
 
903
        // Now, user filtering.
904
        if (!empty($authorid)) {
905
            list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
906
            $where .= " AND s.authorid $usql";
907
            $params = array_merge($params, $uparams);
908
        }
909
 
910
        $order = " ORDER BY s.timecreated";
911
 
912
        $totalcount = $DB->count_records_sql($selectcount.$from.$where, $params);
913
        if ($totalcount) {
914
            $submissions = $DB->get_records_sql($select.$from.$where.$order, $params, $limitfrom, $limitnum);
915
        }
916
        return array($submissions, $totalcount);
917
    }
918
 
919
 
920
    /**
921
     * Returns a submission record with the author's data
922
     *
923
     * @param int $id submission id
924
     * @return stdclass
925
     */
926
    public function get_submission_by_id($id) {
927
        global $DB;
928
 
929
        // we intentionally check the workshopid here, too, so the workshop can't touch submissions
930
        // from other instances
931
        $userfieldsapi = \core_user\fields::for_userpic();
932
        $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects;
933
        $gradeoverbyfields = $userfieldsapi->get_sql('g', false, 'gradeoverby', 'gradeoverbyx', false)->selects;
934
        $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
935
                  FROM {workshop_submissions} s
936
            INNER JOIN {user} u ON (s.authorid = u.id)
937
             LEFT JOIN {user} g ON (s.gradeoverby = g.id)
938
                 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.id = :id";
939
        $params = array('workshopid' => $this->id, 'id' => $id);
940
        return $DB->get_record_sql($sql, $params, MUST_EXIST);
941
    }
942
 
943
    /**
944
     * Returns a submission submitted by the given author
945
     *
946
     * @param int $id author id
947
     * @return stdclass|false
948
     */
949
    public function get_submission_by_author($authorid) {
950
        global $DB;
951
 
952
        if (empty($authorid)) {
953
            return false;
954
        }
955
        $userfieldsapi = \core_user\fields::for_userpic();
956
        $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects;
957
        $gradeoverbyfields = $userfieldsapi->get_sql('g', false, 'gradeoverby', 'gradeoverbyx', false)->selects;
958
        $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
959
                  FROM {workshop_submissions} s
960
            INNER JOIN {user} u ON (s.authorid = u.id)
961
             LEFT JOIN {user} g ON (s.gradeoverby = g.id)
962
                 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.authorid = :authorid";
963
        $params = array('workshopid' => $this->id, 'authorid' => $authorid);
964
        return $DB->get_record_sql($sql, $params);
965
    }
966
 
967
    /**
968
     * Returns published submissions with their authors data
969
     *
970
     * @return array of stdclass
971
     */
972
    public function get_published_submissions($orderby='finalgrade DESC') {
973
        global $DB;
974
 
975
        $userfieldsapi = \core_user\fields::for_userpic();
976
        $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects;
977
        $sql = "SELECT s.id, s.authorid, s.timecreated, s.timemodified,
978
                       s.title, s.grade, s.gradeover, COALESCE(s.gradeover,s.grade) AS finalgrade,
979
                       $authorfields
980
                  FROM {workshop_submissions} s
981
            INNER JOIN {user} u ON (s.authorid = u.id)
982
                 WHERE s.example = 0 AND s.workshopid = :workshopid AND s.published = 1
983
              ORDER BY $orderby";
984
        $params = array('workshopid' => $this->id);
985
        return $DB->get_records_sql($sql, $params);
986
    }
987
 
988
    /**
989
     * Returns full record of the given example submission
990
     *
991
     * @param int $id example submission od
992
     * @return object
993
     */
994
    public function get_example_by_id($id) {
995
        global $DB;
996
        return $DB->get_record('workshop_submissions',
997
                array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST);
998
    }
999
 
1000
    /**
1001
     * Returns the list of example submissions in this workshop with reference assessments attached
1002
     *
1003
     * @return array of objects or an empty array
1004
     * @see workshop::prepare_example_summary()
1005
     */
1006
    public function get_examples_for_manager() {
1007
        global $DB;
1008
 
1009
        $sql = 'SELECT s.id, s.title,
1010
                       a.id AS assessmentid, a.grade, a.gradinggrade
1011
                  FROM {workshop_submissions} s
1012
             LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.weight = 1)
1013
                 WHERE s.example = 1 AND s.workshopid = :workshopid
1014
              ORDER BY s.title';
1015
        return $DB->get_records_sql($sql, array('workshopid' => $this->id));
1016
    }
1017
 
1018
    /**
1019
     * Returns the list of all example submissions in this workshop with the information of assessments done by the given user
1020
     *
1021
     * @param int $reviewerid user id
1022
     * @return array of objects, indexed by example submission id
1023
     * @see workshop::prepare_example_summary()
1024
     */
1025
    public function get_examples_for_reviewer($reviewerid) {
1026
        global $DB;
1027
 
1028
        if (empty($reviewerid)) {
1029
            return false;
1030
        }
1031
        $sql = 'SELECT s.id, s.title,
1032
                       a.id AS assessmentid, a.grade, a.gradinggrade
1033
                  FROM {workshop_submissions} s
1034
             LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.reviewerid = :reviewerid AND a.weight = 0)
1035
                 WHERE s.example = 1 AND s.workshopid = :workshopid
1036
              ORDER BY s.title';
1037
        return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid));
1038
    }
1039
 
1040
    /**
1041
     * Prepares renderable submission component
1042
     *
1043
     * @param stdClass $record required by {@see workshop_submission}
1044
     * @param bool $showauthor show the author-related information
1045
     * @return workshop_submission
1046
     */
1047
    public function prepare_submission(stdClass $record, $showauthor = false) {
1048
 
1049
        $submission         = new workshop_submission($this, $record, $showauthor);
1050
        $submission->url    = $this->submission_url($record->id);
1051
 
1052
        return $submission;
1053
    }
1054
 
1055
    /**
1056
     * Prepares renderable submission summary component
1057
     *
1058
     * @param stdClass $record required by {@see workshop_submission_summary}
1059
     * @param bool $showauthor show the author-related information
1060
     * @return workshop_submission_summary
1061
     */
1062
    public function prepare_submission_summary(stdClass $record, $showauthor = false) {
1063
 
1064
        $summary        = new workshop_submission_summary($this, $record, $showauthor);
1065
        $summary->url   = $this->submission_url($record->id);
1066
 
1067
        return $summary;
1068
    }
1069
 
1070
    /**
1071
     * Prepares renderable example submission component
1072
     *
1073
     * @param stdClass $record required by {@see workshop_example_submission}
1074
     * @return workshop_example_submission
1075
     */
1076
    public function prepare_example_submission(stdClass $record) {
1077
 
1078
        $example = new workshop_example_submission($this, $record);
1079
 
1080
        return $example;
1081
    }
1082
 
1083
    /**
1084
     * Prepares renderable example submission summary component
1085
     *
1086
     * If the example is editable, the caller must set the 'editable' flag explicitly.
1087
     *
1088
     * @param stdClass $example as returned by {@link workshop::get_examples_for_manager()} or {@link workshop::get_examples_for_reviewer()}
1089
     * @return workshop_example_submission_summary to be rendered
1090
     */
1091
    public function prepare_example_summary(stdClass $example) {
1092
 
1093
        $summary = new workshop_example_submission_summary($this, $example);
1094
 
1095
        if (is_null($example->grade)) {
1096
            $summary->status = 'notgraded';
1097
            $summary->assesslabel = get_string('assess', 'workshop');
1098
        } else {
1099
            $summary->status = 'graded';
1100
            $summary->assesslabel = get_string('reassess', 'workshop');
1101
        }
1102
 
1103
        $summary->gradeinfo           = new stdclass();
1104
        $summary->gradeinfo->received = $this->real_grade($example->grade);
1105
        $summary->gradeinfo->max      = $this->real_grade(100);
1106
 
1107
        $summary->url       = new moodle_url($this->exsubmission_url($example->id));
1108
        $summary->editurl   = new moodle_url($this->exsubmission_url($example->id), array('edit' => 'on'));
1109
        $summary->assessurl = new moodle_url($this->exsubmission_url($example->id), array('assess' => 'on', 'sesskey' => sesskey()));
1110
 
1111
        return $summary;
1112
    }
1113
 
1114
    /**
1115
     * Prepares renderable assessment component
1116
     *
1117
     * The $options array supports the following keys:
1118
     * showauthor - should the author user info be available for the renderer
1119
     * showreviewer - should the reviewer user info be available for the renderer
1120
     * showform - show the assessment form if it is available
1121
     * showweight - should the assessment weight be available for the renderer
1122
     *
1123
     * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1124
     * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1125
     * @param array $options
1126
     * @return workshop_assessment
1127
     */
1128
    public function prepare_assessment(stdClass $record, $form, array $options = array()) {
1129
 
1130
        $assessment             = new workshop_assessment($this, $record, $options);
1131
        $assessment->url        = $this->assess_url($record->id);
1132
        $assessment->maxgrade   = $this->real_grade(100);
1133
 
1134
        if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1135
            debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1136
        }
1137
 
1138
        if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1139
            $assessment->form = $form;
1140
        }
1141
 
1142
        if (empty($options['showweight'])) {
1143
            $assessment->weight = null;
1144
        }
1145
 
1146
        if (!is_null($record->grade)) {
1147
            $assessment->realgrade = $this->real_grade($record->grade);
1148
        }
1149
 
1150
        return $assessment;
1151
    }
1152
 
1153
    /**
1154
     * Prepares renderable example submission's assessment component
1155
     *
1156
     * The $options array supports the following keys:
1157
     * showauthor - should the author user info be available for the renderer
1158
     * showreviewer - should the reviewer user info be available for the renderer
1159
     * showform - show the assessment form if it is available
1160
     *
1161
     * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1162
     * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1163
     * @param array $options
1164
     * @return workshop_example_assessment
1165
     */
1166
    public function prepare_example_assessment(stdClass $record, $form = null, array $options = array()) {
1167
 
1168
        $assessment             = new workshop_example_assessment($this, $record, $options);
1169
        $assessment->url        = $this->exassess_url($record->id);
1170
        $assessment->maxgrade   = $this->real_grade(100);
1171
 
1172
        if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1173
            debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1174
        }
1175
 
1176
        if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1177
            $assessment->form = $form;
1178
        }
1179
 
1180
        if (!is_null($record->grade)) {
1181
            $assessment->realgrade = $this->real_grade($record->grade);
1182
        }
1183
 
1184
        $assessment->weight = null;
1185
 
1186
        return $assessment;
1187
    }
1188
 
1189
    /**
1190
     * Prepares renderable example submission's reference assessment component
1191
     *
1192
     * The $options array supports the following keys:
1193
     * showauthor - should the author user info be available for the renderer
1194
     * showreviewer - should the reviewer user info be available for the renderer
1195
     * showform - show the assessment form if it is available
1196
     *
1197
     * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
1198
     * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
1199
     * @param array $options
1200
     * @return workshop_example_reference_assessment
1201
     */
1202
    public function prepare_example_reference_assessment(stdClass $record, $form = null, array $options = array()) {
1203
 
1204
        $assessment             = new workshop_example_reference_assessment($this, $record, $options);
1205
        $assessment->maxgrade   = $this->real_grade(100);
1206
 
1207
        if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
1208
            debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
1209
        }
1210
 
1211
        if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
1212
            $assessment->form = $form;
1213
        }
1214
 
1215
        if (!is_null($record->grade)) {
1216
            $assessment->realgrade = $this->real_grade($record->grade);
1217
        }
1218
 
1219
        $assessment->weight = null;
1220
 
1221
        return $assessment;
1222
    }
1223
 
1224
    /**
1225
     * Removes the submission and all relevant data
1226
     *
1227
     * @param stdClass $submission record to delete
1228
     * @return void
1229
     */
1230
    public function delete_submission(stdclass $submission) {
1231
        global $DB;
1232
 
1233
        $assessments = $DB->get_records('workshop_assessments', array('submissionid' => $submission->id), '', 'id');
1234
        $this->delete_assessment(array_keys($assessments));
1235
 
1236
        $fs = get_file_storage();
1237
        $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_content', $submission->id);
1238
        $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
1239
 
1240
        $DB->delete_records('workshop_submissions', array('id' => $submission->id));
1241
 
1242
        // Event information.
1243
        $params = array(
1244
            'context' => $this->context,
1245
            'courseid' => $this->course->id,
1246
            'relateduserid' => $submission->authorid,
1247
            'other' => array(
1248
                'submissiontitle' => $submission->title
1249
            )
1250
        );
1251
        $params['objectid'] = $submission->id;
1252
        $event = \mod_workshop\event\submission_deleted::create($params);
1253
        $event->add_record_snapshot('workshop', $this->dbrecord);
1254
        $event->trigger();
1255
    }
1256
 
1257
    /**
1258
     * Returns the list of all assessments in the workshop with some data added
1259
     *
1260
     * Fetches data from {workshop_assessments} and adds some useful information from other
1261
     * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory
1262
     * lack issues.
1263
     *
1264
     * @return array [assessmentid] => assessment stdclass
1265
     */
1266
    public function get_all_assessments() {
1267
        global $DB;
1268
 
1269
        $userfieldsapi = \core_user\fields::for_userpic();
1270
        $reviewerfields = $userfieldsapi->get_sql('reviewer', false, '', 'revieweridx', false)->selects;
1271
        $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects;
1272
        $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
1273
        list($sort, $params) = users_order_by_sql('reviewer');
1274
        $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified,
1275
                       a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby,
1276
                       $reviewerfields, $authorfields, $overbyfields,
1277
                       s.title
1278
                  FROM {workshop_assessments} a
1279
            INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1280
            INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1281
            INNER JOIN {user} author ON (s.authorid = author.id)
1282
             LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1283
                 WHERE s.workshopid = :workshopid AND s.example = 0
1284
              ORDER BY $sort";
1285
        $params['workshopid'] = $this->id;
1286
 
1287
        return $DB->get_records_sql($sql, $params);
1288
    }
1289
 
1290
    /**
1291
     * Get the complete information about the given assessment
1292
     *
1293
     * @param int $id Assessment ID
1294
     * @return stdclass
1295
     */
1296
    public function get_assessment_by_id($id) {
1297
        global $DB;
1298
 
1299
        $userfieldsapi = \core_user\fields::for_userpic();
1300
        $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects;
1301
        $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects;
1302
        $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
1303
        $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1304
                  FROM {workshop_assessments} a
1305
            INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1306
            INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1307
            INNER JOIN {user} author ON (s.authorid = author.id)
1308
             LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1309
                 WHERE a.id = :id AND s.workshopid = :workshopid";
1310
        $params = array('id' => $id, 'workshopid' => $this->id);
1311
 
1312
        return $DB->get_record_sql($sql, $params, MUST_EXIST);
1313
    }
1314
 
1315
    /**
1316
     * Get the complete information about the user's assessment of the given submission
1317
     *
1318
     * @param int $sid submission ID
1319
     * @param int $uid user ID of the reviewer
1320
     * @return false|stdclass false if not found, stdclass otherwise
1321
     */
1322
    public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
1323
        global $DB;
1324
 
1325
        $userfieldsapi = \core_user\fields::for_userpic();
1326
        $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects;
1327
        $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects;
1328
        $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
1329
        $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
1330
                  FROM {workshop_assessments} a
1331
            INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1332
            INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
1333
            INNER JOIN {user} author ON (s.authorid = author.id)
1334
             LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1335
                 WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid";
1336
        $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id);
1337
 
1338
        return $DB->get_record_sql($sql, $params, IGNORE_MISSING);
1339
    }
1340
 
1341
    /**
1342
     * Get the complete information about all assessments of the given submission
1343
     *
1344
     * @param int $submissionid
1345
     * @return array
1346
     */
1347
    public function get_assessments_of_submission($submissionid) {
1348
        global $DB;
1349
 
1350
        $userfieldsapi = \core_user\fields::for_userpic();
1351
        $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects;
1352
        $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
1353
        list($sort, $params) = users_order_by_sql('reviewer');
1354
        $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields
1355
                  FROM {workshop_assessments} a
1356
            INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1357
            INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1358
             LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1359
                 WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid
1360
              ORDER BY $sort";
1361
        $params['submissionid'] = $submissionid;
1362
        $params['workshopid']   = $this->id;
1363
 
1364
        return $DB->get_records_sql($sql, $params);
1365
    }
1366
 
1367
    /**
1368
     * Get the complete information about all assessments allocated to the given reviewer
1369
     *
1370
     * @param int $reviewerid
1371
     * @return array
1372
     */
1373
    public function get_assessments_by_reviewer($reviewerid) {
1374
        global $DB;
1375
 
1376
        $userfieldsapi = \core_user\fields::for_userpic();
1377
        $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects;
1378
        $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects;
1379
        $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
1380
        $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields,
1381
                       s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated,
1382
                       s.timemodified AS submissionmodified
1383
                  FROM {workshop_assessments} a
1384
            INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
1385
            INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
1386
            INNER JOIN {user} author ON (s.authorid = author.id)
1387
             LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
1388
                 WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid";
1389
        $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id);
1390
 
1391
        return $DB->get_records_sql($sql, $params);
1392
    }
1393
 
1394
    /**
1395
     * Get allocated assessments not graded yet by the given reviewer
1396
     *
1397
     * @see self::get_assessments_by_reviewer()
1398
     * @param int $reviewerid the reviewer id
1399
     * @param null|int|array $exclude optional assessment id (or list of them) to be excluded
1400
     * @return array
1401
     */
1402
    public function get_pending_assessments_by_reviewer($reviewerid, $exclude = null) {
1403
 
1404
        $assessments = $this->get_assessments_by_reviewer($reviewerid);
1405
 
1406
        foreach ($assessments as $id => $assessment) {
1407
            if (!is_null($assessment->grade)) {
1408
                unset($assessments[$id]);
1409
                continue;
1410
            }
1411
            if (!empty($exclude)) {
1412
                if (is_array($exclude) and in_array($id, $exclude)) {
1413
                    unset($assessments[$id]);
1414
                    continue;
1415
                } else if ($id == $exclude) {
1416
                    unset($assessments[$id]);
1417
                    continue;
1418
                }
1419
            }
1420
        }
1421
 
1422
        return $assessments;
1423
    }
1424
 
1425
    /**
1426
     * Allocate a submission to a user for review
1427
     *
1428
     * @param stdClass $submission Submission object with at least id property
1429
     * @param int $reviewerid User ID
1430
     * @param int $weight of the new assessment, from 0 to 16
1431
     * @param bool $bulk repeated inserts into DB expected
1432
     * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists
1433
     */
1434
    public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
1435
        global $DB;
1436
 
1437
        if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
1438
            return self::ALLOCATION_EXISTS;
1439
        }
1440
 
1441
        $weight = (int)$weight;
1442
        if ($weight < 0) {
1443
            $weight = 0;
1444
        }
1445
        if ($weight > 16) {
1446
            $weight = 16;
1447
        }
1448
 
1449
        $now = time();
1450
        $assessment = new stdclass();
1451
        $assessment->submissionid           = $submission->id;
1452
        $assessment->reviewerid             = $reviewerid;
1453
        $assessment->timecreated            = $now;         // do not set timemodified here
1454
        $assessment->weight                 = $weight;
1455
        $assessment->feedbackauthorformat   = editors_get_preferred_format();
1456
        $assessment->feedbackreviewerformat = editors_get_preferred_format();
1457
 
1458
        return $DB->insert_record('workshop_assessments', $assessment, true, $bulk);
1459
    }
1460
 
1461
    /**
1462
     * Delete assessment record or records.
1463
     *
1464
     * Removes associated records from the workshop_grades table, too.
1465
     *
1466
     * @param int|array $id assessment id or array of assessments ids
1467
     * @todo Give grading strategy plugins a chance to clean up their data, too.
1468
     * @return bool true
1469
     */
1470
    public function delete_assessment($id) {
1471
        global $DB;
1472
 
1473
        if (empty($id)) {
1474
            return true;
1475
        }
1476
 
1477
        $fs = get_file_storage();
1478
 
1479
        if (is_array($id)) {
1480
            $DB->delete_records_list('workshop_grades', 'assessmentid', $id);
1481
            foreach ($id as $itemid) {
1482
                $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $itemid);
1483
                $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $itemid);
1484
            }
1485
            $DB->delete_records_list('workshop_assessments', 'id', $id);
1486
 
1487
        } else {
1488
            $DB->delete_records('workshop_grades', array('assessmentid' => $id));
1489
            $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $id);
1490
            $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $id);
1491
            $DB->delete_records('workshop_assessments', array('id' => $id));
1492
        }
1493
 
1494
        return true;
1495
    }
1496
 
1497
    /**
1498
     * Returns instance of grading strategy class
1499
     *
1500
     * @return stdclass Instance of a grading strategy
1501
     */
1502
    public function grading_strategy_instance() {
1503
        global $CFG;    // because we require other libs here
1504
 
1505
        if (is_null($this->strategyinstance)) {
1506
            if (empty($this->strategy)) {
1507
                throw new coding_exception('Unknown grading strategy');
1508
            }
1509
            $strategylib = __DIR__ . '/form/' . $this->strategy . '/lib.php';
1510
            if (is_readable($strategylib)) {
1511
                require_once($strategylib);
1512
            } else {
1513
                throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
1514
            }
1515
            $classname = 'workshop_' . $this->strategy . '_strategy';
1516
            $this->strategyinstance = new $classname($this);
1517
            if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) {
1518
                throw new coding_exception($classname . ' does not implement workshop_strategy interface');
1519
            }
1520
        }
1521
        return $this->strategyinstance;
1522
    }
1523
 
1524
    /**
1525
     * Sets the current evaluation method to the given plugin.
1526
     *
1527
     * @param string $method the name of the workshopeval subplugin
1528
     * @return bool true if successfully set
1529
     * @throws coding_exception if attempting to set a non-installed evaluation method
1530
     */
1531
    public function set_grading_evaluation_method($method) {
1532
        global $DB;
1533
 
1534
        $method = clean_param($method, PARAM_PLUGIN);
1535
        $evaluationlib = __DIR__ . '/eval/' . $method . '/lib.php';
1536
 
1537
        if (is_readable($evaluationlib)) {
1538
            $this->evaluationinstance = null;
1539
            $this->evaluation = $method;
1540
            $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id));
1541
            return true;
1542
        }
1543
 
1544
        throw new coding_exception('Attempt to set a non-existing evaluation method.');
1545
    }
1546
 
1547
    /**
1548
     * Returns instance of grading evaluation class
1549
     *
1550
     * @return stdclass Instance of a grading evaluation
1551
     */
1552
    public function grading_evaluation_instance() {
1553
        global $CFG;    // because we require other libs here
1554
 
1555
        if (is_null($this->evaluationinstance)) {
1556
            if (empty($this->evaluation)) {
1557
                $this->evaluation = 'best';
1558
            }
1559
            $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
1560
            if (is_readable($evaluationlib)) {
1561
                require_once($evaluationlib);
1562
            } else {
1563
                // Fall back in case the subplugin is not available.
1564
                $this->evaluation = 'best';
1565
                $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
1566
                if (is_readable($evaluationlib)) {
1567
                    require_once($evaluationlib);
1568
                } else {
1569
                    // Fall back in case the subplugin is not available any more.
1570
                    throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
1571
                }
1572
            }
1573
            $classname = 'workshop_' . $this->evaluation . '_evaluation';
1574
            $this->evaluationinstance = new $classname($this);
1575
            if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) {
1576
                throw new coding_exception($classname . ' does not extend workshop_evaluation class');
1577
            }
1578
        }
1579
        return $this->evaluationinstance;
1580
    }
1581
 
1582
    /**
1583
     * Returns instance of submissions allocator
1584
     *
1585
     * @param string $method The name of the allocation method, must be PARAM_ALPHA
1586
     * @return stdclass Instance of submissions allocator
1587
     */
1588
    public function allocator_instance($method) {
1589
        global $CFG;    // because we require other libs here
1590
 
1591
        $allocationlib = __DIR__ . '/allocation/' . $method . '/lib.php';
1592
        if (is_readable($allocationlib)) {
1593
            require_once($allocationlib);
1594
        } else {
1595
            throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
1596
        }
1597
        $classname = 'workshop_' . $method . '_allocator';
1598
        return new $classname($this);
1599
    }
1600
 
1601
    /**
1602
     * @return moodle_url of this workshop's view page
1603
     */
1604
    public function view_url() {
1605
        global $CFG;
1606
        return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
1607
    }
1608
 
1609
    /**
1610
     * @return moodle_url of the page for editing this workshop's grading form
1611
     */
1612
    public function editform_url() {
1613
        global $CFG;
1614
        return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
1615
    }
1616
 
1617
    /**
1618
     * @return moodle_url of the page for previewing this workshop's grading form
1619
     */
1620
    public function previewform_url() {
1621
        global $CFG;
1622
        return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
1623
    }
1624
 
1625
    /**
1626
     * @param int $assessmentid The ID of assessment record
1627
     * @return moodle_url of the assessment page
1628
     */
1629
    public function assess_url($assessmentid) {
1630
        global $CFG;
1631
        $assessmentid = clean_param($assessmentid, PARAM_INT);
1632
        return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
1633
    }
1634
 
1635
    /**
1636
     * @param int $assessmentid The ID of assessment record
1637
     * @return moodle_url of the example assessment page
1638
     */
1639
    public function exassess_url($assessmentid) {
1640
        global $CFG;
1641
        $assessmentid = clean_param($assessmentid, PARAM_INT);
1642
        return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
1643
    }
1644
 
1645
    /**
1646
     * @return moodle_url of the page to view a submission, defaults to the own one
1647
     */
1648
    public function submission_url($id=null) {
1649
        global $CFG;
1650
        return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
1651
    }
1652
 
1653
    /**
1654
     * @param int $id example submission id
1655
     * @return moodle_url of the page to view an example submission
1656
     */
1657
    public function exsubmission_url($id) {
1658
        global $CFG;
1659
        return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
1660
    }
1661
 
1662
    /**
1663
     * @param int $sid submission id
1664
     * @param array $aid of int assessment ids
1665
     * @return moodle_url of the page to compare assessments of the given submission
1666
     */
1667
    public function compare_url($sid, array $aids) {
1668
        global $CFG;
1669
 
1670
        $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
1671
        $i = 0;
1672
        foreach ($aids as $aid) {
1673
            $url->param("aid{$i}", $aid);
1674
            $i++;
1675
        }
1676
        return $url;
1677
    }
1678
 
1679
    /**
1680
     * @param int $sid submission id
1681
     * @param int $aid assessment id
1682
     * @return moodle_url of the page to compare the reference assessments of the given example submission
1683
     */
1684
    public function excompare_url($sid, $aid) {
1685
        global $CFG;
1686
        return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
1687
    }
1688
 
1689
    /**
1690
     * @return moodle_url of the mod_edit form
1691
     */
1692
    public function updatemod_url() {
1693
        global $CFG;
1694
        return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
1695
    }
1696
 
1697
    /**
1698
     * @param string $method allocation method
1699
     * @return moodle_url to the allocation page
1700
     */
1701
    public function allocation_url($method=null) {
1702
        global $CFG;
1703
        $params = array('cmid' => $this->cm->id);
1704
        if (!empty($method)) {
1705
            $params['method'] = $method;
1706
        }
1707
        return new moodle_url('/mod/workshop/allocation.php', $params);
1708
    }
1709
 
1710
    /**
1711
     * @param int $phasecode The internal phase code
1712
     * @return moodle_url of the script to change the current phase to $phasecode
1713
     */
1714
    public function switchphase_url($phasecode) {
1715
        global $CFG;
1716
        $phasecode = clean_param($phasecode, PARAM_INT);
1717
        return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
1718
    }
1719
 
1720
    /**
1721
     * @return moodle_url to the aggregation page
1722
     */
1723
    public function aggregate_url() {
1724
        global $CFG;
1725
        return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
1726
    }
1727
 
1728
    /**
1729
     * @return moodle_url of this workshop's toolbox page
1730
     */
1731
    public function toolbox_url($tool) {
1732
        global $CFG;
1733
        return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
1734
    }
1735
 
1736
    /**
1737
     * Workshop wrapper around {@see add_to_log()}
1738
     * @deprecated since 2.7 Please use the provided event classes for logging actions.
1739
     *
1740
     * @param string $action to be logged
1741
     * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends
1742
     * @param mixed $info additional info, usually id in a table
1743
     * @param bool $return true to return the arguments for add_to_log.
1744
     * @return void|array array of arguments for add_to_log if $return is true
1745
     */
1441 ariadna 1746
    public function log($action, ?moodle_url $url = null, $info = null, $return = false) {
1 efrain 1747
        debugging('The log method is now deprecated, please use event classes instead', DEBUG_DEVELOPER);
1748
 
1749
        if (is_null($url)) {
1750
            $url = $this->view_url();
1751
        }
1752
 
1753
        if (is_null($info)) {
1754
            $info = $this->id;
1755
        }
1756
 
1757
        $logurl = $this->log_convert_url($url);
1758
        $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
1759
        if ($return) {
1760
            return $args;
1761
        }
1762
        call_user_func_array('add_to_log', $args);
1763
    }
1764
 
1765
    /**
1766
     * Is the given user allowed to create their submission?
1767
     *
1768
     * @param int $userid
1769
     * @return bool
1770
     */
1771
    public function creating_submission_allowed($userid) {
1772
 
1773
        $now = time();
1774
        $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1775
 
1776
        if ($this->latesubmissions) {
1777
            if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) {
1778
                // late submissions are allowed in the submission and assessment phase only
1779
                return false;
1780
            }
1781
            if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1782
                // late submissions are not allowed before the submission start
1783
                return false;
1784
            }
1785
            return true;
1786
 
1787
        } else {
1788
            if ($this->phase != self::PHASE_SUBMISSION) {
1789
                // submissions are allowed during the submission phase only
1790
                return false;
1791
            }
1792
            if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1793
                // if enabled, submitting is not allowed before the date/time defined in the mod_form
1794
                return false;
1795
            }
1796
            if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) {
1797
                // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed
1798
                return false;
1799
            }
1800
            return true;
1801
        }
1802
    }
1803
 
1804
    /**
1805
     * Is the given user allowed to modify their existing submission?
1806
     *
1807
     * @param int $userid
1808
     * @return bool
1809
     */
1810
    public function modifying_submission_allowed($userid) {
1811
 
1812
        $now = time();
1813
        $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1814
 
1815
        if ($this->phase != self::PHASE_SUBMISSION) {
1816
            // submissions can be edited during the submission phase only
1817
            return false;
1818
        }
1819
        if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
1820
            // if enabled, re-submitting is not allowed before the date/time defined in the mod_form
1821
            return false;
1822
        }
1823
        if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) {
1824
            // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed
1825
            return false;
1826
        }
1827
        return true;
1828
    }
1829
 
1830
    /**
1831
     * Is the given reviewer allowed to create/edit their assessments?
1832
     *
1833
     * @param int $userid
1834
     * @return bool
1835
     */
1836
    public function assessing_allowed($userid) {
1837
 
1838
        if ($this->phase != self::PHASE_ASSESSMENT) {
1839
            // assessing is allowed in the assessment phase only, unless the user is a teacher
1840
            // providing additional assessment during the evaluation phase
1841
            if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) {
1842
                return false;
1843
            }
1844
        }
1845
 
1846
        $now = time();
1847
        $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
1848
 
1849
        if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) {
1850
            // if enabled, assessing is not allowed before the date/time defined in the mod_form
1851
            return false;
1852
        }
1853
        if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) {
1854
            // if enabled, assessing is not allowed after the date/time defined in the mod_form
1855
            return false;
1856
        }
1857
        // here we go, assessing is allowed
1858
        return true;
1859
    }
1860
 
1861
    /**
1862
     * Are reviewers allowed to create/edit their assessments of the example submissions?
1863
     *
1864
     * Returns null if example submissions are not enabled in this workshop. Otherwise returns
1865
     * true or false. Note this does not check other conditions like the number of already
1866
     * assessed examples, examples mode etc.
1867
     *
1868
     * @return null|bool
1869
     */
1870
    public function assessing_examples_allowed() {
1871
        if (empty($this->useexamples)) {
1872
            return null;
1873
        }
1874
        if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
1875
            return true;
1876
        }
1877
        if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
1878
            return true;
1879
        }
1880
        if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
1881
            return true;
1882
        }
1883
        return false;
1884
    }
1885
 
1886
    /**
1887
     * Are the peer-reviews available to the authors?
1888
     *
1889
     * @return bool
1890
     */
1891
    public function assessments_available() {
1892
        return $this->phase == self::PHASE_CLOSED;
1893
    }
1894
 
1895
    /**
1896
     * Switch to a new workshop phase
1897
     *
1898
     * Modifies the underlying database record. You should terminate the script shortly after calling this.
1899
     *
1900
     * @param int $newphase new phase code
1901
     * @return bool true if success, false otherwise
1902
     */
1903
    public function switch_phase($newphase) {
1904
        global $DB;
1905
 
1906
        $known = $this->available_phases_list();
1907
        if (!isset($known[$newphase])) {
1908
            return false;
1909
        }
1910
 
1911
        if (self::PHASE_CLOSED == $newphase) {
1912
            // push the grades into the gradebook
1913
            $workshop = new stdclass();
1914
            foreach ($this as $property => $value) {
1915
                $workshop->{$property} = $value;
1916
            }
1917
            $workshop->course     = $this->course->id;
1918
            $workshop->cmidnumber = $this->cm->id;
1919
            $workshop->modname    = 'workshop';
1920
            workshop_update_grades($workshop);
1921
        }
1922
 
1923
        $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
1924
        $this->phase = $newphase;
1925
        $eventdata = array(
1926
            'objectid' => $this->id,
1927
            'context' => $this->context,
1928
            'other' => array(
1929
                'workshopphase' => $this->phase
1930
            )
1931
        );
1932
        $event = \mod_workshop\event\phase_switched::create($eventdata);
1933
        $event->trigger();
1934
        return true;
1935
    }
1936
 
1937
    /**
1938
     * Saves a raw grade for submission as calculated from the assessment form fields
1939
     *
1940
     * @param array $assessmentid assessment record id, must exists
1941
     * @param mixed $grade        raw percentual grade from 0.00000 to 100.00000
1942
     * @return false|float        the saved grade
1943
     */
1944
    public function set_peer_grade($assessmentid, $grade) {
1945
        global $DB;
1946
 
1947
        if (is_null($grade)) {
1948
            return false;
1949
        }
1950
        $data = new stdclass();
1951
        $data->id = $assessmentid;
1952
        $data->grade = $grade;
1953
        $data->timemodified = time();
1954
        $DB->update_record('workshop_assessments', $data);
1955
        return $grade;
1956
    }
1957
 
1958
    /**
1959
     * Prepares data object with all workshop grades to be rendered
1960
     *
1961
     * @param int $userid the user we are preparing the report for
1962
     * @param int $groupid if non-zero, prepare the report for the given group only
1963
     * @param int $page the current page (for the pagination)
1964
     * @param int $perpage participants per page (for the pagination)
1965
     * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
1966
     * @param string $sorthow ASC|DESC
1967
     * @return stdclass data for the renderer
1968
     */
1969
    public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
1970
        global $DB;
1971
 
1972
        $canviewall     = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
1973
        $isparticipant  = $this->is_participant($userid);
1974
 
1975
        if (!$canviewall and !$isparticipant) {
1976
            // who the hell is this?
1977
            return array();
1978
        }
1979
 
1980
        if (!in_array($sortby, array('lastname', 'firstname', 'submissiontitle', 'submissionmodified',
1981
                'submissiongrade', 'gradinggrade'))) {
1982
            $sortby = 'lastname';
1983
        }
1984
 
1985
        if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
1986
            $sorthow = 'ASC';
1987
        }
1988
 
1989
        // get the list of user ids to be displayed
1990
        if ($canviewall) {
1991
            $participants = $this->get_participants(false, $groupid);
1992
        } else {
1993
            // this is an ordinary workshop participant (aka student) - display the report just for him/her
1994
            $participants = array($userid => (object)array('id' => $userid));
1995
        }
1996
 
1997
        // we will need to know the number of all records later for the pagination purposes
1998
        $numofparticipants = count($participants);
1999
 
2000
        if ($numofparticipants > 0) {
2001
            // load all fields which can be used for sorting and paginate the records
2002
            list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
2003
            $params['workshopid1'] = $this->id;
2004
            $params['workshopid2'] = $this->id;
2005
            $sqlsort = array();
2006
            $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
2007
            foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
2008
                $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
2009
            }
2010
            $sqlsort = implode(',', $sqlsort);
2011
            $userfieldsapi = \core_user\fields::for_userpic();
2012
            $picturefields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects;
2013
            $sql = "SELECT $picturefields, s.title AS submissiontitle, s.timemodified AS submissionmodified,
2014
                           s.grade AS submissiongrade, ag.gradinggrade
2015
                      FROM {user} u
2016
                 LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)
2017
                 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)
2018
                     WHERE u.id $participantids
2019
                  ORDER BY $sqlsort";
2020
            $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
2021
        } else {
2022
            $participants = array();
2023
        }
2024
 
2025
        // this will hold the information needed to display user names and pictures
2026
        $userinfo = array();
2027
 
2028
        // get the user details for all participants to display
2029
        $additionalnames = \core_user\fields::get_name_fields();
2030
        foreach ($participants as $participant) {
2031
            if (!isset($userinfo[$participant->userid])) {
2032
                $userinfo[$participant->userid]            = new stdclass();
2033
                $userinfo[$participant->userid]->id        = $participant->userid;
2034
                $userinfo[$participant->userid]->picture   = $participant->picture;
2035
                $userinfo[$participant->userid]->imagealt  = $participant->imagealt;
2036
                $userinfo[$participant->userid]->email     = $participant->email;
2037
                foreach ($additionalnames as $addname) {
2038
                    $userinfo[$participant->userid]->$addname = $participant->$addname;
2039
                }
2040
            }
2041
        }
2042
 
2043
        // load the submissions details
2044
        $submissions = $this->get_submissions(array_keys($participants));
2045
 
2046
        // get the user details for all moderators (teachers) that have overridden a submission grade
2047
        foreach ($submissions as $submission) {
2048
            if (!isset($userinfo[$submission->gradeoverby])) {
2049
                $userinfo[$submission->gradeoverby]            = new stdclass();
2050
                $userinfo[$submission->gradeoverby]->id        = $submission->gradeoverby;
2051
                $userinfo[$submission->gradeoverby]->picture   = $submission->overpicture;
2052
                $userinfo[$submission->gradeoverby]->imagealt  = $submission->overimagealt;
2053
                $userinfo[$submission->gradeoverby]->email     = $submission->overemail;
2054
                foreach ($additionalnames as $addname) {
2055
                    $temp = 'over' . $addname;
2056
                    $userinfo[$submission->gradeoverby]->$addname = $submission->$temp;
2057
                }
2058
            }
2059
        }
2060
 
2061
        // get the user details for all reviewers of the displayed participants
2062
        $reviewers = array();
2063
 
2064
        if ($submissions) {
2065
            list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
2066
            list($sort, $sortparams) = users_order_by_sql('r');
2067
            $userfieldsapi = \core_user\fields::for_userpic();
2068
            $picturefields = $userfieldsapi->get_sql('r', false, '', 'reviewerid', false)->selects;
2069
            $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,
2070
                           $picturefields, s.id AS submissionid, s.authorid
2071
                      FROM {workshop_assessments} a
2072
                      JOIN {user} r ON (a.reviewerid = r.id)
2073
                      JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
2074
                     WHERE a.submissionid $submissionids
2075
                  ORDER BY a.weight DESC, $sort";
2076
            $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
2077
            foreach ($reviewers as $reviewer) {
2078
                if (!isset($userinfo[$reviewer->reviewerid])) {
2079
                    $userinfo[$reviewer->reviewerid]            = new stdclass();
2080
                    $userinfo[$reviewer->reviewerid]->id        = $reviewer->reviewerid;
2081
                    $userinfo[$reviewer->reviewerid]->picture   = $reviewer->picture;
2082
                    $userinfo[$reviewer->reviewerid]->imagealt  = $reviewer->imagealt;
2083
                    $userinfo[$reviewer->reviewerid]->email     = $reviewer->email;
2084
                    foreach ($additionalnames as $addname) {
2085
                        $userinfo[$reviewer->reviewerid]->$addname = $reviewer->$addname;
2086
                    }
2087
                }
2088
            }
2089
        }
2090
 
2091
        // get the user details for all reviewees of the displayed participants
2092
        $reviewees = array();
2093
        if ($participants) {
2094
            list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
2095
            list($sort, $sortparams) = users_order_by_sql('e');
2096
            $params['workshopid'] = $this->id;
2097
            $userfieldsapi = \core_user\fields::for_userpic();
2098
            $picturefields = $userfieldsapi->get_sql('e', false, '', 'authorid', false)->selects;
2099
            $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,
2100
                           s.id AS submissionid, $picturefields
2101
                      FROM {user} u
2102
                      JOIN {workshop_assessments} a ON (a.reviewerid = u.id)
2103
                      JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
2104
                      JOIN {user} e ON (s.authorid = e.id)
2105
                     WHERE u.id $participantids AND s.workshopid = :workshopid
2106
                  ORDER BY a.weight DESC, $sort";
2107
            $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
2108
            foreach ($reviewees as $reviewee) {
2109
                if (!isset($userinfo[$reviewee->authorid])) {
2110
                    $userinfo[$reviewee->authorid]            = new stdclass();
2111
                    $userinfo[$reviewee->authorid]->id        = $reviewee->authorid;
2112
                    $userinfo[$reviewee->authorid]->picture   = $reviewee->picture;
2113
                    $userinfo[$reviewee->authorid]->imagealt  = $reviewee->imagealt;
2114
                    $userinfo[$reviewee->authorid]->email     = $reviewee->email;
2115
                    foreach ($additionalnames as $addname) {
2116
                        $userinfo[$reviewee->authorid]->$addname = $reviewee->$addname;
2117
                    }
2118
                }
2119
            }
2120
        }
2121
 
2122
        // finally populate the object to be rendered
2123
        $grades = $participants;
2124
 
2125
        foreach ($participants as $participant) {
2126
            // set up default (null) values
2127
            $grades[$participant->userid]->submissionid = null;
2128
            $grades[$participant->userid]->submissiontitle = null;
2129
            $grades[$participant->userid]->submissiongrade = null;
2130
            $grades[$participant->userid]->submissiongradeover = null;
2131
            $grades[$participant->userid]->submissiongradeoverby = null;
2132
            $grades[$participant->userid]->submissionpublished = null;
2133
            $grades[$participant->userid]->reviewedby = array();
2134
            $grades[$participant->userid]->reviewerof = array();
2135
        }
2136
        unset($participants);
2137
        unset($participant);
2138
 
2139
        foreach ($submissions as $submission) {
2140
            $grades[$submission->authorid]->submissionid = $submission->id;
2141
            $grades[$submission->authorid]->submissiontitle = $submission->title;
2142
            $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
2143
            $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
2144
            $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
2145
            $grades[$submission->authorid]->submissionpublished = $submission->published;
2146
        }
2147
        unset($submissions);
2148
        unset($submission);
2149
 
2150
        foreach($reviewers as $reviewer) {
2151
            $info = new stdclass();
2152
            $info->userid = $reviewer->reviewerid;
2153
            $info->assessmentid = $reviewer->assessmentid;
2154
            $info->submissionid = $reviewer->submissionid;
2155
            $info->grade = $this->real_grade($reviewer->grade);
2156
            $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
2157
            $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
2158
            $info->weight = $reviewer->weight;
2159
            $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
2160
        }
2161
        unset($reviewers);
2162
        unset($reviewer);
2163
 
2164
        foreach($reviewees as $reviewee) {
2165
            $info = new stdclass();
2166
            $info->userid = $reviewee->authorid;
2167
            $info->assessmentid = $reviewee->assessmentid;
2168
            $info->submissionid = $reviewee->submissionid;
2169
            $info->grade = $this->real_grade($reviewee->grade);
2170
            $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
2171
            $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
2172
            $info->weight = $reviewee->weight;
2173
            $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
2174
        }
2175
        unset($reviewees);
2176
        unset($reviewee);
2177
 
2178
        foreach ($grades as $grade) {
2179
            $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
2180
        }
2181
 
2182
        $data = new stdclass();
2183
        $data->grades = $grades;
2184
        $data->userinfo = $userinfo;
2185
        $data->totalcount = $numofparticipants;
2186
        $data->maxgrade = $this->real_grade(100);
2187
        $data->maxgradinggrade = $this->real_grading_grade(100);
2188
        return $data;
2189
    }
2190
 
2191
    /**
2192
     * Calculates the real value of a grade
2193
     *
2194
     * @param float $value percentual value from 0 to 100
2195
     * @param float $max   the maximal grade
2196
     * @return string
2197
     */
2198
    public function real_grade_value($value, $max) {
2199
        $localized = true;
2200
        if (is_null($value) or $value === '') {
2201
            return null;
2202
        } elseif ($max == 0) {
2203
            return 0;
2204
        } else {
2205
            return format_float($max * $value / 100, $this->gradedecimals, $localized);
2206
        }
2207
    }
2208
 
2209
    /**
2210
     * Calculates the raw (percentual) value from a real grade
2211
     *
2212
     * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save
2213
     * this value in a raw percentual form into DB
2214
     * @param float $value given grade
2215
     * @param float $max   the maximal grade
2216
     * @return float       suitable to be stored as numeric(10,5)
2217
     */
2218
    public function raw_grade_value($value, $max) {
2219
        if (is_null($value) or $value === '') {
2220
            return null;
2221
        }
2222
        if ($max == 0 or $value < 0) {
2223
            return 0;
2224
        }
2225
        $p = $value / $max * 100;
2226
        if ($p > 100) {
2227
            return $max;
2228
        }
2229
        return grade_floatval($p);
2230
    }
2231
 
2232
    /**
2233
     * Calculates the real value of grade for submission
2234
     *
2235
     * @param float $value percentual value from 0 to 100
2236
     * @return string
2237
     */
2238
    public function real_grade($value) {
2239
        return $this->real_grade_value($value, $this->grade);
2240
    }
2241
 
2242
    /**
2243
     * Calculates the real value of grade for assessment
2244
     *
2245
     * @param float $value percentual value from 0 to 100
2246
     * @return string
2247
     */
2248
    public function real_grading_grade($value) {
2249
        return $this->real_grade_value($value, $this->gradinggrade);
2250
    }
2251
 
2252
    /**
2253
     * Sets the given grades and received grading grades to null
2254
     *
2255
     * This does not clear the information about how the peers filled the assessment forms, but
2256
     * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess
2257
     * the allocated submissions.
2258
     *
2259
     * @return void
2260
     */
2261
    public function clear_assessments() {
2262
        global $DB;
2263
 
2264
        $submissions = $this->get_submissions();
2265
        if (empty($submissions)) {
2266
            // no money, no love
2267
            return;
2268
        }
2269
        $submissions = array_keys($submissions);
2270
        list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED);
2271
        $sql = "submissionid $sql";
2272
        $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params);
2273
        $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params);
2274
    }
2275
 
2276
    /**
2277
     * Sets the grades for submission to null
2278
     *
2279
     * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2280
     * @return void
2281
     */
2282
    public function clear_submission_grades($restrict=null) {
2283
        global $DB;
2284
 
2285
        $sql = "workshopid = :workshopid AND example = 0";
2286
        $params = array('workshopid' => $this->id);
2287
 
2288
        if (is_null($restrict)) {
2289
            // update all users - no more conditions
2290
        } elseif (!empty($restrict)) {
2291
            list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2292
            $sql .= " AND authorid $usql";
2293
            $params = array_merge($params, $uparams);
2294
        } else {
2295
            throw new coding_exception('Empty value is not a valid parameter here');
2296
        }
2297
 
2298
        $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
2299
    }
2300
 
2301
    /**
2302
     * Calculates grades for submission for the given participant(s) and updates it in the database
2303
     *
2304
     * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
2305
     * @return void
2306
     */
2307
    public function aggregate_submission_grades($restrict=null) {
2308
        global $DB;
2309
 
2310
        // fetch a recordset with all assessments to process
2311
        $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
2312
                       a.weight, a.grade
2313
                  FROM {workshop_submissions} s
2314
             LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id)
2315
                 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2316
        $params = array('workshopid' => $this->id);
2317
 
2318
        if (is_null($restrict)) {
2319
            // update all users - no more conditions
2320
        } elseif (!empty($restrict)) {
2321
            list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2322
            $sql .= " AND s.authorid $usql";
2323
            $params = array_merge($params, $uparams);
2324
        } else {
2325
            throw new coding_exception('Empty value is not a valid parameter here');
2326
        }
2327
 
2328
        $sql .= ' ORDER BY s.id'; // this is important for bulk processing
2329
 
2330
        $rs         = $DB->get_recordset_sql($sql, $params);
2331
        $batch      = array();    // will contain a set of all assessments of a single submission
2332
        $previous   = null;       // a previous record in the recordset
2333
 
2334
        foreach ($rs as $current) {
2335
            if (is_null($previous)) {
2336
                // we are processing the very first record in the recordset
2337
                $previous   = $current;
2338
            }
2339
            if ($current->submissionid == $previous->submissionid) {
2340
                // we are still processing the current submission
2341
                $batch[] = $current;
2342
            } else {
2343
                // process all the assessments of a sigle submission
2344
                $this->aggregate_submission_grades_process($batch);
2345
                // and then start to process another submission
2346
                $batch      = array($current);
2347
                $previous   = $current;
2348
            }
2349
        }
2350
        // do not forget to process the last batch!
2351
        $this->aggregate_submission_grades_process($batch);
2352
        $rs->close();
2353
    }
2354
 
2355
    /**
2356
     * Sets the aggregated grades for assessment to null
2357
     *
2358
     * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2359
     * @return void
2360
     */
2361
    public function clear_grading_grades($restrict=null) {
2362
        global $DB;
2363
 
2364
        $sql = "workshopid = :workshopid";
2365
        $params = array('workshopid' => $this->id);
2366
 
2367
        if (is_null($restrict)) {
2368
            // update all users - no more conditions
2369
        } elseif (!empty($restrict)) {
2370
            list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2371
            $sql .= " AND userid $usql";
2372
            $params = array_merge($params, $uparams);
2373
        } else {
2374
            throw new coding_exception('Empty value is not a valid parameter here');
2375
        }
2376
 
2377
        $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
2378
    }
2379
 
2380
    /**
2381
     * Calculates grades for assessment for the given participant(s)
2382
     *
2383
     * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator.
2384
     * The assessment weight is not taken into account here.
2385
     *
2386
     * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
2387
     * @return void
2388
     */
2389
    public function aggregate_grading_grades($restrict=null) {
2390
        global $DB;
2391
 
2392
        // fetch a recordset with all assessments to process
2393
        $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover,
2394
                       ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade
2395
                  FROM {workshop_assessments} a
2396
            INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
2397
             LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid)
2398
                 WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
2399
        $params = array('workshopid' => $this->id);
2400
 
2401
        if (is_null($restrict)) {
2402
            // update all users - no more conditions
2403
        } elseif (!empty($restrict)) {
2404
            list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
2405
            $sql .= " AND a.reviewerid $usql";
2406
            $params = array_merge($params, $uparams);
2407
        } else {
2408
            throw new coding_exception('Empty value is not a valid parameter here');
2409
        }
2410
 
2411
        $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing
2412
 
2413
        $rs         = $DB->get_recordset_sql($sql, $params);
2414
        $batch      = array();    // will contain a set of all assessments of a single submission
2415
        $previous   = null;       // a previous record in the recordset
2416
 
2417
        foreach ($rs as $current) {
2418
            if (is_null($previous)) {
2419
                // we are processing the very first record in the recordset
2420
                $previous   = $current;
2421
            }
2422
            if ($current->reviewerid == $previous->reviewerid) {
2423
                // we are still processing the current reviewer
2424
                $batch[] = $current;
2425
            } else {
2426
                // process all the assessments of a sigle submission
2427
                $this->aggregate_grading_grades_process($batch);
2428
                // and then start to process another reviewer
2429
                $batch      = array($current);
2430
                $previous   = $current;
2431
            }
2432
        }
2433
        // do not forget to process the last batch!
2434
        $this->aggregate_grading_grades_process($batch);
2435
        $rs->close();
2436
    }
2437
 
2438
    /**
2439
     * Returns the mform the teachers use to put a feedback for the reviewer
2440
     *
2441
     * @param mixed moodle_url|null $actionurl
2442
     * @param stdClass $assessment
2443
     * @param array $options editable, editableweight, overridablegradinggrade
2444
     * @return workshop_feedbackreviewer_form
2445
     */
2446
    public function get_feedbackreviewer_form($actionurl, stdclass $assessment, $options=array()) {
2447
        global $CFG;
2448
        require_once(__DIR__ . '/feedbackreviewer_form.php');
2449
 
2450
        $current = new stdclass();
2451
        $current->asid                      = $assessment->id;
2452
        $current->weight                    = $assessment->weight;
2453
        $current->gradinggrade              = $this->real_grading_grade($assessment->gradinggrade);
2454
        $current->gradinggradeover          = $this->real_grading_grade($assessment->gradinggradeover);
2455
        $current->feedbackreviewer          = $assessment->feedbackreviewer;
2456
        $current->feedbackreviewerformat    = $assessment->feedbackreviewerformat;
2457
        if (is_null($current->gradinggrade)) {
2458
            $current->gradinggrade = get_string('nullgrade', 'workshop');
2459
        }
2460
        if (!isset($options['editable'])) {
2461
            $editable = true;   // by default
2462
        } else {
2463
            $editable = (bool)$options['editable'];
2464
        }
2465
 
2466
        // prepare wysiwyg editor
2467
        $current = file_prepare_standard_editor($current, 'feedbackreviewer', array());
2468
 
2469
        return new workshop_feedbackreviewer_form($actionurl,
2470
                array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2471
                'post', '', null, $editable);
2472
    }
2473
 
2474
    /**
2475
     * Returns the mform the teachers use to put a feedback for the author on their submission
2476
     *
2477
     * @mixed moodle_url|null $actionurl
2478
     * @param stdClass $submission
2479
     * @param array $options editable
2480
     * @return workshop_feedbackauthor_form
2481
     */
2482
    public function get_feedbackauthor_form($actionurl, stdclass $submission, $options=array()) {
2483
        global $CFG;
2484
        require_once(__DIR__ . '/feedbackauthor_form.php');
2485
 
2486
        $current = new stdclass();
2487
        $current->submissionid          = $submission->id;
2488
        $current->published             = $submission->published;
2489
        $current->grade                 = $this->real_grade($submission->grade);
2490
        $current->gradeover             = $this->real_grade($submission->gradeover);
2491
        $current->feedbackauthor        = $submission->feedbackauthor;
2492
        $current->feedbackauthorformat  = $submission->feedbackauthorformat;
2493
        if (is_null($current->grade)) {
2494
            $current->grade = get_string('nullgrade', 'workshop');
2495
        }
2496
        if (!isset($options['editable'])) {
2497
            $editable = true;   // by default
2498
        } else {
2499
            $editable = (bool)$options['editable'];
2500
        }
2501
 
2502
        // prepare wysiwyg editor
2503
        $current = file_prepare_standard_editor($current, 'feedbackauthor', array());
2504
 
2505
        return new workshop_feedbackauthor_form($actionurl,
2506
                array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
2507
                'post', '', null, $editable);
2508
    }
2509
 
2510
    /**
2511
     * Returns the information about the user's grades as they are stored in the gradebook
2512
     *
2513
     * The submission grade is returned for users with the capability mod/workshop:submit and the
2514
     * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
2515
     * user has the capability to view hidden grades, grades must be visible to be returned. Null
2516
     * grades are not returned. If none grade is to be returned, this method returns false.
2517
     *
2518
     * @param int $userid the user's id
2519
     * @return workshop_final_grades|false
2520
     */
2521
    public function get_gradebook_grades($userid) {
2522
        global $CFG;
2523
        require_once($CFG->libdir.'/gradelib.php');
2524
 
2525
        if (empty($userid)) {
2526
            throw new coding_exception('User id expected, empty value given.');
2527
        }
2528
 
2529
        // Read data via the Gradebook API
2530
        $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
2531
 
2532
        $grades = new workshop_final_grades();
2533
 
2534
        if (has_capability('mod/workshop:submit', $this->context, $userid)) {
2535
            if (!empty($gradebook->items[0]->grades)) {
2536
                $submissiongrade = reset($gradebook->items[0]->grades);
2537
                if (!is_null($submissiongrade->grade)) {
2538
                    if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2539
                        $grades->submissiongrade = $submissiongrade;
2540
                    }
2541
                }
2542
            }
2543
        }
2544
 
2545
        if (has_capability('mod/workshop:peerassess', $this->context, $userid)) {
2546
            if (!empty($gradebook->items[1]->grades)) {
2547
                $assessmentgrade = reset($gradebook->items[1]->grades);
2548
                if (!is_null($assessmentgrade->grade)) {
2549
                    if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
2550
                        $grades->assessmentgrade = $assessmentgrade;
2551
                    }
2552
                }
2553
            }
2554
        }
2555
 
2556
        if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
2557
            return $grades;
2558
        }
2559
 
2560
        return false;
2561
    }
2562
 
2563
    /**
2564
     * Return the editor options for the submission content field.
2565
     *
2566
     * @return array
2567
     */
2568
    public function submission_content_options() {
2569
        global $CFG;
2570
        require_once($CFG->dirroot.'/repository/lib.php');
2571
 
2572
        return array(
2573
            'trusttext' => true,
2574
            'subdirs' => false,
2575
            'maxfiles' => $this->nattachments,
2576
            'maxbytes' => $this->maxbytes,
2577
            'context' => $this->context,
2578
            'return_types' => FILE_INTERNAL | FILE_EXTERNAL,
2579
          );
2580
    }
2581
 
2582
    /**
2583
     * Return the filemanager options for the submission attachments field.
2584
     *
2585
     * @return array
2586
     */
2587
    public function submission_attachment_options() {
2588
        global $CFG;
2589
        require_once($CFG->dirroot.'/repository/lib.php');
2590
 
2591
        $options = array(
2592
            'subdirs' => true,
2593
            'maxfiles' => $this->nattachments,
2594
            'maxbytes' => $this->maxbytes,
2595
            'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
2596
        );
2597
 
2598
        $filetypesutil = new \core_form\filetypes_util();
2599
        $options['accepted_types'] = $filetypesutil->normalize_file_types($this->submissionfiletypes);
2600
 
2601
        return $options;
2602
    }
2603
 
2604
    /**
2605
     * Return the editor options for the overall feedback for the author.
2606
     *
2607
     * @return array
2608
     */
2609
    public function overall_feedback_content_options() {
2610
        global $CFG;
2611
        require_once($CFG->dirroot.'/repository/lib.php');
2612
 
2613
        return array(
2614
            'subdirs' => 0,
2615
            'maxbytes' => $this->overallfeedbackmaxbytes,
2616
            'maxfiles' => $this->overallfeedbackfiles,
2617
            'changeformat' => 1,
2618
            'context' => $this->context,
2619
            'return_types' => FILE_INTERNAL,
2620
        );
2621
    }
2622
 
2623
    /**
2624
     * Return the filemanager options for the overall feedback for the author.
2625
     *
2626
     * @return array
2627
     */
2628
    public function overall_feedback_attachment_options() {
2629
        global $CFG;
2630
        require_once($CFG->dirroot.'/repository/lib.php');
2631
 
2632
        $options = array(
2633
            'subdirs' => 1,
2634
            'maxbytes' => $this->overallfeedbackmaxbytes,
2635
            'maxfiles' => $this->overallfeedbackfiles,
2636
            'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
2637
        );
2638
 
2639
        $filetypesutil = new \core_form\filetypes_util();
2640
        $options['accepted_types'] = $filetypesutil->normalize_file_types($this->overallfeedbackfiletypes);
2641
 
2642
        return $options;
2643
    }
2644
 
2645
    /**
2646
     * Performs the reset of this workshop instance.
2647
     *
2648
     * @param stdClass $data The actual course reset settings.
2649
     * @return array List of results, each being array[(string)component, (string)item, (string)error]
2650
     */
2651
    public function reset_userdata(stdClass $data) {
2652
 
2653
        $componentstr = get_string('pluginname', 'workshop').': '.format_string($this->name);
2654
        $status = array();
2655
 
2656
        if (!empty($data->reset_workshop_assessments) or !empty($data->reset_workshop_submissions)) {
2657
            // Reset all data related to assessments, including assessments of
2658
            // example submissions.
2659
            $result = $this->reset_userdata_assessments($data);
2660
            if ($result === true) {
2661
                $status[] = array(
2662
                    'component' => $componentstr,
2663
                    'item' => get_string('resetassessments', 'mod_workshop'),
2664
                    'error' => false,
2665
                );
2666
            } else {
2667
                $status[] = array(
2668
                    'component' => $componentstr,
2669
                    'item' => get_string('resetassessments', 'mod_workshop'),
2670
                    'error' => $result,
2671
                );
2672
            }
2673
        }
2674
 
2675
        if (!empty($data->reset_workshop_submissions)) {
2676
            // Reset all remaining data related to submissions.
2677
            $result = $this->reset_userdata_submissions($data);
2678
            if ($result === true) {
2679
                $status[] = array(
2680
                    'component' => $componentstr,
2681
                    'item' => get_string('resetsubmissions', 'mod_workshop'),
2682
                    'error' => false,
2683
                );
2684
            } else {
2685
                $status[] = array(
2686
                    'component' => $componentstr,
2687
                    'item' => get_string('resetsubmissions', 'mod_workshop'),
2688
                    'error' => $result,
2689
                );
2690
            }
2691
        }
2692
 
2693
        if (!empty($data->reset_workshop_phase)) {
2694
            // Do not use the {@link workshop::switch_phase()} here, we do not
2695
            // want to trigger events.
2696
            $this->reset_phase();
2697
            $status[] = array(
2698
                'component' => $componentstr,
2699
                'item' => get_string('resetsubmissions', 'mod_workshop'),
2700
                'error' => false,
2701
            );
2702
        }
2703
 
2704
        return $status;
2705
    }
2706
 
2707
    /**
2708
     * Check if the current user can access the other user's group.
2709
     *
2710
     * This is typically used for teacher roles that have permissions like
2711
     * 'view all submissions'. Even with such a permission granted, we have to
2712
     * check the workshop activity group mode.
2713
     *
2714
     * If the workshop is not in a group mode, or if it is in the visible group
2715
     * mode, this method returns true. This is consistent with how the
2716
     * {@link groups_get_activity_allowed_groups()} behaves.
2717
     *
2718
     * If the workshop is in a separate group mode, the current user has to
2719
     * have the 'access all groups' permission, or share at least one
2720
     * accessible group with the other user.
2721
     *
2722
     * @param int $otheruserid The ID of the other user, e.g. the author of a submission.
2723
     * @return bool False if the current user cannot access the other user's group.
2724
     */
2725
    public function check_group_membership($otheruserid) {
2726
        global $USER;
2727
 
2728
        if (groups_get_activity_groupmode($this->cm) != SEPARATEGROUPS) {
2729
            // The workshop is not in a group mode, or it is in a visible group mode.
2730
            return true;
2731
 
2732
        } else if (has_capability('moodle/site:accessallgroups', $this->context)) {
2733
            // The current user can access all groups.
2734
            return true;
2735
 
2736
        } else {
2737
            $thisusersgroups = groups_get_all_groups($this->course->id, $USER->id, $this->cm->groupingid, 'g.id');
2738
            $otherusersgroups = groups_get_all_groups($this->course->id, $otheruserid, $this->cm->groupingid, 'g.id');
2739
            $commongroups = array_intersect_key($thisusersgroups, $otherusersgroups);
2740
 
2741
            if (empty($commongroups)) {
2742
                // The current user has no group common with the other user.
2743
                return false;
2744
 
2745
            } else {
2746
                // The current user has a group common with the other user.
2747
                return true;
2748
            }
2749
        }
2750
    }
2751
 
2752
    /**
2753
     * Check whether the given user has assessed all his required examples before submission.
2754
     *
2755
     * @param  int $userid the user to check
2756
     * @return bool        false if there are examples missing assessment, true otherwise.
2757
     * @since  Moodle 3.4
2758
     */
2759
    public function check_examples_assessed_before_submission($userid) {
2760
 
2761
        if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_SUBMISSION
2762
            and !has_capability('mod/workshop:manageexamples', $this->context)) {
2763
 
2764
            // Check that all required examples have been assessed by the user.
2765
            $examples = $this->get_examples_for_reviewer($userid);
2766
            foreach ($examples as $exampleid => $example) {
2767
                if (is_null($example->assessmentid)) {
2768
                    $examples[$exampleid]->assessmentid = $this->add_allocation($example, $userid, 0);
2769
                }
2770
                if (is_null($example->grade)) {
2771
                    return false;
2772
                }
2773
            }
2774
        }
2775
        return true;
2776
    }
2777
 
2778
    /**
2779
     * Check that all required examples have been assessed by the given user.
2780
     *
2781
     * @param  stdClass $userid     the user (reviewer) to check
2782
     * @return mixed bool|state     false and notice code if there are examples missing assessment, true otherwise.
2783
     * @since  Moodle 3.4
2784
     */
2785
    public function check_examples_assessed_before_assessment($userid) {
2786
 
2787
        if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_ASSESSMENT
2788
                and !has_capability('mod/workshop:manageexamples', $this->context)) {
2789
 
2790
            // The reviewer must have submitted their own submission.
2791
            $reviewersubmission = $this->get_submission_by_author($userid);
2792
            if (!$reviewersubmission) {
2793
                // No money, no love.
2794
                return array(false, 'exampleneedsubmission');
2795
            } else {
2796
                $examples = $this->get_examples_for_reviewer($userid);
2797
                foreach ($examples as $exampleid => $example) {
2798
                    if (is_null($example->grade)) {
2799
                        return array(false, 'exampleneedassessed');
2800
                    }
2801
                }
2802
            }
2803
        }
2804
        return array(true, null);
2805
    }
2806
 
2807
    /**
2808
     * Trigger module viewed event and set the module viewed for completion.
2809
     *
2810
     * @since  Moodle 3.4
2811
     */
2812
    public function set_module_viewed() {
2813
        global $CFG;
2814
        require_once($CFG->libdir . '/completionlib.php');
2815
 
2816
        // Mark viewed.
2817
        $completion = new completion_info($this->course);
2818
        $completion->set_module_viewed($this->cm);
2819
 
2820
        $eventdata = array();
2821
        $eventdata['objectid'] = $this->id;
2822
        $eventdata['context'] = $this->context;
2823
 
2824
        // Trigger module viewed event.
2825
        $event = \mod_workshop\event\course_module_viewed::create($eventdata);
2826
        $event->add_record_snapshot('course', $this->course);
2827
        $event->add_record_snapshot('workshop', $this->dbrecord);
2828
        $event->add_record_snapshot('course_modules', $this->cm);
2829
        $event->trigger();
2830
    }
2831
 
2832
    /**
2833
     * Validates the submission form or WS data.
2834
     *
2835
     * @param  array $data the data to be validated
2836
     * @return array       the validation errors (if any)
2837
     * @since  Moodle 3.4
2838
     */
2839
    public function validate_submission_data($data) {
2840
        global $DB, $USER;
2841
 
2842
        $errors = array();
2843
        if (empty($data['id']) and empty($data['example'])) {
2844
            // Make sure there is no submission saved meanwhile from another browser window.
2845
            $sql = "SELECT COUNT(s.id)
2846
                      FROM {workshop_submissions} s
2847
                      JOIN {workshop} w ON (s.workshopid = w.id)
2848
                      JOIN {course_modules} cm ON (w.id = cm.instance)
2849
                      JOIN {modules} m ON (m.name = 'workshop' AND m.id = cm.module)
2850
                     WHERE cm.id = ? AND s.authorid = ? AND s.example = 0";
2851
 
2852
            if ($DB->count_records_sql($sql, array($data['cmid'], $USER->id))) {
2853
                $errors['title'] = get_string('err_multiplesubmissions', 'mod_workshop');
2854
            }
2855
        }
2856
        // Get the workshop record by id or cmid, depending on whether we're creating or editing a submission.
2857
        if (empty($data['workshopid'])) {
2858
            $workshop = $DB->get_record_select('workshop', 'id = (SELECT instance FROM {course_modules} WHERE id = ?)',
2859
                    [$data['cmid']]);
2860
        } else {
2861
            $workshop = $DB->get_record('workshop', ['id' => $data['workshopid']]);
2862
        }
2863
 
2864
        if (isset($data['attachment_filemanager'])) {
2865
            $getfiles = file_get_drafarea_files($data['attachment_filemanager']);
2866
            $attachments = $getfiles->list;
2867
        } else {
2868
            $attachments = array();
2869
        }
2870
 
2871
        if ($workshop->submissiontypefile == WORKSHOP_SUBMISSION_TYPE_REQUIRED) {
2872
            if (empty($attachments)) {
2873
                $errors['attachment_filemanager'] = get_string('err_required', 'form');
2874
            }
2875
        } else if ($workshop->submissiontypefile == WORKSHOP_SUBMISSION_TYPE_DISABLED && !empty($data['attachment_filemanager'])) {
2876
            $errors['attachment_filemanager'] = get_string('submissiontypedisabled', 'mod_workshop');
2877
        }
2878
 
2879
        if ($workshop->submissiontypetext == WORKSHOP_SUBMISSION_TYPE_REQUIRED && html_is_blank($data['content_editor']['text'])) {
2880
            $errors['content_editor'] = get_string('err_required', 'form');
2881
        } else if ($workshop->submissiontypetext == WORKSHOP_SUBMISSION_TYPE_DISABLED && !empty($data['content_editor']['text'])) {
2882
            $errors['content_editor'] = get_string('submissiontypedisabled', 'mod_workshop');
2883
        }
2884
 
2885
        // If neither type is explicitly required, one or the other must be submitted.
2886
        if ($workshop->submissiontypetext != WORKSHOP_SUBMISSION_TYPE_REQUIRED
2887
                && $workshop->submissiontypefile != WORKSHOP_SUBMISSION_TYPE_REQUIRED
2888
                && empty($attachments) && html_is_blank($data['content_editor']['text'])) {
2889
            $errors['content_editor'] = get_string('submissionrequiredcontent', 'mod_workshop');
2890
            $errors['attachment_filemanager'] = get_string('submissionrequiredfile', 'mod_workshop');
2891
        }
2892
 
2893
        return $errors;
2894
    }
2895
 
2896
    /**
2897
     * Adds or updates a submission.
2898
     *
2899
     * @param stdClass $submission The submissin data (via form or via WS).
2900
     * @return the new or updated submission id.
2901
     * @since  Moodle 3.4
2902
     */
2903
    public function edit_submission($submission) {
2904
        global $USER, $DB;
2905
 
2906
        if ($submission->example == 0) {
2907
            // This was used just for validation, it must be set to zero when dealing with normal submissions.
2908
            unset($submission->example);
2909
        } else {
2910
            throw new coding_exception('Invalid submission form data value: example');
2911
        }
2912
        $timenow = time();
2913
        if (is_null($submission->id)) {
2914
            $submission->workshopid     = $this->id;
2915
            $submission->example        = 0;
2916
            $submission->authorid       = $USER->id;
2917
            $submission->timecreated    = $timenow;
2918
            $submission->feedbackauthorformat = editors_get_preferred_format();
2919
        }
2920
        $submission->timemodified       = $timenow;
2921
        $submission->title              = trim($submission->title);
2922
        $submission->content            = '';          // Updated later.
2923
        $submission->contentformat      = FORMAT_HTML; // Updated later.
2924
        $submission->contenttrust       = 0;           // Updated later.
2925
        $submission->late               = 0x0;         // Bit mask.
2926
        if (!empty($this->submissionend) and ($this->submissionend < time())) {
2927
            $submission->late = $submission->late | 0x1;
2928
        }
2929
        if ($this->phase == self::PHASE_ASSESSMENT) {
2930
            $submission->late = $submission->late | 0x2;
2931
        }
2932
 
2933
        // Event information.
2934
        $params = array(
2935
            'context' => $this->context,
2936
            'courseid' => $this->course->id,
2937
            'other' => array(
2938
                'submissiontitle' => $submission->title
2939
            )
2940
        );
2941
        $logdata = null;
2942
        if (is_null($submission->id)) {
2943
            $submission->id = $DB->insert_record('workshop_submissions', $submission);
2944
            $params['objectid'] = $submission->id;
2945
            $event = \mod_workshop\event\submission_created::create($params);
2946
            $event->trigger();
2947
        } else {
2948
            if (empty($submission->id) or empty($submission->id) or ($submission->id != $submission->id)) {
2949
                throw new moodle_exception('err_submissionid', 'workshop');
2950
            }
2951
        }
2952
        $params['objectid'] = $submission->id;
2953
 
2954
        // Save and relink embedded images and save attachments.
2955
        if ($this->submissiontypetext != WORKSHOP_SUBMISSION_TYPE_DISABLED) {
2956
            $submission = file_postupdate_standard_editor($submission, 'content', $this->submission_content_options(),
2957
                    $this->context, 'mod_workshop', 'submission_content', $submission->id);
2958
        }
2959
 
2960
        $submission = file_postupdate_standard_filemanager($submission, 'attachment', $this->submission_attachment_options(),
2961
            $this->context, 'mod_workshop', 'submission_attachment', $submission->id);
2962
 
2963
        if (empty($submission->attachment)) {
2964
            // Explicit cast to zero integer.
2965
            $submission->attachment = 0;
2966
        }
2967
        // Store the updated values or re-save the new submission (re-saving needed because URLs are now rewritten).
2968
        $DB->update_record('workshop_submissions', $submission);
2969
        $event = \mod_workshop\event\submission_updated::create($params);
2970
        $event->add_record_snapshot('workshop', $this->dbrecord);
2971
        $event->trigger();
2972
 
2973
        // Send submitted content for plagiarism detection.
2974
        $fs = get_file_storage();
2975
        $files = $fs->get_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
2976
 
2977
        $params['other']['content'] = $submission->content;
2978
        $params['other']['pathnamehashes'] = array_keys($files);
2979
 
2980
        $event = \mod_workshop\event\assessable_uploaded::create($params);
2981
        $event->trigger();
2982
 
2983
        return $submission->id;
2984
    }
2985
 
2986
    /**
2987
     * Helper method for validating if the current user can view the given assessment.
2988
     *
2989
     * @param  stdClass   $assessment assessment object
2990
     * @param  stdClass   $submission submission object
2991
     * @return void
2992
     * @throws moodle_exception
2993
     * @since  Moodle 3.4
2994
     */
2995
    public function check_view_assessment($assessment, $submission) {
2996
        global $USER;
2997
 
2998
        $isauthor = $submission->authorid == $USER->id;
2999
        $isreviewer = $assessment->reviewerid == $USER->id;
3000
        $canviewallassessments  = has_capability('mod/workshop:viewallassessments', $this->context);
3001
        $canviewallsubmissions  = has_capability('mod/workshop:viewallsubmissions', $this->context);
3002
 
3003
        $canviewallsubmissions = $canviewallsubmissions && $this->check_group_membership($submission->authorid);
3004
 
3005
        if (!$isreviewer and !$isauthor and !($canviewallassessments and $canviewallsubmissions)) {
3006
            throw new \moodle_exception('nopermissions', 'error', $this->view_url(), 'view this assessment');
3007
        }
3008
 
3009
        if ($isauthor and !$isreviewer and !$canviewallassessments and $this->phase != self::PHASE_CLOSED) {
3010
            // Authors can see assessments of their work at the end of workshop only.
3011
            throw new \moodle_exception('nopermissions', 'error', $this->view_url(),
3012
                'view assessment of own work before workshop is closed');
3013
        }
3014
    }
3015
 
3016
    /**
3017
     * Helper method for validating if the current user can edit the given assessment.
3018
     *
3019
     * @param  stdClass   $assessment assessment object
3020
     * @param  stdClass   $submission submission object
3021
     * @return void
3022
     * @throws moodle_exception
3023
     * @since  Moodle 3.4
3024
     */
3025
    public function check_edit_assessment($assessment, $submission) {
3026
        global $USER;
3027
 
3028
        $this->check_view_assessment($assessment, $submission);
3029
        // Further checks.
3030
        $isreviewer = ($USER->id == $assessment->reviewerid);
3031
 
3032
        $assessmenteditable = $isreviewer && $this->assessing_allowed($USER->id);
3033
        if (!$assessmenteditable) {
3034
            throw new moodle_exception('nopermissions', 'error', '', 'edit assessments');
3035
        }
3036
 
3037
        list($assessed, $notice) = $this->check_examples_assessed_before_assessment($assessment->reviewerid);
3038
        if (!$assessed) {
3039
            throw new moodle_exception($notice, 'mod_workshop');
3040
        }
3041
    }
3042
 
3043
    /**
3044
     * Adds information to an allocated assessment (function used the first time a review is done or when updating an existing one).
3045
     *
3046
     * @param  stdClass $assessment the assessment
3047
     * @param  stdClass $submission the submission
3048
     * @param  stdClass $data       the assessment data to be added or Updated
3049
     * @param  stdClass $strategy   the strategy instance
3050
     * @return float|null           Raw percentual grade (0.00000 to 100.00000) for submission
3051
     * @since  Moodle 3.4
3052
     */
3053
    public function edit_assessment($assessment, $submission, $data, $strategy) {
3054
        global $DB;
3055
 
3056
        $cansetassessmentweight = has_capability('mod/workshop:allocate', $this->context);
3057
 
3058
        // Let the grading strategy subplugin save its data.
3059
        $rawgrade = $strategy->save_assessment($assessment, $data);
3060
 
3061
        // Store the data managed by the workshop core.
3062
        $coredata = (object)array('id' => $assessment->id);
3063
        if (isset($data->feedbackauthor_editor)) {
3064
            $coredata->feedbackauthor_editor = $data->feedbackauthor_editor;
3065
            $coredata = file_postupdate_standard_editor($coredata, 'feedbackauthor', $this->overall_feedback_content_options(),
3066
                $this->context, 'mod_workshop', 'overallfeedback_content', $assessment->id);
3067
            unset($coredata->feedbackauthor_editor);
3068
        }
3069
        if (isset($data->feedbackauthorattachment_filemanager)) {
3070
            $coredata->feedbackauthorattachment_filemanager = $data->feedbackauthorattachment_filemanager;
3071
            $coredata = file_postupdate_standard_filemanager($coredata, 'feedbackauthorattachment',
3072
                $this->overall_feedback_attachment_options(), $this->context, 'mod_workshop', 'overallfeedback_attachment',
3073
                $assessment->id);
3074
            unset($coredata->feedbackauthorattachment_filemanager);
3075
            if (empty($coredata->feedbackauthorattachment)) {
3076
                $coredata->feedbackauthorattachment = 0;
3077
            }
3078
        }
3079
        if (isset($data->weight) and $cansetassessmentweight) {
3080
            $coredata->weight = $data->weight;
3081
        }
3082
        // Update the assessment data if there is something other than just the 'id'.
3083
        if (count((array)$coredata) > 1 ) {
3084
            $DB->update_record('workshop_assessments', $coredata);
3085
            $params = array(
3086
                'relateduserid' => $submission->authorid,
3087
                'objectid' => $assessment->id,
3088
                'context' => $this->context,
3089
                'other' => array(
3090
                    'workshopid' => $this->id,
3091
                    'submissionid' => $assessment->submissionid
3092
                )
3093
            );
3094
 
3095
            if (is_null($assessment->grade)) {
3096
                // All workshop_assessments are created when allocations are made. The create event is of more use located here.
3097
                $event = \mod_workshop\event\submission_assessed::create($params);
3098
                $event->trigger();
3099
            } else {
3100
                $params['other']['grade'] = $assessment->grade;
3101
                $event = \mod_workshop\event\submission_reassessed::create($params);
3102
                $event->trigger();
3103
            }
3104
        }
3105
        return $rawgrade;
3106
    }
3107
 
3108
    /**
3109
     * Evaluates an assessment.
3110
     *
3111
     * @param  stdClass $assessment the assessment
3112
     * @param  stdClass $data       the assessment data to be updated
3113
     * @param  bool $cansetassessmentweight   whether the user can change the assessment weight
3114
     * @param  bool $canoverridegrades   whether the user can override the assessment grades
3115
     * @return void
3116
     * @since  Moodle 3.4
3117
     */
3118
    public function evaluate_assessment($assessment, $data, $cansetassessmentweight, $canoverridegrades) {
3119
        global $DB, $USER;
3120
 
3121
        $data = file_postupdate_standard_editor($data, 'feedbackreviewer', array(), $this->context);
3122
        $record = new stdclass();
3123
        $record->id = $assessment->id;
3124
        if ($cansetassessmentweight) {
3125
            $record->weight = $data->weight;
3126
        }
3127
        if ($canoverridegrades) {
3128
            $record->gradinggradeover = $this->raw_grade_value($data->gradinggradeover, $this->gradinggrade);
3129
            $record->gradinggradeoverby = $USER->id;
3130
            $record->feedbackreviewer = $data->feedbackreviewer;
3131
            $record->feedbackreviewerformat = $data->feedbackreviewerformat;
3132
        }
3133
        $DB->update_record('workshop_assessments', $record);
3134
    }
3135
 
3136
    /**
3137
     * Trigger submission viewed event.
3138
     *
3139
     * @param stdClass $submission submission object
3140
     * @since  Moodle 3.4
3141
     */
3142
    public function set_submission_viewed($submission) {
3143
        $params = array(
3144
            'objectid' => $submission->id,
3145
            'context' => $this->context,
3146
            'courseid' => $this->course->id,
3147
            'relateduserid' => $submission->authorid,
3148
            'other' => array(
3149
                'workshopid' => $this->id
3150
            )
3151
        );
3152
 
3153
        $event = \mod_workshop\event\submission_viewed::create($params);
3154
        $event->trigger();
3155
    }
3156
 
3157
    /**
3158
     * Evaluates a submission.
3159
     *
3160
     * @param  stdClass $submission the submission
3161
     * @param  stdClass $data       the submission data to be updated
3162
     * @param  bool $canpublish     whether the user can publish the submission
3163
     * @param  bool $canoverride    whether the user can override the submission grade
3164
     * @return void
3165
     * @since  Moodle 3.4
3166
     */
3167
    public function evaluate_submission($submission, $data, $canpublish, $canoverride) {
3168
        global $DB, $USER;
3169
 
3170
        $data = file_postupdate_standard_editor($data, 'feedbackauthor', array(), $this->context);
3171
        $record = new stdclass();
3172
        $record->id = $submission->id;
3173
        if ($canoverride) {
3174
            $record->gradeover = $this->raw_grade_value($data->gradeover, $this->grade);
3175
            $record->gradeoverby = $USER->id;
3176
            $record->feedbackauthor = $data->feedbackauthor;
3177
            $record->feedbackauthorformat = $data->feedbackauthorformat;
3178
        }
3179
        if ($canpublish) {
3180
            $record->published = !empty($data->published);
3181
        }
3182
        $DB->update_record('workshop_submissions', $record);
3183
    }
3184
 
3185
    /**
3186
     * Get the initial first name.
3187
     *
3188
     * @return string|null initial of first name we are currently filtering by.
3189
     */
3190
    public function get_initial_first(): ?string {
3191
        if (empty($this->initialbarprefs['i_first'])) {
3192
            return null;
3193
        }
3194
 
3195
        return $this->initialbarprefs['i_first'];
3196
    }
3197
 
3198
    /**
3199
     * Get the initial last name.
3200
     *
3201
     * @return string|null initial of last name we are currently filtering by.
3202
     */
3203
    public function get_initial_last(): ?string {
3204
        if (empty($this->initialbarprefs['i_last'])) {
3205
            return null;
3206
        }
3207
 
3208
        return $this->initialbarprefs['i_last'];
3209
    }
3210
 
3211
    /**
3212
     * Init method for initial bars.
3213
     * @return void
3214
     */
3215
    public function init_initial_bar(): void {
3216
        global $SESSION;
3217
        if ($this->phase === self::PHASE_SETUP) {
3218
            return;
3219
        }
3220
 
3221
        $ifirst = optional_param('ifirst', null, PARAM_NOTAGS);
3222
        $ilast = optional_param('ilast', null, PARAM_NOTAGS);
3223
 
3224
        if (empty($SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id])) {
3225
            $SESSION->mod_workshop = new stdClass();
3226
            $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id] = [];
3227
        }
3228
        if (!empty($SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_first'])) {
3229
            $this->initialbarprefs['i_first'] = $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_first'];
3230
        }
3231
        if (!empty($SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_last'])) {
3232
            $this->initialbarprefs['i_last'] = $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_last'];
3233
        }
3234
        if (!is_null($ifirst)) {
3235
            $this->initialbarprefs['i_first'] = $ifirst;
3236
            $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_first'] = $ifirst;
3237
        }
3238
 
3239
        if (!is_null($ilast)) {
3240
            $this->initialbarprefs['i_last'] = $ilast;
3241
            $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_last'] = $ilast;
3242
        }
3243
    }
3244
 
3245
    ////////////////////////////////////////////////////////////////////////////////
3246
    // Internal methods (implementation details)                                  //
3247
    ////////////////////////////////////////////////////////////////////////////////
3248
 
3249
    /**
3250
     * Given an array of all assessments of a single submission, calculates the final grade for this submission
3251
     *
3252
     * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade
3253
     * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored.
3254
     *
3255
     * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
3256
     * @return void
3257
     */
3258
    protected function aggregate_submission_grades_process(array $assessments) {
3259
        global $DB;
3260
 
3261
        $submissionid   = null; // the id of the submission being processed
3262
        $current        = null; // the grade currently saved in database
3263
        $finalgrade     = null; // the new grade to be calculated
3264
        $sumgrades      = 0;
3265
        $sumweights     = 0;
3266
 
3267
        foreach ($assessments as $assessment) {
3268
            if (is_null($submissionid)) {
3269
                // the id is the same in all records, fetch it during the first loop cycle
3270
                $submissionid = $assessment->submissionid;
3271
            }
3272
            if (is_null($current)) {
3273
                // the currently saved grade is the same in all records, fetch it during the first loop cycle
3274
                $current = $assessment->submissiongrade;
3275
            }
3276
            if (is_null($assessment->grade)) {
3277
                // this was not assessed yet
3278
                continue;
3279
            }
3280
            if ($assessment->weight == 0) {
3281
                // this does not influence the calculation
3282
                continue;
3283
            }
3284
            $sumgrades  += $assessment->grade * $assessment->weight;
3285
            $sumweights += $assessment->weight;
3286
        }
3287
        if ($sumweights > 0 and is_null($finalgrade)) {
3288
            $finalgrade = grade_floatval($sumgrades / $sumweights);
3289
        }
3290
        // check if the new final grade differs from the one stored in the database
3291
        if (grade_floats_different($finalgrade, $current)) {
3292
            // we need to save new calculation into the database
3293
            $record = new stdclass();
3294
            $record->id = $submissionid;
3295
            $record->grade = $finalgrade;
3296
            $record->timegraded = time();
3297
            $DB->update_record('workshop_submissions', $record);
3298
        }
3299
    }
3300
 
3301
    /**
3302
     * Given an array of all assessments done by a single reviewer, calculates the final grading grade
3303
     *
3304
     * This calculates the simple mean of the passed grading grades. If, however, the grading grade
3305
     * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored.
3306
     *
3307
     * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade)
3308
     * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time
3309
     * @return void
3310
     */
3311
    protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
3312
        global $DB;
3313
 
3314
        $reviewerid = null; // the id of the reviewer being processed
3315
        $current    = null; // the gradinggrade currently saved in database
3316
        $finalgrade = null; // the new grade to be calculated
3317
        $agid       = null; // aggregation id
3318
        $sumgrades  = 0;
3319
        $count      = 0;
3320
 
3321
        if (is_null($timegraded)) {
3322
            $timegraded = time();
3323
        }
3324
 
3325
        foreach ($assessments as $assessment) {
3326
            if (is_null($reviewerid)) {
3327
                // the id is the same in all records, fetch it during the first loop cycle
3328
                $reviewerid = $assessment->reviewerid;
3329
            }
3330
            if (is_null($agid)) {
3331
                // the id is the same in all records, fetch it during the first loop cycle
3332
                $agid = $assessment->aggregationid;
3333
            }
3334
            if (is_null($current)) {
3335
                // the currently saved grade is the same in all records, fetch it during the first loop cycle
3336
                $current = $assessment->aggregatedgrade;
3337
            }
3338
            if (!is_null($assessment->gradinggradeover)) {
3339
                // the grading grade for this assessment is overridden by a teacher
3340
                $sumgrades += $assessment->gradinggradeover;
3341
                $count++;
3342
            } else {
3343
                if (!is_null($assessment->gradinggrade)) {
3344
                    $sumgrades += $assessment->gradinggrade;
3345
                    $count++;
3346
                }
3347
            }
3348
        }
3349
        if ($count > 0) {
3350
            $finalgrade = grade_floatval($sumgrades / $count);
3351
        }
3352
 
3353
        // Event information.
3354
        $params = array(
3355
            'context' => $this->context,
3356
            'courseid' => $this->course->id,
3357
            'relateduserid' => $reviewerid
3358
        );
3359
 
3360
        // check if the new final grade differs from the one stored in the database
3361
        if (grade_floats_different($finalgrade, $current)) {
3362
            $params['other'] = array(
3363
                'currentgrade' => $current,
3364
                'finalgrade' => $finalgrade
3365
            );
3366
 
3367
            // we need to save new calculation into the database
3368
            if (is_null($agid)) {
3369
                // no aggregation record yet
3370
                $record = new stdclass();
3371
                $record->workshopid = $this->id;
3372
                $record->userid = $reviewerid;
3373
                $record->gradinggrade = $finalgrade;
3374
                $record->timegraded = $timegraded;
3375
                $record->id = $DB->insert_record('workshop_aggregations', $record);
3376
                $params['objectid'] = $record->id;
3377
                $event = \mod_workshop\event\assessment_evaluated::create($params);
3378
                $event->trigger();
3379
            } else {
3380
                $record = new stdclass();
3381
                $record->id = $agid;
3382
                $record->gradinggrade = $finalgrade;
3383
                $record->timegraded = $timegraded;
3384
                $DB->update_record('workshop_aggregations', $record);
3385
                $params['objectid'] = $agid;
3386
                $event = \mod_workshop\event\assessment_reevaluated::create($params);
3387
                $event->trigger();
3388
            }
3389
        }
3390
    }
3391
 
3392
    /**
1441 ariadna 3393
     * This is a replacement for the old get_users_with_capability_sql method.
3394
     * The old method returned huge amounts of SQL for large courses, potentially 10s of thousands of lines
3395
     * with hundreds of UNIONS, which caused some poor performance. This new method aims to streamline it all
3396
     * into one query.
1 efrain 3397
     *
1441 ariadna 3398
     * Gets users with any of the specified capabilities on the workshop activity.
1 efrain 3399
     *
3400
     * The list is automatically restricted according to any availability restrictions
3401
     * that apply to user lists (e.g. group, grouping restrictions).
3402
     *
1441 ariadna 3403
     * @param array $capabilities array of capability names (If the user has ANY of them, it returns true for that user)
3404
     * @param bool $musthavesubmission if true, return only users who have already submitted
1 efrain 3405
     * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1441 ariadna 3406
     * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
3407
     * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
3408
     * @return array of users
1 efrain 3409
     */
1441 ariadna 3410
    protected function get_users_with_capability(array $capabilities, bool $musthavesubmission, int $groupid,
3411
            int $limitfrom = 0, int $limitnum = 0): array {
1 efrain 3412
 
1441 ariadna 3413
        global $CFG, $DB;
1 efrain 3414
 
1441 ariadna 3415
        $params = [];
1 efrain 3416
 
1441 ariadna 3417
        // This is from enrollib.php:get_enrolled_join(). It says it's better for caching to use round.
3418
        $now = round(time(), -2);
3419
        $userfieldsapi = \core_user\fields::for_name()->with_userpic();
1 efrain 3420
 
1441 ariadna 3421
        $sqlarray = [];
3422
        $sqlarray['select'] = "SELECT DISTINCT u.id" . $userfieldsapi->get_sql('u')->selects;
3423
        $sqlarray['from'] = "FROM {user} u";
3424
        $sqlarray['join'] = [];
3425
        $sqlarray['join'][] = "JOIN {user_enrolments} ue ON ue.userid = u.id";
3426
        $sqlarray['join'][] = "JOIN {enrol} e ON e.id = ue.enrolid AND e.courseid = :courseid";
3427
        $sqlarray['where'] = [];
3428
        $sqlarray['where'][] = "WHERE u.deleted = 0";
3429
        $sqlarray['where'][] = "AND u.id <> :guestid";
3430
        $sqlarray['where'][] = "AND ue.status = :activestatus";
3431
        $sqlarray['where'][] = "AND e.status = :enabledstatus";
3432
        $sqlarray['where'][] = "AND ue.timestart < :timestart";
3433
        $sqlarray['where'][] = "AND (ue.timeend > :timeend OR ue.timeend = 0)";
1 efrain 3434
 
1441 ariadna 3435
        // Apply sorting.
3436
        [$sortby, $sortbyparams] = users_order_by_sql('u');
3437
        $sqlarray['sort'] = "ORDER BY {$sortby}";
3438
 
3439
        // Apply filtering.
3440
        [$filtersql, $filterparams] = $this->get_users_with_initial_filtering_sql_where('u');
3441
        if ($filtersql) {
3442
            $sqlarray['where'][] = "AND {$filtersql}";
3443
            $params = array_merge($params, $filterparams);
3444
        }
3445
 
3446
        $params['courseid'] = $this->context->get_course_context()->instanceid;
3447
        $params['timestart'] = $now;
3448
        $params['timeend'] = $now;
3449
        $params['guestid'] = $CFG->siteguest;
3450
        $params['activestatus'] = ENROL_USER_ACTIVE;
3451
        $params['enabledstatus'] = ENROL_INSTANCE_ENABLED;
3452
 
3453
        // If we are filtering by users who have submitted.
1 efrain 3454
        if ($musthavesubmission) {
1441 ariadna 3455
            $sqlarray['join'][] = "JOIN {workshop_submissions} ws ON
3456
                (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid) ";
3457
            $params['workshopid'] = $this->id;
1 efrain 3458
        }
3459
 
1441 ariadna 3460
        // Are we searching one specific group?
3461
        if ($groupid > 0) {
3462
            $sqlarray['join'][] = "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
3463
            $params['groupid'] = $groupid;
3464
        } else if ($this->cm->groupingid) {
3465
            // If not, is there a groupingid set on the activity?
3466
            $sqlarray['join'][] = "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid";
3467
            $sqlarray['join'][] = "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid)";
3468
            $params['groupingid'] = $this->cm->groupingid;
3469
        }
3470
 
3471
        // Is the activity restricted so only certain users can access it?
1 efrain 3472
        $info = new \core_availability\info_module($this->cm);
1441 ariadna 3473
        [$listsql, $listparams] = $info->get_user_list_sql(false);
1 efrain 3474
        if ($listsql) {
1441 ariadna 3475
            $sqlarray['join'][] = " JOIN ($listsql) restricted ON restricted.id = u.id";
1 efrain 3476
            $params = array_merge($params, $listparams);
3477
        }
3478
 
1441 ariadna 3479
        // Join the role assignments to only return users with the right capabilities.
3480
        $capjoin = get_with_capability_join($this->context, $capabilities, 'u.id');
3481
        $sqlarray['join'][] = $capjoin->joins;
3482
 
3483
        // Convert the sql array into a string.
3484
        $sql = $this->build_sql($sqlarray);
3485
 
3486
        // We actually query the users here instead of returning SQL like it used to.
3487
        return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3488
 
1 efrain 3489
    }
3490
 
3491
    /**
1441 ariadna 3492
     * Build SQL string from array of clauses
3493
     *
3494
     * @param array $sqlarray ['select' => '', 'from' => '', 'join' => [], 'where' => [], 'sort' => '']
3495
     * @return string
3496
     */
3497
    protected function build_sql(array $sqlarray): string {
3498
 
3499
        $sql = "";
3500
        foreach ($sqlarray as $el) {
3501
            if (is_array($el)) {
3502
                $sql .= implode(" ", $el) . " ";
3503
            } else {
3504
                $sql .= " {$el} ";
3505
            }
3506
        }
3507
 
3508
        return $sql;
3509
 
3510
    }
3511
 
3512
    /**
1 efrain 3513
     * Returns SQL to fetch all enrolled users with the first name or last name.
3514
     *
1441 ariadna 3515
     * @param string $table Table alias for users table
1 efrain 3516
     * @return array
3517
     */
1441 ariadna 3518
    protected function get_users_with_initial_filtering_sql_where(string $table): array {
1 efrain 3519
        global $DB;
3520
        $conditions = [];
3521
        $params = [];
3522
        $ifirst = $this->get_initial_first();
3523
        $ilast = $this->get_initial_last();
3524
        if ($ifirst) {
1441 ariadna 3525
            $conditions[] = $DB->sql_like('LOWER(' . $table . '.firstname)', ':i_first' , false, false);
1 efrain 3526
            $params['i_first'] = $DB->sql_like_escape($ifirst) . '%';
3527
        }
3528
        if ($ilast) {
1441 ariadna 3529
            $conditions[] = $DB->sql_like('LOWER(' . $table . '.lastname)', ':i_last' , false, false);
1 efrain 3530
            $params['i_last'] = $DB->sql_like_escape($ilast) . '%';
3531
        }
3532
        return [implode(" AND ", $conditions), $params];
3533
    }
3534
 
3535
    /**
3536
     * @return array of available workshop phases
3537
     */
3538
    protected function available_phases_list() {
3539
        return array(
3540
            self::PHASE_SETUP       => true,
3541
            self::PHASE_SUBMISSION  => true,
3542
            self::PHASE_ASSESSMENT  => true,
3543
            self::PHASE_EVALUATION  => true,
3544
            self::PHASE_CLOSED      => true,
3545
        );
3546
    }
3547
 
3548
    /**
3549
     * Converts absolute URL to relative URL needed by {@see add_to_log()}
3550
     *
3551
     * @param moodle_url $url absolute URL
3552
     * @return string
3553
     */
3554
    protected function log_convert_url(moodle_url $fullurl) {
3555
        static $baseurl;
3556
 
3557
        if (!isset($baseurl)) {
3558
            $baseurl = new moodle_url('/mod/workshop/');
3559
            $baseurl = $baseurl->out();
3560
        }
3561
 
3562
        return substr($fullurl->out(), strlen($baseurl));
3563
    }
3564
 
3565
    /**
3566
     * Removes all user data related to assessments (including allocations).
3567
     *
3568
     * This includes assessments of example submissions as long as they are not
3569
     * referential assessments.
3570
     *
3571
     * @param stdClass $data The actual course reset settings.
3572
     * @return bool|string True on success, error message otherwise.
3573
     */
3574
    protected function reset_userdata_assessments(stdClass $data) {
3575
        global $DB;
3576
 
3577
        $sql = "SELECT a.id
3578
                  FROM {workshop_assessments} a
3579
                  JOIN {workshop_submissions} s ON (a.submissionid = s.id)
3580
                 WHERE s.workshopid = :workshopid
3581
                       AND (s.example = 0 OR (s.example = 1 AND a.weight = 0))";
3582
 
3583
        $assessments = $DB->get_records_sql($sql, array('workshopid' => $this->id));
3584
        $this->delete_assessment(array_keys($assessments));
3585
 
3586
        $DB->delete_records('workshop_aggregations', array('workshopid' => $this->id));
3587
 
3588
        return true;
3589
    }
3590
 
3591
    /**
3592
     * Removes all user data related to participants' submissions.
3593
     *
3594
     * @param stdClass $data The actual course reset settings.
3595
     * @return bool|string True on success, error message otherwise.
3596
     */
3597
    protected function reset_userdata_submissions(stdClass $data) {
3598
        global $DB;
3599
 
3600
        $submissions = $this->get_submissions();
3601
        foreach ($submissions as $submission) {
3602
            $this->delete_submission($submission);
3603
        }
3604
 
3605
        return true;
3606
    }
3607
 
3608
    /**
3609
     * Hard set the workshop phase to the setup one.
3610
     */
3611
    protected function reset_phase() {
3612
        global $DB;
3613
 
3614
        $DB->set_field('workshop', 'phase', self::PHASE_SETUP, array('id' => $this->id));
3615
        $this->phase = self::PHASE_SETUP;
3616
    }
3617
}
3618
 
3619
////////////////////////////////////////////////////////////////////////////////
3620
// Renderable components
3621
////////////////////////////////////////////////////////////////////////////////
3622
 
3623
/**
3624
 * Represents the user planner tool
3625
 *
3626
 * Planner contains list of phases. Each phase contains list of tasks. Task is a simple object with
3627
 * title, link and completed (true/false/null logic).
3628
 */
3629
class workshop_user_plan implements renderable {
3630
 
3631
    /** @var int id of the user this plan is for */
3632
    public $userid;
3633
    /** @var workshop */
3634
    public $workshop;
3635
    /** @var array of (stdclass)tasks */
3636
    public $phases = array();
3637
    /** @var null|array of example submissions to be assessed by the planner owner */
3638
    protected $examples = null;
3639
 
3640
    /**
3641
     * Prepare an individual workshop plan for the given user.
3642
     *
3643
     * @param workshop $workshop instance
3644
     * @param int $userid whom the plan is prepared for
3645
     */
3646
    public function __construct(workshop $workshop, $userid) {
3647
        global $DB;
3648
 
3649
        $this->workshop = $workshop;
3650
        $this->userid   = $userid;
3651
 
3652
        //---------------------------------------------------------
3653
        // * SETUP | submission | assessment | evaluation | closed
3654
        //---------------------------------------------------------
3655
        $phase = new stdclass();
3656
        $phase->title = get_string('phasesetup', 'workshop');
3657
        $phase->tasks = array();
3658
        if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3659
            $task = new stdclass();
3660
            $task->title = get_string('taskintro', 'workshop');
3661
            $task->link = $workshop->updatemod_url();
3662
            $task->completed = !(trim($workshop->intro) == '');
3663
            $phase->tasks['intro'] = $task;
3664
        }
3665
        if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3666
            $task = new stdclass();
3667
            $task->title = get_string('taskinstructauthors', 'workshop');
3668
            $task->link = $workshop->updatemod_url();
3669
            $task->completed = !(trim($workshop->instructauthors) == '');
3670
            $phase->tasks['instructauthors'] = $task;
3671
        }
3672
        if (has_capability('mod/workshop:editdimensions', $workshop->context, $userid)) {
3673
            $task = new stdclass();
3674
            $task->title = get_string('editassessmentform', 'workshop');
3675
            $task->link = $workshop->editform_url();
3676
            if ($workshop->grading_strategy_instance()->form_ready()) {
3677
                $task->completed = true;
3678
            } elseif ($workshop->phase > workshop::PHASE_SETUP) {
3679
                $task->completed = false;
3680
            }
3681
            $phase->tasks['editform'] = $task;
3682
        }
3683
        if ($workshop->useexamples and has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
3684
            $task = new stdclass();
3685
            $task->title = get_string('prepareexamples', 'workshop');
3686
            if ($DB->count_records('workshop_submissions', array('example' => 1, 'workshopid' => $workshop->id)) > 0) {
3687
                $task->completed = true;
3688
            } elseif ($workshop->phase > workshop::PHASE_SETUP) {
3689
                $task->completed = false;
3690
            }
3691
            $phase->tasks['prepareexamples'] = $task;
3692
        }
3693
        if (empty($phase->tasks) and $workshop->phase == workshop::PHASE_SETUP) {
3694
            // if we are in the setup phase and there is no task (typical for students), let us
3695
            // display some explanation what is going on
3696
            $task = new stdclass();
3697
            $task->title = get_string('undersetup', 'workshop');
3698
            $task->completed = 'info';
3699
            $phase->tasks['setupinfo'] = $task;
3700
        }
3701
        $this->phases[workshop::PHASE_SETUP] = $phase;
3702
 
3703
        //---------------------------------------------------------
3704
        // setup | * SUBMISSION | assessment | evaluation | closed
3705
        //---------------------------------------------------------
3706
        $phase = new stdclass();
3707
        $phase->title = get_string('phasesubmission', 'workshop');
3708
        $phase->tasks = array();
3709
        if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3710
            $task = new stdclass();
3711
            $task->title = get_string('taskinstructreviewers', 'workshop');
3712
            $task->link = $workshop->updatemod_url();
3713
            if (trim($workshop->instructreviewers)) {
3714
                $task->completed = true;
3715
            } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
3716
                $task->completed = false;
3717
            }
3718
            $phase->tasks['instructreviewers'] = $task;
3719
        }
3720
        if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION
3721
                and has_capability('mod/workshop:submit', $workshop->context, $userid, false)
3722
                    and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
3723
            $task = new stdclass();
3724
            $task->title = get_string('exampleassesstask', 'workshop');
3725
            $examples = $this->get_examples();
3726
            $a = new stdclass();
3727
            $a->expected = count($examples);
3728
            $a->assessed = 0;
3729
            foreach ($examples as $exampleid => $example) {
3730
                if (!is_null($example->grade)) {
3731
                    $a->assessed++;
3732
                }
3733
            }
3734
            $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
3735
            if ($a->assessed == $a->expected) {
3736
                $task->completed = true;
3737
            } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
3738
                $task->completed = false;
3739
            }
3740
            $phase->tasks['examples'] = $task;
3741
        }
3742
        if (has_capability('mod/workshop:submit', $workshop->context, $userid, false)) {
3743
            $task = new stdclass();
3744
            $task->title = get_string('tasksubmit', 'workshop');
3745
            $task->link = $workshop->submission_url();
3746
            if ($DB->record_exists('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0, 'authorid'=>$userid))) {
3747
                $task->completed = true;
3748
            } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
3749
                $task->completed = false;
3750
            } else {
3751
                $task->completed = null;    // still has a chance to submit
3752
            }
3753
            $phase->tasks['submit'] = $task;
3754
        }
3755
        if (has_capability('mod/workshop:allocate', $workshop->context, $userid)) {
3756
            if ($workshop->phaseswitchassessment) {
3757
                $task = new stdClass();
3758
                $allocator = $DB->get_record('workshopallocation_scheduled', array('workshopid' => $workshop->id));
3759
                if (empty($allocator)) {
3760
                    $task->completed = false;
3761
                } else if ($allocator->enabled and is_null($allocator->resultstatus)) {
3762
                    $task->completed = true;
3763
                } else if ($workshop->submissionend > time()) {
3764
                    $task->completed = null;
3765
                } else {
3766
                    $task->completed = false;
3767
                }
3768
                $task->title = get_string('setup', 'workshopallocation_scheduled');
3769
                $task->link = $workshop->allocation_url('scheduled');
3770
                $phase->tasks['allocatescheduled'] = $task;
3771
            }
3772
            $task = new stdclass();
3773
            $task->title = get_string('allocate', 'workshop');
3774
            $task->link = $workshop->allocation_url();
3775
            $numofauthors = $workshop->count_potential_authors(false);
3776
            $numofsubmissions = $DB->count_records('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0));
3777
            $sql = 'SELECT COUNT(s.id) AS nonallocated
3778
                      FROM {workshop_submissions} s
3779
                 LEFT JOIN {workshop_assessments} a ON (a.submissionid=s.id)
3780
                     WHERE s.workshopid = :workshopid AND s.example=0 AND a.submissionid IS NULL';
3781
            $params['workshopid'] = $workshop->id;
3782
            $numnonallocated = $DB->count_records_sql($sql, $params);
3783
            if ($numofsubmissions == 0) {
3784
                $task->completed = null;
3785
            } elseif ($numnonallocated == 0) {
3786
                $task->completed = true;
3787
            } elseif ($workshop->phase > workshop::PHASE_SUBMISSION) {
3788
                $task->completed = false;
3789
            } else {
3790
                $task->completed = null;    // still has a chance to allocate
3791
            }
3792
            $a = new stdclass();
3793
            $a->expected    = $numofauthors;
3794
            $a->submitted   = $numofsubmissions;
3795
            $a->allocate    = $numnonallocated;
3796
            $task->details  = get_string('allocatedetails', 'workshop', $a);
3797
            unset($a);
3798
            $phase->tasks['allocate'] = $task;
3799
 
3800
            if ($numofsubmissions < $numofauthors and $workshop->phase >= workshop::PHASE_SUBMISSION) {
3801
                $task = new stdclass();
3802
                $task->title = get_string('someuserswosubmission', 'workshop');
3803
                $task->completed = 'info';
3804
                $phase->tasks['allocateinfo'] = $task;
3805
            }
3806
 
3807
        }
3808
        if ($workshop->submissionstart) {
3809
            $task = new stdclass();
3810
            $task->title = get_string('submissionstartdatetime', 'workshop', workshop::timestamp_formats($workshop->submissionstart));
3811
            $task->completed = 'info';
3812
            $phase->tasks['submissionstartdatetime'] = $task;
3813
        }
3814
        if ($workshop->submissionend) {
3815
            $task = new stdclass();
3816
            $task->title = get_string('submissionenddatetime', 'workshop', workshop::timestamp_formats($workshop->submissionend));
3817
            $task->completed = 'info';
3818
            $phase->tasks['submissionenddatetime'] = $task;
3819
        }
3820
        if (($workshop->submissionstart < time()) and $workshop->latesubmissions) {
3821
            // If submission deadline has passed and late submissions are allowed, only display 'latesubmissionsallowed' text to
3822
            // users (students) who have not submitted and users(teachers, admins)  who can switch pahase..
3823
            if (has_capability('mod/workshop:switchphase', $workshop->context, $userid) ||
3824
                    (!$workshop->get_submission_by_author($userid) && $workshop->submissionend < time())) {
3825
                $task = new stdclass();
3826
                $task->title = get_string('latesubmissionsallowed', 'workshop');
3827
                $task->completed = 'info';
3828
                $phase->tasks['latesubmissionsallowed'] = $task;
3829
            }
3830
        }
3831
        if (isset($phase->tasks['submissionstartdatetime']) or isset($phase->tasks['submissionenddatetime'])) {
3832
            if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
3833
                $task = new stdclass();
3834
                $task->title = get_string('deadlinesignored', 'workshop');
3835
                $task->completed = 'info';
3836
                $phase->tasks['deadlinesignored'] = $task;
3837
            }
3838
        }
3839
        $this->phases[workshop::PHASE_SUBMISSION] = $phase;
3840
 
3841
        //---------------------------------------------------------
3842
        // setup | submission | * ASSESSMENT | evaluation | closed
3843
        //---------------------------------------------------------
3844
        $phase = new stdclass();
3845
        $phase->title = get_string('phaseassessment', 'workshop');
3846
        $phase->tasks = array();
3847
        $phase->isreviewer = has_capability('mod/workshop:peerassess', $workshop->context, $userid);
3848
        if ($workshop->phase == workshop::PHASE_SUBMISSION and $workshop->phaseswitchassessment
3849
                and has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
3850
            $task = new stdClass();
3851
            $task->title = get_string('switchphase30auto', 'mod_workshop', workshop::timestamp_formats($workshop->submissionend));
3852
            $task->completed = 'info';
3853
            $phase->tasks['autoswitchinfo'] = $task;
3854
        }
3855
        if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_ASSESSMENT
3856
                and $phase->isreviewer and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
3857
            $task = new stdclass();
3858
            $task->title = get_string('exampleassesstask', 'workshop');
3859
            $examples = $workshop->get_examples_for_reviewer($userid);
3860
            $a = new stdclass();
3861
            $a->expected = count($examples);
3862
            $a->assessed = 0;
3863
            foreach ($examples as $exampleid => $example) {
3864
                if (!is_null($example->grade)) {
3865
                    $a->assessed++;
3866
                }
3867
            }
3868
            $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
3869
            if ($a->assessed == $a->expected) {
3870
                $task->completed = true;
3871
            } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3872
                $task->completed = false;
3873
            }
3874
            $phase->tasks['examples'] = $task;
3875
        }
3876
        if (empty($phase->tasks['examples']) or !empty($phase->tasks['examples']->completed)) {
3877
            $phase->assessments = $workshop->get_assessments_by_reviewer($userid);
3878
            $numofpeers     = 0;    // number of allocated peer-assessments
3879
            $numofpeerstodo = 0;    // number of peer-assessments to do
3880
            $numofself      = 0;    // number of allocated self-assessments - should be 0 or 1
3881
            $numofselftodo  = 0;    // number of self-assessments to do - should be 0 or 1
3882
            foreach ($phase->assessments as $a) {
3883
                if ($a->authorid == $userid) {
3884
                    $numofself++;
3885
                    if (is_null($a->grade)) {
3886
                        $numofselftodo++;
3887
                    }
3888
                } else {
3889
                    $numofpeers++;
3890
                    if (is_null($a->grade)) {
3891
                        $numofpeerstodo++;
3892
                    }
3893
                }
3894
            }
3895
            unset($a);
3896
            if ($numofpeers) {
3897
                $task = new stdclass();
3898
                if ($numofpeerstodo == 0) {
3899
                    $task->completed = true;
3900
                } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3901
                    $task->completed = false;
3902
                }
3903
                $a = new stdclass();
3904
                $a->total = $numofpeers;
3905
                $a->todo  = $numofpeerstodo;
3906
                $task->title = get_string('taskassesspeers', 'workshop');
3907
                $task->details = get_string('taskassesspeersdetails', 'workshop', $a);
3908
                unset($a);
3909
                $phase->tasks['assesspeers'] = $task;
3910
            }
3911
            if ($workshop->useselfassessment and $numofself) {
3912
                $task = new stdclass();
3913
                if ($numofselftodo == 0) {
3914
                    $task->completed = true;
3915
                } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
3916
                    $task->completed = false;
3917
                }
3918
                $task->title = get_string('taskassessself', 'workshop');
3919
                $phase->tasks['assessself'] = $task;
3920
            }
3921
        }
3922
        if ($workshop->assessmentstart) {
3923
            $task = new stdclass();
3924
            $task->title = get_string('assessmentstartdatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentstart));
3925
            $task->completed = 'info';
3926
            $phase->tasks['assessmentstartdatetime'] = $task;
3927
        }
3928
        if ($workshop->assessmentend) {
3929
            $task = new stdclass();
3930
            $task->title = get_string('assessmentenddatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentend));
3931
            $task->completed = 'info';
3932
            $phase->tasks['assessmentenddatetime'] = $task;
3933
        }
3934
        if (isset($phase->tasks['assessmentstartdatetime']) or isset($phase->tasks['assessmentenddatetime'])) {
3935
            if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
3936
                $task = new stdclass();
3937
                $task->title = get_string('deadlinesignored', 'workshop');
3938
                $task->completed = 'info';
3939
                $phase->tasks['deadlinesignored'] = $task;
3940
            }
3941
        }
3942
        $this->phases[workshop::PHASE_ASSESSMENT] = $phase;
3943
 
3944
        //---------------------------------------------------------
3945
        // setup | submission | assessment | * EVALUATION | closed
3946
        //---------------------------------------------------------
3947
        $phase = new stdclass();
3948
        $phase->title = get_string('phaseevaluation', 'workshop');
3949
        $phase->tasks = array();
3950
        if (has_capability('mod/workshop:overridegrades', $workshop->context)) {
3951
            $expected = $workshop->count_potential_authors(false);
3952
            $calculated = $DB->count_records_select('workshop_submissions',
3953
                    'workshopid = ? AND (grade IS NOT NULL OR gradeover IS NOT NULL)', array($workshop->id));
3954
            $task = new stdclass();
3955
            $task->title = get_string('calculatesubmissiongrades', 'workshop');
3956
            $a = new stdclass();
3957
            $a->expected    = $expected;
3958
            $a->calculated  = $calculated;
3959
            $task->details  = get_string('calculatesubmissiongradesdetails', 'workshop', $a);
3960
            if ($calculated >= $expected) {
3961
                $task->completed = true;
3962
            } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
3963
                $task->completed = false;
3964
            }
3965
            $phase->tasks['calculatesubmissiongrade'] = $task;
3966
 
3967
            $expected = $workshop->count_potential_reviewers(false);
3968
            $calculated = $DB->count_records_select('workshop_aggregations',
3969
                    'workshopid = ? AND gradinggrade IS NOT NULL', array($workshop->id));
3970
            $task = new stdclass();
3971
            $task->title = get_string('calculategradinggrades', 'workshop');
3972
            $a = new stdclass();
3973
            $a->expected    = $expected;
3974
            $a->calculated  = $calculated;
3975
            $task->details  = get_string('calculategradinggradesdetails', 'workshop', $a);
3976
            if ($calculated >= $expected) {
3977
                $task->completed = true;
3978
            } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
3979
                $task->completed = false;
3980
            }
3981
            $phase->tasks['calculategradinggrade'] = $task;
3982
 
3983
        } elseif ($workshop->phase == workshop::PHASE_EVALUATION) {
3984
            $task = new stdclass();
3985
            $task->title = get_string('evaluategradeswait', 'workshop');
3986
            $task->completed = 'info';
3987
            $phase->tasks['evaluateinfo'] = $task;
3988
        }
3989
 
3990
        if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
3991
            $task = new stdclass();
3992
            $task->title = get_string('taskconclusion', 'workshop');
3993
            $task->link = $workshop->updatemod_url();
3994
            if (trim($workshop->conclusion)) {
3995
                $task->completed = true;
3996
            } elseif ($workshop->phase >= workshop::PHASE_EVALUATION) {
3997
                $task->completed = false;
3998
            }
3999
            $phase->tasks['conclusion'] = $task;
4000
        }
4001
 
4002
        $this->phases[workshop::PHASE_EVALUATION] = $phase;
4003
 
4004
        //---------------------------------------------------------
4005
        // setup | submission | assessment | evaluation | * CLOSED
4006
        //---------------------------------------------------------
4007
        $phase = new stdclass();
4008
        $phase->title = get_string('phaseclosed', 'workshop');
4009
        $phase->tasks = array();
4010
        $this->phases[workshop::PHASE_CLOSED] = $phase;
4011
 
4012
        // Polish data, set default values if not done explicitly
4013
        foreach ($this->phases as $phasecode => $phase) {
4014
            $phase->title       = isset($phase->title)      ? $phase->title     : '';
4015
            $phase->tasks       = isset($phase->tasks)      ? $phase->tasks     : array();
4016
            if ($phasecode == $workshop->phase) {
4017
                $phase->active = true;
4018
            } else {
4019
                $phase->active = false;
4020
            }
4021
            if (!isset($phase->actions)) {
4022
                $phase->actions = array();
4023
            }
4024
 
4025
            foreach ($phase->tasks as $taskcode => $task) {
4026
                $task->title        = isset($task->title)       ? $task->title      : '';
4027
                $task->link         = isset($task->link)        ? $task->link       : null;
4028
                $task->details      = isset($task->details)     ? $task->details    : '';
4029
                $task->completed    = isset($task->completed)   ? $task->completed  : null;
4030
            }
4031
        }
4032
 
4033
        // Add phase switching actions.
4034
        if (has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
4035
            $nextphases = array(
4036
                workshop::PHASE_SETUP => workshop::PHASE_SUBMISSION,
4037
                workshop::PHASE_SUBMISSION => workshop::PHASE_ASSESSMENT,
4038
                workshop::PHASE_ASSESSMENT => workshop::PHASE_EVALUATION,
4039
                workshop::PHASE_EVALUATION => workshop::PHASE_CLOSED,
4040
            );
4041
            foreach ($this->phases as $phasecode => $phase) {
4042
                if ($phase->active) {
4043
                    if (isset($nextphases[$workshop->phase])) {
4044
                        $task = new stdClass();
4045
                        $task->title = get_string('switchphasenext', 'mod_workshop');
4046
                        $task->link = $workshop->switchphase_url($nextphases[$workshop->phase]);
4047
                        $task->details = '';
4048
                        $task->completed = null;
4049
                        $phase->tasks['switchtonextphase'] = $task;
4050
                    }
4051
 
4052
                } else {
4053
                    $action = new stdclass();
4054
                    $action->type = 'switchphase';
4055
                    $action->url  = $workshop->switchphase_url($phasecode);
4056
                    $phase->actions[] = $action;
4057
                }
4058
            }
4059
        }
4060
    }
4061
 
4062
    /**
4063
     * Returns example submissions to be assessed by the owner of the planner
4064
     *
4065
     * This is here to cache the DB query because the same list is needed later in view.php
4066
     *
4067
     * @see workshop::get_examples_for_reviewer() for the format of returned value
4068
     * @return array
4069
     */
4070
    public function get_examples() {
4071
        if (is_null($this->examples)) {
4072
            $this->examples = $this->workshop->get_examples_for_reviewer($this->userid);
4073
        }
4074
        return $this->examples;
4075
    }
4076
}
4077
 
4078
/**
4079
 * Common base class for submissions and example submissions rendering
4080
 *
4081
 * Subclasses of this class convert raw submission record from
4082
 * workshop_submissions table (as returned by {@see workshop::get_submission_by_id()}
4083
 * for example) into renderable objects.
4084
 */
4085
abstract class workshop_submission_base {
4086
 
4087
    /** @var bool is the submission anonymous (i.e. contains author information) */
4088
    protected $anonymous;
4089
 
4090
    /* @var array of columns from workshop_submissions that are assigned as properties */
4091
    protected $fields = array();
4092
 
4093
    /** @var workshop */
4094
    protected $workshop;
4095
 
4096
    /**
4097
     * Copies the properties of the given database record into properties of $this instance
4098
     *
4099
     * @param workshop $workshop
4100
     * @param stdClass $submission full record
4101
     * @param bool $showauthor show the author-related information
4102
     * @param array $options additional properties
4103
     */
4104
    public function __construct(workshop $workshop, stdClass $submission, $showauthor = false) {
4105
 
4106
        $this->workshop = $workshop;
4107
 
4108
        foreach ($this->fields as $field) {
4109
            if (!property_exists($submission, $field)) {
4110
                throw new coding_exception('Submission record must provide public property ' . $field);
4111
            }
4112
            if (!property_exists($this, $field)) {
4113
                throw new coding_exception('Renderable component must accept public property ' . $field);
4114
            }
4115
            $this->{$field} = $submission->{$field};
4116
        }
4117
 
4118
        if ($showauthor) {
4119
            $this->anonymous = false;
4120
        } else {
4121
            $this->anonymize();
4122
        }
4123
    }
4124
 
4125
    /**
4126
     * Unsets all author-related properties so that the renderer does not have access to them
4127
     *
4128
     * Usually this is called by the contructor but can be called explicitely, too.
4129
     */
4130
    public function anonymize() {
4131
        $authorfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
4132
        foreach ($authorfields as $field) {
4133
            $prefixedusernamefield = 'author' . $field;
4134
            unset($this->{$prefixedusernamefield});
4135
        }
4136
        $this->anonymous = true;
4137
    }
4138
 
4139
    /**
4140
     * Does the submission object contain author-related information?
4141
     *
4142
     * @return null|boolean
4143
     */
4144
    public function is_anonymous() {
4145
        return $this->anonymous;
4146
    }
4147
}
4148
 
4149
/**
4150
 * Renderable object containing a basic set of information needed to display the submission summary
4151
 *
4152
 * @see workshop_renderer::render_workshop_submission_summary
4153
 */
4154
class workshop_submission_summary extends workshop_submission_base implements renderable {
4155
 
4156
    /** @var int */
4157
    public $id;
4158
    /** @var string */
4159
    public $title;
4160
    /** @var string graded|notgraded */
4161
    public $status;
4162
    /** @var int */
4163
    public $timecreated;
4164
    /** @var int */
4165
    public $timemodified;
4166
    /** @var int */
4167
    public $authorid;
4168
    /** @var string */
4169
    public $authorfirstname;
4170
    /** @var string */
4171
    public $authorlastname;
4172
    /** @var string */
4173
    public $authorfirstnamephonetic;
4174
    /** @var string */
4175
    public $authorlastnamephonetic;
4176
    /** @var string */
4177
    public $authormiddlename;
4178
    /** @var string */
4179
    public $authoralternatename;
4180
    /** @var int */
4181
    public $authorpicture;
4182
    /** @var string */
4183
    public $authorimagealt;
4184
    /** @var string */
4185
    public $authoremail;
4186
    /** @var moodle_url to display submission */
4187
    public $url;
4188
 
4189
    /**
4190
     * @var array of columns from workshop_submissions that are assigned as properties
4191
     * of instances of this class
4192
     */
4193
    protected $fields = array(
4194
        'id', 'title', 'timecreated', 'timemodified',
4195
        'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
4196
        'authormiddlename', 'authoralternatename', 'authorpicture',
4197
        'authorimagealt', 'authoremail');
4198
}
4199
 
4200
/**
4201
 * Renderable object containing all the information needed to display the submission
4202
 *
4203
 * @see workshop_renderer::render_workshop_submission()
4204
 */
4205
class workshop_submission extends workshop_submission_summary implements renderable {
4206
 
4207
    /** @var string */
4208
    public $content;
4209
    /** @var int */
4210
    public $contentformat;
4211
    /** @var bool */
4212
    public $contenttrust;
4213
    /** @var array */
4214
    public $attachment;
4215
 
4216
    /**
4217
     * @var array of columns from workshop_submissions that are assigned as properties
4218
     * of instances of this class
4219
     */
4220
    protected $fields = array(
4221
        'id', 'title', 'timecreated', 'timemodified', 'content', 'contentformat', 'contenttrust',
4222
        'attachment', 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
4223
        'authormiddlename', 'authoralternatename', 'authorpicture', 'authorimagealt', 'authoremail');
4224
}
4225
 
4226
/**
4227
 * Renderable object containing a basic set of information needed to display the example submission summary
4228
 *
4229
 * @see workshop::prepare_example_summary()
4230
 * @see workshop_renderer::render_workshop_example_submission_summary()
4231
 */
4232
class workshop_example_submission_summary extends workshop_submission_base implements renderable {
4233
 
4234
    /** @var int */
4235
    public $id;
4236
    /** @var string */
4237
    public $title;
4238
    /** @var string graded|notgraded */
4239
    public $status;
4240
    /** @var stdClass */
4241
    public $gradeinfo;
4242
    /** @var moodle_url */
4243
    public $url;
4244
    /** @var moodle_url */
4245
    public $editurl;
4246
    /** @var string */
4247
    public $assesslabel;
4248
    /** @var moodle_url */
4249
    public $assessurl;
4250
    /** @var bool must be set explicitly by the caller */
4251
    public $editable = false;
4252
 
4253
    /**
4254
     * @var array of columns from workshop_submissions that are assigned as properties
4255
     * of instances of this class
4256
     */
4257
    protected $fields = array('id', 'title');
4258
 
4259
    /**
4260
     * Example submissions are always anonymous
4261
     *
4262
     * @return true
4263
     */
4264
    public function is_anonymous() {
4265
        return true;
4266
    }
4267
}
4268
 
4269
/**
4270
 * Renderable object containing all the information needed to display the example submission
4271
 *
4272
 * @see workshop_renderer::render_workshop_example_submission()
4273
 */
4274
class workshop_example_submission extends workshop_example_submission_summary implements renderable {
4275
 
4276
    /** @var string */
4277
    public $content;
4278
    /** @var int */
4279
    public $contentformat;
4280
    /** @var bool */
4281
    public $contenttrust;
4282
    /** @var array */
4283
    public $attachment;
4284
 
4285
    /**
4286
     * @var array of columns from workshop_submissions that are assigned as properties
4287
     * of instances of this class
4288
     */
4289
    protected $fields = array('id', 'title', 'content', 'contentformat', 'contenttrust', 'attachment');
4290
}
4291
 
4292
 
4293
/**
4294
 * Common base class for assessments rendering
4295
 *
4296
 * Subclasses of this class convert raw assessment record from
4297
 * workshop_assessments table (as returned by {@see workshop::get_assessment_by_id()}
4298
 * for example) into renderable objects.
4299
 */
4300
abstract class workshop_assessment_base {
4301
 
4302
    /** @var string the optional title of the assessment */
4303
    public $title = '';
4304
 
4305
    /** @var workshop_assessment_form $form as returned by {@link workshop_strategy::get_assessment_form()} */
4306
    public $form;
4307
 
4308
    /** @var moodle_url */
4309
    public $url;
4310
 
4311
    /** @var float|null the real received grade */
4312
    public $realgrade = null;
4313
 
4314
    /** @var float the real maximum grade */
4315
    public $maxgrade;
4316
 
4317
    /** @var stdClass|null reviewer user info */
4318
    public $reviewer = null;
4319
 
4320
    /** @var stdClass|null assessed submission's author user info */
4321
    public $author = null;
4322
 
4323
    /** @var array of actions */
4324
    public $actions = array();
4325
 
4326
    /* @var array of columns that are assigned as properties */
4327
    protected $fields = array();
4328
 
4329
    /** @var workshop */
4330
    public $workshop;
4331
 
4332
    /**
4333
     * Copies the properties of the given database record into properties of $this instance
4334
     *
4335
     * The $options keys are: showreviewer, showauthor
4336
     * @param workshop $workshop
4337
     * @param stdClass $assessment full record
4338
     * @param array $options additional properties
4339
     */
4340
    public function __construct(workshop $workshop, stdClass $record, array $options = array()) {
4341
 
4342
        $this->workshop = $workshop;
4343
        $this->validate_raw_record($record);
4344
 
4345
        foreach ($this->fields as $field) {
4346
            if (!property_exists($record, $field)) {
4347
                throw new coding_exception('Assessment record must provide public property ' . $field);
4348
            }
4349
            if (!property_exists($this, $field)) {
4350
                throw new coding_exception('Renderable component must accept public property ' . $field);
4351
            }
4352
            $this->{$field} = $record->{$field};
4353
        }
4354
 
4355
        if (!empty($options['showreviewer'])) {
4356
            $this->reviewer = user_picture::unalias($record, null, 'revieweridx', 'reviewer');
4357
        }
4358
 
4359
        if (!empty($options['showauthor'])) {
4360
            $this->author = user_picture::unalias($record, null, 'authorid', 'author');
4361
        }
4362
    }
4363
 
4364
    /**
4365
     * Adds a new action
4366
     *
4367
     * @param moodle_url $url action URL
4368
     * @param string $label action label
4369
     * @param string $method get|post
4370
     */
4371
    public function add_action(moodle_url $url, $label, $method = 'get') {
4372
 
4373
        $action = new stdClass();
4374
        $action->url = $url;
4375
        $action->label = $label;
4376
        $action->method = $method;
4377
 
4378
        $this->actions[] = $action;
4379
    }
4380
 
4381
    /**
4382
     * Makes sure that we can cook the renderable component from the passed raw database record
4383
     *
4384
     * @param stdClass $assessment full assessment record
4385
     * @throws coding_exception if the caller passed unexpected data
4386
     */
4387
    protected function validate_raw_record(stdClass $record) {
4388
        // nothing to do here
4389
    }
4390
}
4391
 
4392
 
4393
/**
4394
 * Represents a rendarable full assessment
4395
 */
4396
class workshop_assessment extends workshop_assessment_base implements renderable {
4397
 
4398
    /** @var int */
4399
    public $id;
4400
 
4401
    /** @var int */
4402
    public $submissionid;
4403
 
4404
    /** @var int */
4405
    public $weight;
4406
 
4407
    /** @var int */
4408
    public $timecreated;
4409
 
4410
    /** @var int */
4411
    public $timemodified;
4412
 
4413
    /** @var float */
4414
    public $grade;
4415
 
4416
    /** @var float */
4417
    public $gradinggrade;
4418
 
4419
    /** @var float */
4420
    public $gradinggradeover;
4421
 
4422
    /** @var string */
4423
    public $feedbackauthor;
4424
 
4425
    /** @var int */
4426
    public $feedbackauthorformat;
4427
 
4428
    /** @var int */
4429
    public $feedbackauthorattachment;
4430
 
4431
    /** @var array */
4432
    protected $fields = array('id', 'submissionid', 'weight', 'timecreated',
4433
        'timemodified', 'grade', 'gradinggrade', 'gradinggradeover', 'feedbackauthor',
4434
        'feedbackauthorformat', 'feedbackauthorattachment');
4435
 
4436
    /**
4437
     * Format the overall feedback text content
4438
     *
4439
     * False is returned if the overall feedback feature is disabled. Null is returned
4440
     * if the overall feedback content has not been found. Otherwise, string with
4441
     * formatted feedback text is returned.
4442
     *
4443
     * @return string|bool|null
4444
     */
4445
    public function get_overall_feedback_content() {
4446
 
4447
        if ($this->workshop->overallfeedbackmode == 0) {
4448
            return false;
4449
        }
4450
 
4451
        if (trim($this->feedbackauthor) === '') {
4452
            return null;
4453
        }
4454
 
4455
        $content = file_rewrite_pluginfile_urls($this->feedbackauthor, 'pluginfile.php', $this->workshop->context->id,
4456
            'mod_workshop', 'overallfeedback_content', $this->id);
4457
        $content = format_text($content, $this->feedbackauthorformat,
4458
            array('overflowdiv' => true, 'context' => $this->workshop->context));
4459
 
4460
        return $content;
4461
    }
4462
 
4463
    /**
4464
     * Prepares the list of overall feedback attachments
4465
     *
4466
     * Returns false if overall feedback attachments are not allowed. Otherwise returns
4467
     * list of attachments (may be empty).
4468
     *
4469
     * @return bool|array of stdClass
4470
     */
4471
    public function get_overall_feedback_attachments() {
4472
 
4473
        if ($this->workshop->overallfeedbackmode == 0) {
4474
            return false;
4475
        }
4476
 
4477
        if ($this->workshop->overallfeedbackfiles == 0) {
4478
            return false;
4479
        }
4480
 
4481
        if (empty($this->feedbackauthorattachment)) {
4482
            return array();
4483
        }
4484
 
4485
        $attachments = array();
4486
        $fs = get_file_storage();
4487
        $files = $fs->get_area_files($this->workshop->context->id, 'mod_workshop', 'overallfeedback_attachment', $this->id);
4488
        foreach ($files as $file) {
4489
            if ($file->is_directory()) {
4490
                continue;
4491
            }
4492
            $filepath = $file->get_filepath();
4493
            $filename = $file->get_filename();
4494
            $fileurl = moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop',
4495
                'overallfeedback_attachment', $this->id, $filepath, $filename, true);
4496
            $previewurl = new moodle_url(moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop',
4497
                'overallfeedback_attachment', $this->id, $filepath, $filename, false), array('preview' => 'bigthumb'));
4498
            $attachments[] = (object)array(
4499
                'filepath' => $filepath,
4500
                'filename' => $filename,
4501
                'fileurl' => $fileurl,
4502
                'previewurl' => $previewurl,
4503
                'mimetype' => $file->get_mimetype(),
4504
 
4505
            );
4506
        }
4507
 
4508
        return $attachments;
4509
    }
4510
}
4511
 
4512
 
4513
/**
4514
 * Represents a renderable training assessment of an example submission
4515
 */
4516
class workshop_example_assessment extends workshop_assessment implements renderable {
4517
 
4518
    /**
4519
     * @see parent::validate_raw_record()
4520
     */
4521
    protected function validate_raw_record(stdClass $record) {
4522
        if ($record->weight != 0) {
4523
            throw new coding_exception('Invalid weight of example submission assessment');
4524
        }
4525
        parent::validate_raw_record($record);
4526
    }
4527
}
4528
 
4529
 
4530
/**
4531
 * Represents a renderable reference assessment of an example submission
4532
 */
4533
class workshop_example_reference_assessment extends workshop_assessment implements renderable {
4534
 
4535
    /**
4536
     * @see parent::validate_raw_record()
4537
     */
4538
    protected function validate_raw_record(stdClass $record) {
4539
        if ($record->weight != 1) {
4540
            throw new coding_exception('Invalid weight of the reference example submission assessment');
4541
        }
4542
        parent::validate_raw_record($record);
4543
    }
4544
}
4545
 
4546
 
4547
/**
4548
 * Renderable message to be displayed to the user
4549
 *
4550
 * Message can contain an optional action link with a label that is supposed to be rendered
4551
 * as a button or a link.
4552
 *
4553
 * @see workshop::renderer::render_workshop_message()
4554
 */
4555
class workshop_message implements renderable {
4556
 
4557
    const TYPE_INFO     = 10;
4558
    const TYPE_OK       = 20;
4559
    const TYPE_ERROR    = 30;
4560
 
4561
    /** @var string */
4562
    protected $text = '';
4563
    /** @var int */
4564
    protected $type = self::TYPE_INFO;
4565
    /** @var moodle_url */
4566
    protected $actionurl = null;
4567
    /** @var string */
4568
    protected $actionlabel = '';
4569
 
4570
    /**
4571
     * @param string $text short text to be displayed
4572
     * @param string $type optional message type info|ok|error
4573
     */
4574
    public function __construct($text = null, $type = self::TYPE_INFO) {
4575
        $this->set_text($text);
4576
        $this->set_type($type);
4577
    }
4578
 
4579
    /**
4580
     * Sets the message text
4581
     *
4582
     * @param string $text short text to be displayed
4583
     */
4584
    public function set_text($text) {
4585
        $this->text = $text;
4586
    }
4587
 
4588
    /**
4589
     * Sets the message type
4590
     *
4591
     * @param int $type
4592
     */
4593
    public function set_type($type = self::TYPE_INFO) {
4594
        if (in_array($type, array(self::TYPE_OK, self::TYPE_ERROR, self::TYPE_INFO))) {
4595
            $this->type = $type;
4596
        } else {
4597
            throw new coding_exception('Unknown message type.');
4598
        }
4599
    }
4600
 
4601
    /**
4602
     * Sets the optional message action
4603
     *
4604
     * @param moodle_url $url to follow on action
4605
     * @param string $label action label
4606
     */
4607
    public function set_action(moodle_url $url, $label) {
4608
        $this->actionurl    = $url;
4609
        $this->actionlabel  = $label;
4610
    }
4611
 
4612
    /**
4613
     * Returns message text with HTML tags quoted
4614
     *
4615
     * @return string
4616
     */
4617
    public function get_message() {
4618
        return s($this->text);
4619
    }
4620
 
4621
    /**
4622
     * Returns message type
4623
     *
4624
     * @return int
4625
     */
4626
    public function get_type() {
4627
        return $this->type;
4628
    }
4629
 
4630
    /**
4631
     * Returns action URL
4632
     *
4633
     * @return moodle_url|null
4634
     */
4635
    public function get_action_url() {
4636
        return $this->actionurl;
4637
    }
4638
 
4639
    /**
4640
     * Returns action label
4641
     *
4642
     * @return string
4643
     */
4644
    public function get_action_label() {
4645
        return $this->actionlabel;
4646
    }
4647
}
4648
 
4649
 
4650
/**
4651
 * Renderable component containing all the data needed to display the grading report
4652
 */
4653
class workshop_grading_report implements renderable {
4654
 
4655
    /** @var stdClass returned by {@see workshop::prepare_grading_report_data()} */
4656
    protected $data;
4657
    /** @var stdClass rendering options */
4658
    protected $options;
4659
 
4660
    /**
4661
     * Grades in $data must be already rounded to the set number of decimals or must be null
4662
     * (in which later case, the [mod_workshop,nullgrade] string shall be displayed)
4663
     *
4664
     * @param stdClass $data prepared by {@link workshop::prepare_grading_report_data()}
4665
     * @param stdClass $options display options (showauthornames, showreviewernames, sortby, sorthow, showsubmissiongrade, showgradinggrade)
4666
     */
4667
    public function __construct(stdClass $data, stdClass $options) {
4668
        $this->data     = $data;
4669
        $this->options  = $options;
4670
    }
4671
 
4672
    /**
4673
     * @return stdClass grading report data
4674
     */
4675
    public function get_data() {
4676
        return $this->data;
4677
    }
4678
 
4679
    /**
4680
     * @return stdClass rendering options
4681
     */
4682
    public function get_options() {
4683
        return $this->options;
4684
    }
4685
 
4686
    /**
4687
     * Prepare the data to be exported to a external system via Web Services.
4688
     *
4689
     * This function applies extra capabilities checks.
4690
     * @return stdClass the data ready for external systems
4691
     */
4692
    public function export_data_for_external() {
4693
        $data = $this->get_data();
4694
        $options = $this->get_options();
4695
 
4696
        foreach ($data->grades as $reportdata) {
4697
            // If we are in submission phase ignore the following data.
4698
            if ($options->workshopphase == workshop::PHASE_SUBMISSION) {
4699
                unset($reportdata->submissiongrade);
4700
                unset($reportdata->gradinggrade);
4701
                unset($reportdata->submissiongradeover);
4702
                unset($reportdata->submissiongradeoverby);
4703
                unset($reportdata->submissionpublished);
4704
                unset($reportdata->reviewedby);
4705
                unset($reportdata->reviewerof);
4706
                continue;
4707
            }
4708
 
4709
            if (!$options->showsubmissiongrade) {
4710
                unset($reportdata->submissiongrade);
4711
                unset($reportdata->submissiongradeover);
4712
            }
4713
 
4714
            if (!$options->showgradinggrade and $tr == 0) {
4715
                unset($reportdata->gradinggrade);
4716
            }
4717
 
4718
            if (!$options->showreviewernames) {
4719
                foreach ($reportdata->reviewedby as $reviewedby) {
4720
                    $reviewedby->userid = 0;
4721
                }
4722
            }
4723
 
4724
            if (!$options->showauthornames) {
4725
                foreach ($reportdata->reviewerof as $reviewerof) {
4726
                    $reviewerof->userid = 0;
4727
                }
4728
            }
4729
        }
4730
 
4731
        return $data;
4732
    }
4733
}
4734
 
4735
 
4736
/**
4737
 * Base class for renderable feedback for author and feedback for reviewer
4738
 */
4739
abstract class workshop_feedback {
4740
 
4741
    /** @var stdClass the user info */
4742
    protected $provider = null;
4743
 
4744
    /** @var string the feedback text */
4745
    protected $content = null;
4746
 
4747
    /** @var int format of the feedback text */
4748
    protected $format = null;
4749
 
4750
    /**
4751
     * @return stdClass the user info
4752
     */
4753
    public function get_provider() {
4754
 
4755
        if (is_null($this->provider)) {
4756
            throw new coding_exception('Feedback provider not set');
4757
        }
4758
 
4759
        return $this->provider;
4760
    }
4761
 
4762
    /**
4763
     * @return string the feedback text
4764
     */
4765
    public function get_content() {
4766
 
4767
        if (is_null($this->content)) {
4768
            throw new coding_exception('Feedback content not set');
4769
        }
4770
 
4771
        return $this->content;
4772
    }
4773
 
4774
    /**
4775
     * @return int format of the feedback text
4776
     */
4777
    public function get_format() {
4778
 
4779
        if (is_null($this->format)) {
4780
            throw new coding_exception('Feedback text format not set');
4781
        }
4782
 
4783
        return $this->format;
4784
    }
4785
}
4786
 
4787
 
4788
/**
4789
 * Renderable feedback for the author of submission
4790
 */
4791
class workshop_feedback_author extends workshop_feedback implements renderable {
4792
 
4793
    /**
4794
     * Extracts feedback from the given submission record
4795
     *
4796
     * @param stdClass $submission record as returned by {@see self::get_submission_by_id()}
4797
     */
4798
    public function __construct(stdClass $submission) {
4799
 
4800
        $this->provider = user_picture::unalias($submission, null, 'gradeoverbyx', 'gradeoverby');
4801
        $this->content  = $submission->feedbackauthor;
4802
        $this->format   = $submission->feedbackauthorformat;
4803
    }
4804
}
4805
 
4806
 
4807
/**
4808
 * Renderable feedback for the reviewer
4809
 */
4810
class workshop_feedback_reviewer extends workshop_feedback implements renderable {
4811
 
4812
    /**
4813
     * Extracts feedback from the given assessment record
4814
     *
4815
     * @param stdClass $assessment record as returned by eg {@see self::get_assessment_by_id()}
4816
     */
4817
    public function __construct(stdClass $assessment) {
4818
 
4819
        $this->provider = user_picture::unalias($assessment, null, 'gradinggradeoverbyx', 'overby');
4820
        $this->content  = $assessment->feedbackreviewer;
4821
        $this->format   = $assessment->feedbackreviewerformat;
4822
    }
4823
}
4824
 
4825
 
4826
/**
4827
 * Holds the final grades for the activity as are stored in the gradebook
4828
 */
4829
class workshop_final_grades implements renderable {
4830
 
4831
    /** @var object the info from the gradebook about the grade for submission */
4832
    public $submissiongrade = null;
4833
 
4834
    /** @var object the infor from the gradebook about the grade for assessment */
4835
    public $assessmentgrade = null;
4836
}