Proyectos de Subversion Moodle

Rev

| 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
 * File containing the course class.
19
 *
20
 * @package    tool_uploadcourse
21
 * @copyright  2013 Frédéric Massart
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
use tool_uploadcourse\permissions;
26
 
27
defined('MOODLE_INTERNAL') || die();
28
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
29
require_once($CFG->dirroot . '/course/lib.php');
30
 
31
/**
32
 * Course class.
33
 *
34
 * @package    tool_uploadcourse
35
 * @copyright  2013 Frédéric Massart
36
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37
 */
38
class tool_uploadcourse_course {
39
 
40
    /** Outcome of the process: creating the course */
41
    const DO_CREATE = 1;
42
 
43
    /** Outcome of the process: updating the course */
44
    const DO_UPDATE = 2;
45
 
46
    /** Outcome of the process: deleting the course */
47
    const DO_DELETE = 3;
48
 
49
    /** @var array assignable roles. */
50
    protected $assignableroles = [];
51
 
52
    /** @var array Roles context levels. */
53
    protected $contextlevels = [];
54
 
55
    /** @var array final import data. */
56
    protected $data = array();
57
 
58
    /** @var array default values. */
59
    protected $defaults = array();
60
 
61
    /** @var array enrolment data. */
62
    protected $enrolmentdata;
63
 
64
    /** @var array errors. */
65
    protected $errors = array();
66
 
67
    /** @var int the ID of the course that had been processed. */
68
    protected $id;
69
 
70
    /** @var array containing options passed from the processor. */
71
    protected $importoptions = array();
72
 
73
    /** @var int import mode. Matches tool_uploadcourse_processor::MODE_* */
74
    protected $mode;
75
 
76
    /** @var array course import options. */
77
    protected $options = array();
78
 
79
    /** @var int constant value of self::DO_*, what to do with that course */
80
    protected $do;
81
 
82
    /** @var bool set to true once we have prepared the course */
83
    protected $prepared = false;
84
 
85
    /** @var bool set to true once we have started the process of the course */
86
    protected $processstarted = false;
87
 
88
    /** @var array course import data. */
89
    protected $rawdata = array();
90
 
91
    /** @var array restore directory. */
92
    protected $restoredata;
93
 
94
    /** @var string course shortname. */
95
    protected $shortname;
96
 
97
    /** @var array errors. */
98
    protected $statuses = array();
99
 
100
    /** @var int update mode. Matches tool_uploadcourse_processor::UPDATE_* */
101
    protected $updatemode;
102
 
103
    /** @var array fields allowed as course data. */
104
    static protected $validfields = array('fullname', 'shortname', 'idnumber', 'category', 'visible', 'startdate', 'enddate',
105
        'summary', 'format', 'theme', 'lang', 'newsitems', 'showgrades', 'showreports', 'legacyfiles', 'maxbytes',
106
        'groupmode', 'groupmodeforce', 'enablecompletion', 'downloadcontent', 'showactivitydates');
107
 
108
    /** @var array fields required on course creation. */
109
    static protected $mandatoryfields = array('fullname', 'category');
110
 
111
    /** @var array fields which are considered as options. */
112
    static protected $optionfields = array('delete' => false, 'rename' => null, 'backupfile' => null,
113
        'templatecourse' => null, 'reset' => false);
114
 
115
    /** @var array options determining what can or cannot be done at an import level. */
116
    static protected $importoptionsdefaults = array('canrename' => false, 'candelete' => false, 'canreset' => false,
117
        'reset' => false, 'restoredir' => null, 'shortnametemplate' => null);
118
 
119
    /**
120
     * Constructor
121
     *
122
     * @param int $mode import mode, constant matching tool_uploadcourse_processor::MODE_*
123
     * @param int $updatemode update mode, constant matching tool_uploadcourse_processor::UPDATE_*
124
     * @param array $rawdata raw course data.
125
     * @param array $defaults default course data.
126
     * @param array $importoptions import options.
127
     */
128
    public function __construct($mode, $updatemode, $rawdata, $defaults = array(), $importoptions = array()) {
129
 
130
        if ($mode !== tool_uploadcourse_processor::MODE_CREATE_NEW &&
131
                $mode !== tool_uploadcourse_processor::MODE_CREATE_ALL &&
132
                $mode !== tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE &&
133
                $mode !== tool_uploadcourse_processor::MODE_UPDATE_ONLY) {
134
            throw new coding_exception('Incorrect mode.');
135
        } else if ($updatemode !== tool_uploadcourse_processor::UPDATE_NOTHING &&
136
                $updatemode !== tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY &&
137
                $updatemode !== tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_OR_DEFAUTLS &&
138
                $updatemode !== tool_uploadcourse_processor::UPDATE_MISSING_WITH_DATA_OR_DEFAUTLS) {
139
            throw new coding_exception('Incorrect update mode.');
140
        }
141
 
142
        $this->mode = $mode;
143
        $this->updatemode = $updatemode;
144
 
145
        if (isset($rawdata['shortname'])) {
146
            $this->shortname = $rawdata['shortname'];
147
        }
148
        $this->rawdata = $rawdata;
149
        $this->defaults = $defaults;
150
 
151
        // Extract course options.
152
        foreach (self::$optionfields as $option => $default) {
153
            $this->options[$option] = isset($rawdata[$option]) ? $rawdata[$option] : $default;
154
        }
155
 
156
        // Import options.
157
        foreach (self::$importoptionsdefaults as $option => $default) {
158
            $this->importoptions[$option] = isset($importoptions[$option]) ? $importoptions[$option] : $default;
159
        }
160
    }
161
 
162
    /**
163
     * Does the mode allow for course creation?
164
     *
165
     * @return bool
166
     */
167
    public function can_create() {
168
        return in_array($this->mode, array(tool_uploadcourse_processor::MODE_CREATE_ALL,
169
            tool_uploadcourse_processor::MODE_CREATE_NEW,
170
            tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE)
171
        );
172
    }
173
 
174
    /**
175
     * Does the mode allow for course deletion?
176
     *
177
     * @return bool
178
     */
179
    public function can_delete() {
180
        return $this->importoptions['candelete'];
181
    }
182
 
183
    /**
184
     * Does the mode only allow for course creation?
185
     *
186
     * @return bool
187
     */
188
    public function can_only_create() {
189
        return in_array($this->mode, array(tool_uploadcourse_processor::MODE_CREATE_ALL,
190
            tool_uploadcourse_processor::MODE_CREATE_NEW));
191
    }
192
 
193
    /**
194
     * Does the mode allow for course rename?
195
     *
196
     * @return bool
197
     */
198
    public function can_rename() {
199
        return $this->importoptions['canrename'];
200
    }
201
 
202
    /**
203
     * Does the mode allow for course reset?
204
     *
205
     * @return bool
206
     */
207
    public function can_reset() {
208
        return $this->importoptions['canreset'];
209
    }
210
 
211
    /**
212
     * Does the mode allow for course update?
213
     *
214
     * @return bool
215
     */
216
    public function can_update() {
217
        return in_array($this->mode,
218
                array(
219
                    tool_uploadcourse_processor::MODE_UPDATE_ONLY,
220
                    tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE)
221
                ) && $this->updatemode != tool_uploadcourse_processor::UPDATE_NOTHING;
222
    }
223
 
224
    /**
225
     * Can we use default values?
226
     *
227
     * @return bool
228
     */
229
    public function can_use_defaults() {
230
        return in_array($this->updatemode, array(tool_uploadcourse_processor::UPDATE_MISSING_WITH_DATA_OR_DEFAUTLS,
231
            tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_OR_DEFAUTLS));
232
    }
233
 
234
    /**
235
     * Delete the current course.
236
     *
237
     * @return bool
238
     */
239
    protected function delete() {
240
        global $DB;
241
        $this->id = $DB->get_field_select('course', 'id', 'shortname = :shortname',
242
            array('shortname' => $this->shortname), MUST_EXIST);
243
        return delete_course($this->id, false);
244
    }
245
 
246
    /**
247
     * Log an error
248
     *
249
     * @param string $code error code.
250
     * @param string $message error message.
251
     * @return void
252
     */
253
    protected function error($code, string $message) {
254
        if (array_key_exists($code, $this->errors)) {
255
            throw new coding_exception('Error code already defined');
256
        }
257
        $this->errors[$code] = $message;
258
    }
259
 
260
    /**
261
     * Return whether the course exists or not.
262
     *
263
     * @param string $shortname the shortname to use to check if the course exists. Falls back on $this->shortname if empty.
264
     * @return bool
265
     */
266
    protected function exists($shortname = null) {
267
        global $DB;
268
        if (is_null($shortname)) {
269
            $shortname = $this->shortname;
270
        }
271
        if (!empty($shortname) || is_numeric($shortname)) {
272
            return $DB->record_exists('course', array('shortname' => $shortname));
273
        }
274
        return false;
275
    }
276
 
277
    /**
278
     * Return the data that will be used upon saving.
279
     *
280
     * @return null|array
281
     */
282
    public function get_data() {
283
        return $this->data;
284
    }
285
 
286
    /**
287
     * Return the errors found during preparation.
288
     *
289
     * @return array
290
     */
291
    public function get_errors() {
292
        return $this->errors;
293
    }
294
 
295
    /**
296
     * Return array of valid fields for default values
297
     *
298
     * @return array
299
     */
300
    protected function get_valid_fields() {
301
        return array_merge(self::$validfields, \tool_uploadcourse_helper::get_custom_course_field_names());
302
    }
303
 
304
    /**
305
     * Assemble the course data based on defaults.
306
     *
307
     * This returns the final data to be passed to create_course().
308
     *
309
     * @param array $data current data.
310
     * @return array
311
     */
312
    protected function get_final_create_data($data) {
313
        foreach ($this->get_valid_fields() as $field) {
314
            if (!isset($data[$field]) && isset($this->defaults[$field])) {
315
                $data[$field] = $this->defaults[$field];
316
            }
317
        }
318
        $data['shortname'] = $this->shortname;
319
        return $data;
320
    }
321
 
322
    /**
323
     * Assemble the course data based on defaults.
324
     *
325
     * This returns the final data to be passed to update_course().
326
     *
327
     * @param array $data current data.
328
     * @param bool $usedefaults are defaults allowed?
329
     * @param bool $missingonly ignore fields which are already set.
330
     * @return array
331
     */
332
    protected function get_final_update_data($data, $usedefaults = false, $missingonly = false) {
333
        global $DB;
334
        $newdata = array();
335
        $existingdata = $DB->get_record('course', array('shortname' => $this->shortname));
336
        foreach ($this->get_valid_fields() as $field) {
337
            if ($missingonly) {
338
                if (isset($existingdata->$field) and $existingdata->$field !== '') {
339
                    continue;
340
                }
341
            }
342
            if (isset($data[$field])) {
343
                $newdata[$field] = $data[$field];
344
            } else if ($usedefaults && isset($this->defaults[$field])) {
345
                $newdata[$field] = $this->defaults[$field];
346
            }
347
        }
348
        $newdata['id'] =  $existingdata->id;
349
        return $newdata;
350
    }
351
 
352
    /**
353
     * Return the ID of the processed course.
354
     *
355
     * @return int|null
356
     */
357
    public function get_id() {
358
        if (!$this->processstarted) {
359
            throw new coding_exception('The course has not been processed yet!');
360
        }
361
        return $this->id;
362
    }
363
 
364
    /**
365
     * Get the directory of the object to restore.
366
     *
367
     * @return string|false|null subdirectory in $CFG->backuptempdir/..., false when an error occured
368
     *                           and null when there is simply nothing.
369
     */
370
    protected function get_restore_content_dir() {
371
        $backupfile = null;
372
        $shortname = null;
373
 
374
        if (!empty($this->options['backupfile'])) {
375
            $backupfile = $this->options['backupfile'];
376
        } else if (!empty($this->options['templatecourse']) || is_numeric($this->options['templatecourse'])) {
377
            $shortname = $this->options['templatecourse'];
378
        }
379
 
380
        $errors = array();
381
        $dir = tool_uploadcourse_helper::get_restore_content_dir($backupfile, $shortname, $errors);
382
        if (!empty($errors)) {
383
            foreach ($errors as $key => $message) {
384
                $this->error($key, $message);
385
            }
386
            return false;
387
        } else if ($dir === false) {
388
            // We want to return null when nothing was wrong, but nothing was found.
389
            $dir = null;
390
        }
391
 
392
        if (empty($dir) && !empty($this->importoptions['restoredir'])) {
393
            $dir = $this->importoptions['restoredir'];
394
        }
395
 
396
        return $dir;
397
    }
398
 
399
    /**
400
     * Return the errors found during preparation.
401
     *
402
     * @return array
403
     */
404
    public function get_statuses() {
405
        return $this->statuses;
406
    }
407
 
408
    /**
409
     * Return whether there were errors with this course.
410
     *
411
     * @return boolean
412
     */
413
    public function has_errors() {
414
        return !empty($this->errors);
415
    }
416
 
417
    /**
418
     * Validates and prepares the data.
419
     *
420
     * @return bool false is any error occured.
421
     */
422
    public function prepare() {
423
        global $DB, $SITE, $CFG;
424
 
425
        $this->prepared = true;
426
 
427
        // Validate the shortname.
428
        if (!empty($this->shortname) || is_numeric($this->shortname)) {
429
            if ($this->shortname !== clean_param($this->shortname, PARAM_TEXT)) {
430
                $this->error('invalidshortname', new lang_string('invalidshortname', 'tool_uploadcourse'));
431
                return false;
432
            }
433
 
434
            // Ensure we don't overflow the maximum length of the shortname field.
435
            if (core_text::strlen($this->shortname) > 255) {
436
                $this->error('invalidshortnametoolong', new lang_string('invalidshortnametoolong', 'tool_uploadcourse', 255));
437
                return false;
438
            }
439
        }
440
 
441
        $exists = $this->exists();
442
 
443
        // Do we want to delete the course?
444
        if ($this->options['delete']) {
445
            if (!$exists) {
446
                $this->error('cannotdeletecoursenotexist', new lang_string('cannotdeletecoursenotexist', 'tool_uploadcourse'));
447
                return false;
448
            } else if (!$this->can_delete()) {
449
                $this->error('coursedeletionnotallowed', new lang_string('coursedeletionnotallowed', 'tool_uploadcourse'));
450
                return false;
451
            }
452
 
453
            if ($error = permissions::check_permission_to_delete($this->shortname)) {
454
                $this->error('coursedeletionpermission', $error);
455
                return false;
456
            }
457
 
458
            $this->do = self::DO_DELETE;
459
            return true;
460
        }
461
 
462
        // Can we create/update the course under those conditions?
463
        if ($exists) {
464
            if ($this->mode === tool_uploadcourse_processor::MODE_CREATE_NEW) {
465
                $this->error('courseexistsanduploadnotallowed',
466
                    new lang_string('courseexistsanduploadnotallowed', 'tool_uploadcourse'));
467
                return false;
468
            } else if ($this->can_update()) {
469
                // We can never allow for any front page changes!
470
                if ($this->shortname == $SITE->shortname) {
471
                    $this->error('cannotupdatefrontpage', new lang_string('cannotupdatefrontpage', 'tool_uploadcourse'));
472
                    return false;
473
                }
474
            }
475
        } else {
476
            if (!$this->can_create()) {
477
                $this->error('coursedoesnotexistandcreatenotallowed',
478
                    new lang_string('coursedoesnotexistandcreatenotallowed', 'tool_uploadcourse'));
479
                return false;
480
            }
481
        }
482
 
483
        // Basic data.
484
        $coursedata = array();
485
        foreach ($this->rawdata as $field => $value) {
486
            if (!in_array($field, self::$validfields)) {
487
                continue;
488
            } else if ($field == 'shortname') {
489
                // Let's leave it apart from now, use $this->shortname only.
490
                continue;
491
            }
492
            $coursedata[$field] = $value;
493
        }
494
 
495
        $mode = $this->mode;
496
        $updatemode = $this->updatemode;
497
        $usedefaults = $this->can_use_defaults();
498
 
499
        // Resolve the category, and fail if not found.
500
        $errors = array();
501
        $catid = tool_uploadcourse_helper::resolve_category($this->rawdata, $errors);
502
        if (empty($errors)) {
503
            $coursedata['category'] = $catid;
504
        } else {
505
            foreach ($errors as $key => $message) {
506
                $this->error($key, $message);
507
            }
508
            return false;
509
        }
510
 
511
        // Ensure we don't overflow the maximum length of the fullname field.
512
        if (!empty($coursedata['fullname']) && core_text::strlen($coursedata['fullname']) > 254) {
513
            $this->error('invalidfullnametoolong', new lang_string('invalidfullnametoolong', 'tool_uploadcourse', 254));
514
            return false;
515
        }
516
 
517
        // If the course does not exist, or will be forced created.
518
        if (!$exists || $mode === tool_uploadcourse_processor::MODE_CREATE_ALL) {
519
 
520
            // Mandatory fields upon creation.
521
            $errors = array();
522
            foreach (self::$mandatoryfields as $field) {
523
                if ((!isset($coursedata[$field]) || $coursedata[$field] === '') &&
524
                        (!isset($this->defaults[$field]) || $this->defaults[$field] === '')) {
525
                    $errors[] = $field;
526
                }
527
            }
528
            if (!empty($errors)) {
529
                $this->error('missingmandatoryfields', new lang_string('missingmandatoryfields', 'tool_uploadcourse',
530
                    implode(', ', $errors)));
531
                return false;
532
            }
533
        }
534
 
535
        // Should the course be renamed?
536
        if (!empty($this->options['rename']) || is_numeric($this->options['rename'])) {
537
            if (!$this->can_update()) {
538
                $this->error('canonlyrenameinupdatemode', new lang_string('canonlyrenameinupdatemode', 'tool_uploadcourse'));
539
                return false;
540
            } else if (!$exists) {
541
                $this->error('cannotrenamecoursenotexist', new lang_string('cannotrenamecoursenotexist', 'tool_uploadcourse'));
542
                return false;
543
            } else if (!$this->can_rename()) {
544
                $this->error('courserenamingnotallowed', new lang_string('courserenamingnotallowed', 'tool_uploadcourse'));
545
                return false;
546
            } else if ($this->options['rename'] !== clean_param($this->options['rename'], PARAM_TEXT)) {
547
                $this->error('invalidshortname', new lang_string('invalidshortname', 'tool_uploadcourse'));
548
                return false;
549
            } else if ($this->exists($this->options['rename'])) {
550
                $this->error('cannotrenameshortnamealreadyinuse',
551
                    new lang_string('cannotrenameshortnamealreadyinuse', 'tool_uploadcourse'));
552
                return false;
553
            } else if (isset($coursedata['idnumber']) &&
554
                    $DB->count_records_select('course', 'idnumber = :idn AND shortname != :sn',
555
                    array('idn' => $coursedata['idnumber'], 'sn' => $this->shortname)) > 0) {
556
                $this->error('cannotrenameidnumberconflict', new lang_string('cannotrenameidnumberconflict', 'tool_uploadcourse'));
557
                return false;
558
            }
559
            $coursedata['shortname'] = $this->options['rename'];
560
            $this->status('courserenamed', new lang_string('courserenamed', 'tool_uploadcourse',
561
                array('from' => $this->shortname, 'to' => $coursedata['shortname'])));
562
        }
563
 
564
        // Should we generate a shortname?
565
        if (empty($this->shortname) && !is_numeric($this->shortname)) {
566
            if (empty($this->importoptions['shortnametemplate'])) {
567
                $this->error('missingshortnamenotemplate', new lang_string('missingshortnamenotemplate', 'tool_uploadcourse'));
568
                return false;
569
            } else if (!$this->can_only_create()) {
570
                $this->error('cannotgenerateshortnameupdatemode',
571
                    new lang_string('cannotgenerateshortnameupdatemode', 'tool_uploadcourse'));
572
                return false;
573
            } else {
574
                $newshortname = tool_uploadcourse_helper::generate_shortname($coursedata,
575
                    $this->importoptions['shortnametemplate']);
576
                if (is_null($newshortname)) {
577
                    $this->error('generatedshortnameinvalid', new lang_string('generatedshortnameinvalid', 'tool_uploadcourse'));
578
                    return false;
579
                } else if ($this->exists($newshortname)) {
580
                    if ($mode === tool_uploadcourse_processor::MODE_CREATE_NEW) {
581
                        $this->error('generatedshortnamealreadyinuse',
582
                            new lang_string('generatedshortnamealreadyinuse', 'tool_uploadcourse'));
583
                        return false;
584
                    }
585
                    $exists = true;
586
                }
587
                $this->status('courseshortnamegenerated', new lang_string('courseshortnamegenerated', 'tool_uploadcourse',
588
                    $newshortname));
589
                $this->shortname = $newshortname;
590
            }
591
        }
592
 
593
        // If exists, but we only want to create courses, increment the shortname.
594
        if ($exists && $mode === tool_uploadcourse_processor::MODE_CREATE_ALL) {
595
            $original = $this->shortname;
596
            $this->shortname = tool_uploadcourse_helper::increment_shortname($this->shortname);
597
            $exists = false;
598
            if ($this->shortname != $original) {
599
                $this->status('courseshortnameincremented', new lang_string('courseshortnameincremented', 'tool_uploadcourse',
600
                    array('from' => $original, 'to' => $this->shortname)));
601
                if (isset($coursedata['idnumber'])) {
602
                    $originalidn = $coursedata['idnumber'];
603
                    $coursedata['idnumber'] = tool_uploadcourse_helper::increment_idnumber($coursedata['idnumber']);
604
                    if ($originalidn != $coursedata['idnumber']) {
605
                        $this->status('courseidnumberincremented', new lang_string('courseidnumberincremented', 'tool_uploadcourse',
606
                            array('from' => $originalidn, 'to' => $coursedata['idnumber'])));
607
                    }
608
                }
609
            }
610
        }
611
 
612
        // If the course does not exist, ensure that the ID number is not taken.
613
        if (!$exists && isset($coursedata['idnumber'])) {
614
            if ($DB->count_records_select('course', 'idnumber = :idn', array('idn' => $coursedata['idnumber'])) > 0) {
615
                $this->error('idnumberalreadyinuse', new lang_string('idnumberalreadyinuse', 'tool_uploadcourse'));
616
                return false;
617
            }
618
        }
619
 
620
        // Course start date.
621
        if (!empty($coursedata['startdate'])) {
622
            $coursedata['startdate'] = strtotime($coursedata['startdate']);
623
        }
624
 
625
        // Course end date.
626
        if (!empty($coursedata['enddate'])) {
627
            $coursedata['enddate'] = strtotime($coursedata['enddate']);
628
        }
629
 
630
        // If lang is specified, check the user is allowed to set that field.
631
        if (!empty($coursedata['lang'])) {
632
            if ($exists) {
633
                $courseid = $DB->get_field('course', 'id', ['shortname' => $this->shortname]);
634
                if (!has_capability('moodle/course:setforcedlanguage', context_course::instance($courseid))) {
635
                    $this->error('cannotforcelang', new lang_string('cannotforcelang', 'tool_uploadcourse'));
636
                    return false;
637
                }
638
            } else {
639
                $catcontext = context_coursecat::instance($coursedata['category']);
640
                if (!guess_if_creator_will_have_course_capability('moodle/course:setforcedlanguage', $catcontext)) {
641
                    $this->error('cannotforcelang', new lang_string('cannotforcelang', 'tool_uploadcourse'));
642
                    return false;
643
                }
644
            }
645
        }
646
 
647
        // Ultimate check mode vs. existence.
648
        switch ($mode) {
649
            case tool_uploadcourse_processor::MODE_CREATE_NEW:
650
            case tool_uploadcourse_processor::MODE_CREATE_ALL:
651
                if ($exists) {
652
                    $this->error('courseexistsanduploadnotallowed',
653
                        new lang_string('courseexistsanduploadnotallowed', 'tool_uploadcourse'));
654
                    return false;
655
                }
656
                break;
657
            case tool_uploadcourse_processor::MODE_UPDATE_ONLY:
658
                if (!$exists) {
659
                    $this->error('coursedoesnotexistandcreatenotallowed',
660
                        new lang_string('coursedoesnotexistandcreatenotallowed', 'tool_uploadcourse'));
661
                    return false;
662
                }
663
                // No break!
664
            case tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE:
665
                if ($exists) {
666
                    if ($updatemode === tool_uploadcourse_processor::UPDATE_NOTHING) {
667
                        $this->error('updatemodedoessettonothing',
668
                            new lang_string('updatemodedoessettonothing', 'tool_uploadcourse'));
669
                        return false;
670
                    }
671
                }
672
                break;
673
            default:
674
                // O_o Huh?! This should really never happen here!
675
                $this->error('unknownimportmode', new lang_string('unknownimportmode', 'tool_uploadcourse'));
676
                return false;
677
        }
678
 
679
        // Get final data.
680
        if ($exists) {
681
            $missingonly = ($updatemode === tool_uploadcourse_processor::UPDATE_MISSING_WITH_DATA_OR_DEFAUTLS);
682
            $coursedata = $this->get_final_update_data($coursedata, $usedefaults, $missingonly);
683
 
684
            // Make sure we are not trying to mess with the front page, though we should never get here!
685
            if ($coursedata['id'] == $SITE->id) {
686
                $this->error('cannotupdatefrontpage', new lang_string('cannotupdatefrontpage', 'tool_uploadcourse'));
687
                return false;
688
            }
689
 
690
            if ($error = permissions::check_permission_to_update($coursedata)) {
691
                $this->error('cannotupdatepermission', $error);
692
                return false;
693
            }
694
 
695
            $this->do = self::DO_UPDATE;
696
        } else {
697
            $coursedata = $this->get_final_create_data($coursedata);
698
 
699
            if ($error = permissions::check_permission_to_create($coursedata)) {
700
                $this->error('courseuploadnotallowed', $error);
701
                return false;
702
            }
703
 
704
            $this->do = self::DO_CREATE;
705
        }
706
 
707
        // Validate course start and end dates.
708
        if ($exists) {
709
            // We also check existing start and end dates if we are updating an existing course.
710
            $existingdata = $DB->get_record('course', array('shortname' => $this->shortname));
711
            if (empty($coursedata['startdate'])) {
712
                $coursedata['startdate'] = $existingdata->startdate;
713
            }
714
            if (empty($coursedata['enddate'])) {
715
                $coursedata['enddate'] = $existingdata->enddate;
716
            }
717
        }
718
        if ($errorcode = course_validate_dates($coursedata)) {
719
            $this->error($errorcode, new lang_string($errorcode, 'error'));
720
            return false;
721
        }
722
 
723
        // Add role renaming.
724
        $errors = array();
725
        $rolenames = tool_uploadcourse_helper::get_role_names($this->rawdata, $errors);
726
        if (!empty($errors)) {
727
            foreach ($errors as $key => $message) {
728
                $this->error($key, $message);
729
            }
730
            return false;
731
        }
732
        foreach ($rolenames as $rolekey => $rolename) {
733
            $coursedata[$rolekey] = $rolename;
734
        }
735
 
736
        // Custom fields. If the course already exists and mode isn't set to force creation, we can use its context.
737
        if ($exists && $mode !== tool_uploadcourse_processor::MODE_CREATE_ALL) {
738
            $context = context_course::instance($coursedata['id']);
739
        } else {
740
            // The category ID is taken from the defaults if it exists, otherwise from course data.
741
            $context = context_coursecat::instance($this->defaults['category'] ?? $coursedata['category']);
742
        }
743
        $customfielddata = tool_uploadcourse_helper::get_custom_course_field_data($this->rawdata, $this->defaults, $context,
744
            $errors);
745
        if (!empty($errors)) {
746
            foreach ($errors as $key => $message) {
747
                $this->error($key, $message);
748
            }
749
 
750
            return false;
751
        }
752
 
753
        foreach ($customfielddata as $name => $value) {
754
            $coursedata[$name] = $value;
755
        }
756
 
757
        // Some validation.
758
        if (!empty($coursedata['format']) && !in_array($coursedata['format'], tool_uploadcourse_helper::get_course_formats())) {
759
            $this->error('invalidcourseformat', new lang_string('invalidcourseformat', 'tool_uploadcourse'));
760
            return false;
761
        }
762
 
763
        // Add data for course format options.
764
        if (isset($coursedata['format']) || $exists) {
765
            if (isset($coursedata['format'])) {
766
                $courseformat = course_get_format((object)['format' => $coursedata['format']]);
767
            } else {
768
                $courseformat = course_get_format($existingdata);
769
            }
770
            $coursedata += $courseformat->validate_course_format_options($this->rawdata);
771
        }
772
 
773
        // Special case, 'numsections' is not a course format option any more but still should apply from the template course,
774
        // if any, and otherwise from defaults.
775
        if (!$exists || !array_key_exists('numsections', $coursedata)) {
776
            if (isset($this->rawdata['numsections']) && is_numeric($this->rawdata['numsections'])) {
777
                $coursedata['numsections'] = (int)$this->rawdata['numsections'];
778
            } else if (isset($this->options['templatecourse'])) {
779
                $numsections = tool_uploadcourse_helper::get_coursesection_count($this->options['templatecourse']);
780
                if ($numsections != 0) {
781
                    $coursedata['numsections'] = $numsections;
782
                } else {
783
                    $coursedata['numsections'] = get_config('moodlecourse', 'numsections');
784
                }
785
            } else {
786
                $coursedata['numsections'] = get_config('moodlecourse', 'numsections');
787
            }
788
        }
789
 
790
        // Visibility can only be 0 or 1.
791
        if (!empty($coursedata['visible']) AND !($coursedata['visible'] == 0 OR $coursedata['visible'] == 1)) {
792
            $this->error('invalidvisibilitymode', new lang_string('invalidvisibilitymode', 'tool_uploadcourse'));
793
            return false;
794
        }
795
 
796
        // Ensure that user is allowed to configure course content download and the field contains a valid value.
797
        if (isset($coursedata['downloadcontent'])) {
798
            if (!$CFG->downloadcoursecontentallowed ||
799
                    !has_capability('moodle/course:configuredownloadcontent', $context)) {
800
 
801
                $this->error('downloadcontentnotallowed', new lang_string('downloadcontentnotallowed', 'tool_uploadcourse'));
802
                return false;
803
            }
804
 
805
            $downloadcontentvalues = [
806
                DOWNLOAD_COURSE_CONTENT_DISABLED,
807
                DOWNLOAD_COURSE_CONTENT_ENABLED,
808
                DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT,
809
            ];
810
            if (!in_array($coursedata['downloadcontent'], $downloadcontentvalues)) {
811
                $this->error('invaliddownloadcontent', new lang_string('invaliddownloadcontent', 'tool_uploadcourse'));
812
                return false;
813
            }
814
        }
815
 
816
        // Saving data.
817
        $this->data = $coursedata;
818
 
819
        // Get enrolment data. Where the course already exists, we can also perform validation.
820
        // Some data is impossible to validate without the existing course, we will do it again during actual upload.
821
        $this->enrolmentdata = tool_uploadcourse_helper::get_enrolment_data($this->rawdata);
822
        $courseid = $coursedata['id'] ?? 0;
823
        $errors = $this->validate_enrolment_data($courseid, $this->enrolmentdata);
824
 
825
        if (!empty($errors)) {
826
            foreach ($errors as $key => $message) {
827
                $this->error($key, $message);
828
            }
829
 
830
            return false;
831
        }
832
 
833
        if (isset($this->rawdata['tags']) && strval($this->rawdata['tags']) !== '') {
834
            $this->data['tags'] = preg_split('/\s*,\s*/', trim($this->rawdata['tags']), -1, PREG_SPLIT_NO_EMPTY);
835
        }
836
 
837
        // Restore data.
838
        // TODO Speed up things by not really extracting the backup just yet, but checking that
839
        // the backup file or shortname passed are valid. Extraction should happen in proceed().
840
        $this->restoredata = $this->get_restore_content_dir();
841
        if ($this->restoredata === false) {
842
            return false;
843
        }
844
 
845
        if ($this->restoredata && ($error = permissions::check_permission_to_restore($this->do, $this->data))) {
846
            $this->error('courserestorepermission', $error);
847
            return false;
848
        }
849
 
850
        // We can only reset courses when allowed and we are updating the course.
851
        if ($this->importoptions['reset'] || $this->options['reset']) {
852
            if ($this->do !== self::DO_UPDATE) {
853
                $this->error('canonlyresetcourseinupdatemode',
854
                    new lang_string('canonlyresetcourseinupdatemode', 'tool_uploadcourse'));
855
                return false;
856
            } else if (!$this->can_reset()) {
857
                $this->error('courseresetnotallowed', new lang_string('courseresetnotallowed', 'tool_uploadcourse'));
858
                return false;
859
            }
860
 
861
            if ($error = permissions::check_permission_to_reset($this->data)) {
862
                $this->error('courseresetpermission', $error);
863
                return false;
864
            }
865
        }
866
 
867
        return true;
868
    }
869
 
870
    /**
871
     * Proceed with the import of the course.
872
     *
873
     * @return void
874
     */
875
    public function proceed() {
876
        global $CFG, $USER;
877
 
878
        if (!$this->prepared) {
879
            throw new coding_exception('The course has not been prepared.');
880
        } else if ($this->has_errors()) {
881
            throw new moodle_exception('Cannot proceed, errors were detected.');
882
        } else if ($this->processstarted) {
883
            throw new coding_exception('The process has already been started.');
884
        }
885
        $this->processstarted = true;
886
 
887
        if ($this->do === self::DO_DELETE) {
888
            if ($this->delete()) {
889
                $this->status('coursedeleted', new lang_string('coursedeleted', 'tool_uploadcourse'));
890
            } else {
891
                $this->error('errorwhiledeletingcourse', new lang_string('errorwhiledeletingcourse', 'tool_uploadcourse'));
892
            }
893
            return true;
894
        } else if ($this->do === self::DO_CREATE) {
895
            $course = create_course((object) $this->data);
896
            $this->id = $course->id;
897
            $this->status('coursecreated', new lang_string('coursecreated', 'tool_uploadcourse'));
898
        } else if ($this->do === self::DO_UPDATE) {
899
            $course = (object) $this->data;
900
            update_course($course);
901
            $this->id = $course->id;
902
            $this->status('courseupdated', new lang_string('courseupdated', 'tool_uploadcourse'));
903
        } else {
904
            // Strangely the outcome has not been defined, or is unknown!
905
            throw new coding_exception('Unknown outcome!');
906
        }
907
 
908
        // Restore a course.
909
        if (!empty($this->restoredata)) {
910
            $rc = new restore_controller($this->restoredata, $course->id, backup::INTERACTIVE_NO,
911
                backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
912
 
913
            // Check if the format conversion must happen first.
914
            if ($rc->get_status() == backup::STATUS_REQUIRE_CONV) {
915
                $rc->convert();
916
            }
917
            if ($rc->execute_precheck()) {
918
                $rc->execute_plan();
919
                $this->status('courserestored', new lang_string('courserestored', 'tool_uploadcourse'));
920
            } else {
921
                $this->error('errorwhilerestoringcourse', new lang_string('errorwhilerestoringcourse', 'tool_uploadcourse'));
922
            }
923
            $rc->destroy();
924
        }
925
 
926
        // Proceed with enrolment data.
927
        $this->process_enrolment_data($course);
928
 
929
        // Reset the course.
930
        if ($this->importoptions['reset'] || $this->options['reset']) {
931
            if ($this->do === self::DO_UPDATE && $this->can_reset()) {
932
                $this->reset($course);
933
                $this->status('coursereset', new lang_string('coursereset', 'tool_uploadcourse'));
934
            }
935
        }
936
 
937
        // Mark context as dirty.
938
        $context = context_course::instance($course->id);
939
        $context->mark_dirty();
940
    }
941
 
942
    /**
943
     * Validate passed enrolment data against an existing course
944
     *
945
     * @param int $courseid id of the course where enrolment methods are created/updated or 0 if it is a new course
946
     * @param array[] $enrolmentdata
947
     * @return lang_string[] Errors keyed on error code
948
     */
949
    protected function validate_enrolment_data(int $courseid, array $enrolmentdata): array {
950
        global $DB;
951
 
952
        // Nothing to validate.
953
        if (empty($enrolmentdata)) {
954
            return [];
955
        }
956
 
957
        $errors = [];
958
 
959
        $enrolmentplugins = tool_uploadcourse_helper::get_enrolment_plugins();
960
        $instances = enrol_get_instances($courseid, false);
961
 
962
        foreach ($enrolmentdata as $method => $options) {
963
 
964
            if (isset($options['role']) || isset($options['roleid'])) {
965
                if (isset($options['role'])) {
966
                    $role = $options['role'];
967
                    $roleid = $DB->get_field('role', 'id', ['shortname' => $role], MUST_EXIST);
968
                } else {
969
                    $roleid = $options['roleid'];
970
                    $role = $DB->get_field('role', 'shortname', ['id' => $roleid], MUST_EXIST);
971
                }
972
                if ($courseid) {
973
                    if (!$this->validate_role_context($courseid, $roleid)) {
974
                        $errors['contextrolenotallowed'] = new lang_string('contextrolenotallowed', 'core_role', $role);
975
 
976
                        break;
977
                    }
978
                } else {
979
                    // We can at least check that context level is correct while actual context not exist.
980
                    if (!$this->validate_role_context_level($roleid)) {
981
                        $errors['contextrolenotallowed'] = new lang_string('contextrolenotallowed', 'core_role', $role);
982
 
983
                        break;
984
                    }
985
                }
986
            }
987
 
988
            $plugin = $enrolmentplugins[$method];
989
            $errors += $plugin->validate_enrol_plugin_data($options, $courseid);
990
            if ($errors) {
991
                break;
992
            }
993
 
994
            if ($courseid) {
995
                // Find matching instances by enrolment method.
996
                $methodinstances = array_filter($instances, static function (stdClass $instance) use ($method) {
997
                    return (strcmp($instance->enrol, $method) == 0);
998
                });
999
 
1000
                if (!empty($options['delete'])) {
1001
                    // Ensure user is able to delete the instances.
1002
                    foreach ($methodinstances as $methodinstance) {
1003
                        if (!$plugin->can_delete_instance($methodinstance)) {
1004
                            $errors['errorcannotdeleteenrolment'] = new lang_string('errorcannotdeleteenrolment',
1005
                                'tool_uploadcourse', $plugin->get_instance_name($methodinstance));
1006
                            break;
1007
                        }
1008
                    }
1009
                } else if (!empty($options['disable'])) {
1010
                    // Ensure user is able to toggle instance statuses.
1011
                    foreach ($methodinstances as $methodinstance) {
1012
                        if (!$plugin->can_hide_show_instance($methodinstance)) {
1013
                            $errors['errorcannotdisableenrolment'] =
1014
                                new lang_string('errorcannotdisableenrolment', 'tool_uploadcourse',
1015
                                    $plugin->get_instance_name($methodinstance));
1016
 
1017
                            break;
1018
                        }
1019
                    }
1020
                } else {
1021
                    // Ensure user is able to create/update instance.
1022
                    $methodinstance = empty($methodinstances) ? null : reset($methodinstances);
1023
                    if ((empty($methodinstance) && !$plugin->can_add_instance($courseid)) ||
1024
                        (!empty($methodinstance) && !$plugin->can_edit_instance($methodinstance))) {
1025
 
1026
                        $errors['errorcannotcreateorupdateenrolment'] =
1027
                            new lang_string('errorcannotcreateorupdateenrolment', 'tool_uploadcourse',
1028
                                $plugin->get_instance_name($methodinstance));
1029
 
1030
                        break;
1031
                    }
1032
                }
1033
            }
1034
        }
1035
 
1036
        return $errors;
1037
    }
1038
 
1039
    /**
1040
     * Add the enrolment data for the course.
1041
     *
1042
     * @param object $course course record.
1043
     * @return void
1044
     */
1045
    protected function process_enrolment_data($course) {
1046
        global $DB;
1047
 
1048
        $enrolmentdata = $this->enrolmentdata;
1049
        if (empty($enrolmentdata)) {
1050
            return;
1051
        }
1052
 
1053
        $enrolmentplugins = tool_uploadcourse_helper::get_enrolment_plugins();
1054
        foreach ($enrolmentdata as $enrolmethod => $method) {
1055
 
1056
            $plugin = $enrolmentplugins[$enrolmethod];
1057
            $instance = $plugin->find_instance($method, $course->id);
1058
 
1059
            $todelete = isset($method['delete']) && $method['delete'];
1060
            $todisable = isset($method['disable']) && $method['disable'];
1061
            unset($method['delete']);
1062
            unset($method['disable']);
1063
 
1064
            if ($todelete) {
1065
                // Remove the enrolment method.
1066
                if ($instance) {
1067
                    $plugin = $enrolmentplugins[$instance->enrol];
1068
 
1069
                    // Ensure user is able to delete the instance.
1070
                    if ($plugin->can_delete_instance($instance) && $plugin->is_csv_upload_supported()) {
1071
                        $plugin->delete_instance($instance);
1072
                    } else {
1073
                        $this->error('errorcannotdeleteenrolment',
1074
                            new lang_string('errorcannotdeleteenrolment', 'tool_uploadcourse',
1075
                                $plugin->get_instance_name($instance)));
1076
                    }
1077
                }
1078
            } else {
1079
                // Create/update enrolment.
1080
                $plugin = $enrolmentplugins[$enrolmethod];
1081
 
1082
                // In case we could not properly validate enrolment data before the course existed
1083
                // let's repeat it again here.
1084
                $errors = $plugin->validate_enrol_plugin_data($method, $course->id);
1085
 
1086
                if (!$errors) {
1087
                    $status = ($todisable) ? ENROL_INSTANCE_DISABLED : ENROL_INSTANCE_ENABLED;
1088
                    $method += ['status' => $status, 'courseid' => $course->id, 'id' => $instance->id ?? null];
1089
                    $method = $plugin->fill_enrol_custom_fields($method, $course->id);
1090
 
1091
                    // Create a new instance if necessary.
1092
                    if (empty($instance) && $plugin->can_add_instance($course->id)) {
1093
                        $error = $plugin->validate_plugin_data_context($method, $course->id);
1094
                        if ($error) {
1095
                            $this->error('contextnotallowed', $error);
1096
                            break;
1097
                        }
1098
                        $instanceid = $plugin->add_default_instance($course);
1099
                        if (!$instanceid) {
1100
                            // Add instance with provided fields if plugin supports it.
1101
                            $instanceid = $plugin->add_custom_instance($course, $method);
1102
                        }
1103
 
1104
                        $instance = $DB->get_record('enrol', ['id' => $instanceid]);
1105
                        if ($instance) {
1106
                            $instance->roleid = $plugin->get_config('roleid');
1107
                            // On creation the user can decide the status.
1108
                            $plugin->update_status($instance, $status);
1109
                        }
1110
                    }
1111
 
1112
                    // Check if the we need to update the instance status.
1113
                    if ($instance && $status != $instance->status) {
1114
                        if ($plugin->can_hide_show_instance($instance)) {
1115
                            $plugin->update_status($instance, $status);
1116
                        } else {
1117
                            $this->error('errorcannotdisableenrolment',
1118
                                new lang_string('errorcannotdisableenrolment', 'tool_uploadcourse',
1119
                                    $plugin->get_instance_name($instance)));
1120
                            break;
1121
                        }
1122
                    }
1123
 
1124
                    if (empty($instance) || !$plugin->can_edit_instance($instance)) {
1125
                        $this->error('errorcannotcreateorupdateenrolment',
1126
                            new lang_string('errorcannotcreateorupdateenrolment', 'tool_uploadcourse',
1127
                                $plugin->get_instance_name($instance)));
1128
 
1129
                        break;
1130
                    }
1131
 
1132
                    // Validate role context again since course is created.
1133
                    if (isset($method['role']) || isset($method['roleid'])) {
1134
                        if (isset($method['role'])) {
1135
                            $role = $method['role'];
1136
                            $roleid = $DB->get_field('role', 'id', ['shortname' => $role], MUST_EXIST);
1137
                        } else {
1138
                            $roleid = $method['roleid'];
1139
                            $role = $DB->get_field('role', 'shortname', ['id' => $roleid], MUST_EXIST);
1140
                        }
1141
                        if (!$this->validate_role_context($course->id, $roleid)) {
1142
                            $this->error('contextrolenotallowed', new lang_string('contextrolenotallowed', 'core_role', $role));
1143
                            break;
1144
                        }
1145
                    }
1146
 
1147
                    // Now update values.
1148
                    // Sort out plugin specific fields.
1149
                    $modifiedinstance = $plugin->update_enrol_plugin_data($course->id, $method, $instance);
1150
                    $plugin->update_instance($instance, $modifiedinstance);
1151
                } else {
1152
                    foreach ($errors as $key => $message) {
1153
                        $this->error($key, $message);
1154
                    }
1155
                }
1156
            }
1157
        }
1158
    }
1159
 
1160
    /**
1161
     * Check if role is allowed in course context
1162
     *
1163
     * @param int $courseid course context.
1164
     * @param int $roleid Role ID.
1165
     * @return bool
1166
     */
1167
    protected function validate_role_context(int $courseid, int $roleid): bool {
1168
        if (empty($this->assignableroles[$courseid])) {
1169
            $coursecontext = \context_course::instance($courseid);
1170
            $this->assignableroles[$courseid] = get_assignable_roles($coursecontext, ROLENAME_SHORT);
1171
        }
1172
        if (!array_key_exists($roleid, $this->assignableroles[$courseid])) {
1173
            return false;
1174
        }
1175
        return true;
1176
    }
1177
 
1178
    /**
1179
     * Check if role is allowed at this context level.
1180
     *
1181
     * @param int $roleid Role ID.
1182
     * @return bool
1183
     */
1184
    protected function validate_role_context_level(int $roleid): bool {
1185
        if (empty($this->contextlevels[$roleid])) {
1186
            $this->contextlevels[$roleid] = get_role_contextlevels($roleid);
1187
        }
1188
 
1189
        if (!in_array(CONTEXT_COURSE, $this->contextlevels[$roleid])) {
1190
            return false;
1191
        }
1192
        return true;
1193
    }
1194
 
1195
    /**
1196
     * Reset the current course.
1197
     *
1198
     * This does not reset any of the content of the activities.
1199
     *
1200
     * @param stdClass $course the course object of the course to reset.
1201
     * @return array status array of array component, item, error.
1202
     */
1203
    protected function reset($course) {
1204
        global $DB;
1205
 
1206
        $resetdata = new stdClass();
1207
        $resetdata->id = $course->id;
1208
        $resetdata->reset_start_date = time();
1209
        $resetdata->reset_events = true;
1210
        $resetdata->reset_notes = true;
1211
        $resetdata->delete_blog_associations = true;
1212
        $resetdata->reset_completion = true;
1213
        $resetdata->reset_roles_overrides = true;
1214
        $resetdata->reset_roles_local = true;
1215
        $resetdata->reset_groups_members = true;
1216
        $resetdata->reset_groups_remove = true;
1217
        $resetdata->reset_groupings_members = true;
1218
        $resetdata->reset_groupings_remove = true;
1219
        $resetdata->reset_gradebook_items = true;
1220
        $resetdata->reset_gradebook_grades = true;
1221
        $resetdata->reset_comments = true;
1222
 
1223
        if (empty($course->startdate)) {
1224
            $course->startdate = $DB->get_field_select('course', 'startdate', 'id = :id', array('id' => $course->id));
1225
        }
1226
        $resetdata->reset_start_date_old = $course->startdate;
1227
 
1228
        if (empty($course->enddate)) {
1229
            $course->enddate = $DB->get_field_select('course', 'enddate', 'id = :id', array('id' => $course->id));
1230
        }
1231
        $resetdata->reset_end_date_old = $course->enddate;
1232
 
1233
        // Add roles.
1234
        $roles = tool_uploadcourse_helper::get_role_ids();
1235
        $resetdata->unenrol_users = array_values($roles);
1236
        $resetdata->unenrol_users[] = 0;    // Enrolled without role.
1237
 
1238
        return reset_course_userdata($resetdata);
1239
    }
1240
 
1241
    /**
1242
     * Log a status
1243
     *
1244
     * @param string $code status code.
1245
     * @param lang_string $message status message.
1246
     * @return void
1247
     */
1248
    protected function status($code, lang_string $message) {
1249
        if (array_key_exists($code, $this->statuses)) {
1250
            throw new coding_exception('Status code already defined');
1251
        }
1252
        $this->statuses[$code] = $message;
1253
    }
1254
 
1255
}