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
 * 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.
1441 ariadna 512
        if (
513
            !empty($coursedata['fullname']) &&
514
            core_text::strlen($coursedata['fullname']) > \core_course\constants::FULLNAME_MAXIMUM_LENGTH
515
        ) {
516
            $this->error('invalidfullnametoolong', new lang_string('invalidfullnametoolong', 'tool_uploadcourse',
517
                \core_course\constants::FULLNAME_MAXIMUM_LENGTH));
1 efrain 518
            return false;
519
        }
520
 
521
        // If the course does not exist, or will be forced created.
522
        if (!$exists || $mode === tool_uploadcourse_processor::MODE_CREATE_ALL) {
523
 
524
            // Mandatory fields upon creation.
525
            $errors = array();
526
            foreach (self::$mandatoryfields as $field) {
527
                if ((!isset($coursedata[$field]) || $coursedata[$field] === '') &&
528
                        (!isset($this->defaults[$field]) || $this->defaults[$field] === '')) {
529
                    $errors[] = $field;
530
                }
531
            }
532
            if (!empty($errors)) {
533
                $this->error('missingmandatoryfields', new lang_string('missingmandatoryfields', 'tool_uploadcourse',
534
                    implode(', ', $errors)));
535
                return false;
536
            }
537
        }
538
 
539
        // Should the course be renamed?
540
        if (!empty($this->options['rename']) || is_numeric($this->options['rename'])) {
541
            if (!$this->can_update()) {
542
                $this->error('canonlyrenameinupdatemode', new lang_string('canonlyrenameinupdatemode', 'tool_uploadcourse'));
543
                return false;
544
            } else if (!$exists) {
545
                $this->error('cannotrenamecoursenotexist', new lang_string('cannotrenamecoursenotexist', 'tool_uploadcourse'));
546
                return false;
547
            } else if (!$this->can_rename()) {
548
                $this->error('courserenamingnotallowed', new lang_string('courserenamingnotallowed', 'tool_uploadcourse'));
549
                return false;
550
            } else if ($this->options['rename'] !== clean_param($this->options['rename'], PARAM_TEXT)) {
551
                $this->error('invalidshortname', new lang_string('invalidshortname', 'tool_uploadcourse'));
552
                return false;
553
            } else if ($this->exists($this->options['rename'])) {
554
                $this->error('cannotrenameshortnamealreadyinuse',
555
                    new lang_string('cannotrenameshortnamealreadyinuse', 'tool_uploadcourse'));
556
                return false;
557
            } else if (isset($coursedata['idnumber']) &&
558
                    $DB->count_records_select('course', 'idnumber = :idn AND shortname != :sn',
559
                    array('idn' => $coursedata['idnumber'], 'sn' => $this->shortname)) > 0) {
560
                $this->error('cannotrenameidnumberconflict', new lang_string('cannotrenameidnumberconflict', 'tool_uploadcourse'));
561
                return false;
562
            }
563
            $coursedata['shortname'] = $this->options['rename'];
564
            $this->status('courserenamed', new lang_string('courserenamed', 'tool_uploadcourse',
565
                array('from' => $this->shortname, 'to' => $coursedata['shortname'])));
566
        }
567
 
568
        // Should we generate a shortname?
569
        if (empty($this->shortname) && !is_numeric($this->shortname)) {
570
            if (empty($this->importoptions['shortnametemplate'])) {
571
                $this->error('missingshortnamenotemplate', new lang_string('missingshortnamenotemplate', 'tool_uploadcourse'));
572
                return false;
573
            } else if (!$this->can_only_create()) {
574
                $this->error('cannotgenerateshortnameupdatemode',
575
                    new lang_string('cannotgenerateshortnameupdatemode', 'tool_uploadcourse'));
576
                return false;
577
            } else {
578
                $newshortname = tool_uploadcourse_helper::generate_shortname($coursedata,
579
                    $this->importoptions['shortnametemplate']);
580
                if (is_null($newshortname)) {
581
                    $this->error('generatedshortnameinvalid', new lang_string('generatedshortnameinvalid', 'tool_uploadcourse'));
582
                    return false;
583
                } else if ($this->exists($newshortname)) {
584
                    if ($mode === tool_uploadcourse_processor::MODE_CREATE_NEW) {
585
                        $this->error('generatedshortnamealreadyinuse',
586
                            new lang_string('generatedshortnamealreadyinuse', 'tool_uploadcourse'));
587
                        return false;
588
                    }
589
                    $exists = true;
590
                }
591
                $this->status('courseshortnamegenerated', new lang_string('courseshortnamegenerated', 'tool_uploadcourse',
592
                    $newshortname));
593
                $this->shortname = $newshortname;
594
            }
595
        }
596
 
597
        // If exists, but we only want to create courses, increment the shortname.
598
        if ($exists && $mode === tool_uploadcourse_processor::MODE_CREATE_ALL) {
599
            $original = $this->shortname;
600
            $this->shortname = tool_uploadcourse_helper::increment_shortname($this->shortname);
601
            $exists = false;
602
            if ($this->shortname != $original) {
603
                $this->status('courseshortnameincremented', new lang_string('courseshortnameincremented', 'tool_uploadcourse',
604
                    array('from' => $original, 'to' => $this->shortname)));
605
                if (isset($coursedata['idnumber'])) {
606
                    $originalidn = $coursedata['idnumber'];
607
                    $coursedata['idnumber'] = tool_uploadcourse_helper::increment_idnumber($coursedata['idnumber']);
608
                    if ($originalidn != $coursedata['idnumber']) {
609
                        $this->status('courseidnumberincremented', new lang_string('courseidnumberincremented', 'tool_uploadcourse',
610
                            array('from' => $originalidn, 'to' => $coursedata['idnumber'])));
611
                    }
612
                }
613
            }
614
        }
615
 
616
        // If the course does not exist, ensure that the ID number is not taken.
617
        if (!$exists && isset($coursedata['idnumber'])) {
618
            if ($DB->count_records_select('course', 'idnumber = :idn', array('idn' => $coursedata['idnumber'])) > 0) {
619
                $this->error('idnumberalreadyinuse', new lang_string('idnumberalreadyinuse', 'tool_uploadcourse'));
620
                return false;
621
            }
622
        }
623
 
624
        // Course start date.
625
        if (!empty($coursedata['startdate'])) {
626
            $coursedata['startdate'] = strtotime($coursedata['startdate']);
627
        }
628
 
629
        // Course end date.
630
        if (!empty($coursedata['enddate'])) {
631
            $coursedata['enddate'] = strtotime($coursedata['enddate']);
632
        }
633
 
634
        // If lang is specified, check the user is allowed to set that field.
635
        if (!empty($coursedata['lang'])) {
636
            if ($exists) {
637
                $courseid = $DB->get_field('course', 'id', ['shortname' => $this->shortname]);
638
                if (!has_capability('moodle/course:setforcedlanguage', context_course::instance($courseid))) {
639
                    $this->error('cannotforcelang', new lang_string('cannotforcelang', 'tool_uploadcourse'));
640
                    return false;
641
                }
642
            } else {
643
                $catcontext = context_coursecat::instance($coursedata['category']);
644
                if (!guess_if_creator_will_have_course_capability('moodle/course:setforcedlanguage', $catcontext)) {
645
                    $this->error('cannotforcelang', new lang_string('cannotforcelang', 'tool_uploadcourse'));
646
                    return false;
647
                }
648
            }
649
        }
650
 
651
        // Ultimate check mode vs. existence.
652
        switch ($mode) {
653
            case tool_uploadcourse_processor::MODE_CREATE_NEW:
654
            case tool_uploadcourse_processor::MODE_CREATE_ALL:
655
                if ($exists) {
656
                    $this->error('courseexistsanduploadnotallowed',
657
                        new lang_string('courseexistsanduploadnotallowed', 'tool_uploadcourse'));
658
                    return false;
659
                }
660
                break;
661
            case tool_uploadcourse_processor::MODE_UPDATE_ONLY:
662
                if (!$exists) {
663
                    $this->error('coursedoesnotexistandcreatenotallowed',
664
                        new lang_string('coursedoesnotexistandcreatenotallowed', 'tool_uploadcourse'));
665
                    return false;
666
                }
667
                // No break!
668
            case tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE:
669
                if ($exists) {
670
                    if ($updatemode === tool_uploadcourse_processor::UPDATE_NOTHING) {
671
                        $this->error('updatemodedoessettonothing',
672
                            new lang_string('updatemodedoessettonothing', 'tool_uploadcourse'));
673
                        return false;
674
                    }
675
                }
676
                break;
677
            default:
678
                // O_o Huh?! This should really never happen here!
679
                $this->error('unknownimportmode', new lang_string('unknownimportmode', 'tool_uploadcourse'));
680
                return false;
681
        }
682
 
683
        // Get final data.
684
        if ($exists) {
685
            $missingonly = ($updatemode === tool_uploadcourse_processor::UPDATE_MISSING_WITH_DATA_OR_DEFAUTLS);
686
            $coursedata = $this->get_final_update_data($coursedata, $usedefaults, $missingonly);
687
 
688
            // Make sure we are not trying to mess with the front page, though we should never get here!
689
            if ($coursedata['id'] == $SITE->id) {
690
                $this->error('cannotupdatefrontpage', new lang_string('cannotupdatefrontpage', 'tool_uploadcourse'));
691
                return false;
692
            }
693
 
694
            if ($error = permissions::check_permission_to_update($coursedata)) {
695
                $this->error('cannotupdatepermission', $error);
696
                return false;
697
            }
698
 
699
            $this->do = self::DO_UPDATE;
700
        } else {
701
            $coursedata = $this->get_final_create_data($coursedata);
702
 
703
            if ($error = permissions::check_permission_to_create($coursedata)) {
704
                $this->error('courseuploadnotallowed', $error);
705
                return false;
706
            }
707
 
708
            $this->do = self::DO_CREATE;
709
        }
710
 
711
        // Validate course start and end dates.
712
        if ($exists) {
713
            // We also check existing start and end dates if we are updating an existing course.
714
            $existingdata = $DB->get_record('course', array('shortname' => $this->shortname));
715
            if (empty($coursedata['startdate'])) {
716
                $coursedata['startdate'] = $existingdata->startdate;
717
            }
718
            if (empty($coursedata['enddate'])) {
719
                $coursedata['enddate'] = $existingdata->enddate;
720
            }
721
        }
722
        if ($errorcode = course_validate_dates($coursedata)) {
723
            $this->error($errorcode, new lang_string($errorcode, 'error'));
724
            return false;
725
        }
726
 
727
        // Add role renaming.
728
        $errors = array();
729
        $rolenames = tool_uploadcourse_helper::get_role_names($this->rawdata, $errors);
730
        if (!empty($errors)) {
731
            foreach ($errors as $key => $message) {
732
                $this->error($key, $message);
733
            }
734
            return false;
735
        }
736
        foreach ($rolenames as $rolekey => $rolename) {
737
            $coursedata[$rolekey] = $rolename;
738
        }
739
 
740
        // Custom fields. If the course already exists and mode isn't set to force creation, we can use its context.
741
        if ($exists && $mode !== tool_uploadcourse_processor::MODE_CREATE_ALL) {
742
            $context = context_course::instance($coursedata['id']);
743
        } else {
744
            // The category ID is taken from the defaults if it exists, otherwise from course data.
745
            $context = context_coursecat::instance($this->defaults['category'] ?? $coursedata['category']);
746
        }
747
        $customfielddata = tool_uploadcourse_helper::get_custom_course_field_data($this->rawdata, $this->defaults, $context,
748
            $errors);
749
        if (!empty($errors)) {
750
            foreach ($errors as $key => $message) {
751
                $this->error($key, $message);
752
            }
753
 
754
            return false;
755
        }
756
 
757
        foreach ($customfielddata as $name => $value) {
758
            $coursedata[$name] = $value;
759
        }
760
 
761
        // Some validation.
762
        if (!empty($coursedata['format']) && !in_array($coursedata['format'], tool_uploadcourse_helper::get_course_formats())) {
763
            $this->error('invalidcourseformat', new lang_string('invalidcourseformat', 'tool_uploadcourse'));
764
            return false;
765
        }
766
 
767
        // Add data for course format options.
768
        if (isset($coursedata['format']) || $exists) {
769
            if (isset($coursedata['format'])) {
770
                $courseformat = course_get_format((object)['format' => $coursedata['format']]);
771
            } else {
772
                $courseformat = course_get_format($existingdata);
773
            }
774
            $coursedata += $courseformat->validate_course_format_options($this->rawdata);
775
        }
776
 
777
        // Special case, 'numsections' is not a course format option any more but still should apply from the template course,
778
        // if any, and otherwise from defaults.
779
        if (!$exists || !array_key_exists('numsections', $coursedata)) {
780
            if (isset($this->rawdata['numsections']) && is_numeric($this->rawdata['numsections'])) {
781
                $coursedata['numsections'] = (int)$this->rawdata['numsections'];
782
            } else if (isset($this->options['templatecourse'])) {
783
                $numsections = tool_uploadcourse_helper::get_coursesection_count($this->options['templatecourse']);
784
                if ($numsections != 0) {
785
                    $coursedata['numsections'] = $numsections;
786
                } else {
787
                    $coursedata['numsections'] = get_config('moodlecourse', 'numsections');
788
                }
789
            } else {
790
                $coursedata['numsections'] = get_config('moodlecourse', 'numsections');
791
            }
792
        }
793
 
794
        // Visibility can only be 0 or 1.
795
        if (!empty($coursedata['visible']) AND !($coursedata['visible'] == 0 OR $coursedata['visible'] == 1)) {
796
            $this->error('invalidvisibilitymode', new lang_string('invalidvisibilitymode', 'tool_uploadcourse'));
797
            return false;
798
        }
799
 
800
        // Ensure that user is allowed to configure course content download and the field contains a valid value.
801
        if (isset($coursedata['downloadcontent'])) {
802
            if (!$CFG->downloadcoursecontentallowed ||
803
                    !has_capability('moodle/course:configuredownloadcontent', $context)) {
804
 
805
                $this->error('downloadcontentnotallowed', new lang_string('downloadcontentnotallowed', 'tool_uploadcourse'));
806
                return false;
807
            }
808
 
809
            $downloadcontentvalues = [
810
                DOWNLOAD_COURSE_CONTENT_DISABLED,
811
                DOWNLOAD_COURSE_CONTENT_ENABLED,
812
                DOWNLOAD_COURSE_CONTENT_SITE_DEFAULT,
813
            ];
814
            if (!in_array($coursedata['downloadcontent'], $downloadcontentvalues)) {
815
                $this->error('invaliddownloadcontent', new lang_string('invaliddownloadcontent', 'tool_uploadcourse'));
816
                return false;
817
            }
818
        }
819
 
820
        // Saving data.
821
        $this->data = $coursedata;
822
 
823
        // Get enrolment data. Where the course already exists, we can also perform validation.
824
        // Some data is impossible to validate without the existing course, we will do it again during actual upload.
825
        $this->enrolmentdata = tool_uploadcourse_helper::get_enrolment_data($this->rawdata);
826
        $courseid = $coursedata['id'] ?? 0;
827
        $errors = $this->validate_enrolment_data($courseid, $this->enrolmentdata);
828
 
829
        if (!empty($errors)) {
830
            foreach ($errors as $key => $message) {
831
                $this->error($key, $message);
832
            }
833
 
834
            return false;
835
        }
836
 
837
        if (isset($this->rawdata['tags']) && strval($this->rawdata['tags']) !== '') {
838
            $this->data['tags'] = preg_split('/\s*,\s*/', trim($this->rawdata['tags']), -1, PREG_SPLIT_NO_EMPTY);
839
        }
840
 
841
        // Restore data.
842
        // TODO Speed up things by not really extracting the backup just yet, but checking that
843
        // the backup file or shortname passed are valid. Extraction should happen in proceed().
844
        $this->restoredata = $this->get_restore_content_dir();
845
        if ($this->restoredata === false) {
846
            return false;
847
        }
848
 
849
        if ($this->restoredata && ($error = permissions::check_permission_to_restore($this->do, $this->data))) {
850
            $this->error('courserestorepermission', $error);
851
            return false;
852
        }
853
 
854
        // We can only reset courses when allowed and we are updating the course.
855
        if ($this->importoptions['reset'] || $this->options['reset']) {
856
            if ($this->do !== self::DO_UPDATE) {
857
                $this->error('canonlyresetcourseinupdatemode',
858
                    new lang_string('canonlyresetcourseinupdatemode', 'tool_uploadcourse'));
859
                return false;
860
            } else if (!$this->can_reset()) {
861
                $this->error('courseresetnotallowed', new lang_string('courseresetnotallowed', 'tool_uploadcourse'));
862
                return false;
863
            }
864
 
865
            if ($error = permissions::check_permission_to_reset($this->data)) {
866
                $this->error('courseresetpermission', $error);
867
                return false;
868
            }
869
        }
870
 
871
        return true;
872
    }
873
 
874
    /**
875
     * Proceed with the import of the course.
876
     *
877
     * @return void
878
     */
879
    public function proceed() {
880
        global $CFG, $USER;
881
 
882
        if (!$this->prepared) {
883
            throw new coding_exception('The course has not been prepared.');
884
        } else if ($this->has_errors()) {
885
            throw new moodle_exception('Cannot proceed, errors were detected.');
886
        } else if ($this->processstarted) {
887
            throw new coding_exception('The process has already been started.');
888
        }
889
        $this->processstarted = true;
890
 
891
        if ($this->do === self::DO_DELETE) {
892
            if ($this->delete()) {
893
                $this->status('coursedeleted', new lang_string('coursedeleted', 'tool_uploadcourse'));
894
            } else {
895
                $this->error('errorwhiledeletingcourse', new lang_string('errorwhiledeletingcourse', 'tool_uploadcourse'));
896
            }
897
            return true;
898
        } else if ($this->do === self::DO_CREATE) {
899
            $course = create_course((object) $this->data);
900
            $this->id = $course->id;
901
            $this->status('coursecreated', new lang_string('coursecreated', 'tool_uploadcourse'));
902
        } else if ($this->do === self::DO_UPDATE) {
903
            $course = (object) $this->data;
904
            update_course($course);
905
            $this->id = $course->id;
906
            $this->status('courseupdated', new lang_string('courseupdated', 'tool_uploadcourse'));
907
        } else {
908
            // Strangely the outcome has not been defined, or is unknown!
909
            throw new coding_exception('Unknown outcome!');
910
        }
911
 
912
        // Restore a course.
913
        if (!empty($this->restoredata)) {
914
            $rc = new restore_controller($this->restoredata, $course->id, backup::INTERACTIVE_NO,
915
                backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
916
 
917
            // Check if the format conversion must happen first.
918
            if ($rc->get_status() == backup::STATUS_REQUIRE_CONV) {
919
                $rc->convert();
920
            }
921
            if ($rc->execute_precheck()) {
922
                $rc->execute_plan();
923
                $this->status('courserestored', new lang_string('courserestored', 'tool_uploadcourse'));
924
            } else {
925
                $this->error('errorwhilerestoringcourse', new lang_string('errorwhilerestoringcourse', 'tool_uploadcourse'));
926
            }
927
            $rc->destroy();
928
        }
929
 
930
        // Proceed with enrolment data.
931
        $this->process_enrolment_data($course);
932
 
933
        // Reset the course.
934
        if ($this->importoptions['reset'] || $this->options['reset']) {
935
            if ($this->do === self::DO_UPDATE && $this->can_reset()) {
936
                $this->reset($course);
937
                $this->status('coursereset', new lang_string('coursereset', 'tool_uploadcourse'));
938
            }
939
        }
940
 
941
        // Mark context as dirty.
942
        $context = context_course::instance($course->id);
943
        $context->mark_dirty();
944
    }
945
 
946
    /**
947
     * Validate passed enrolment data against an existing course
948
     *
949
     * @param int $courseid id of the course where enrolment methods are created/updated or 0 if it is a new course
950
     * @param array[] $enrolmentdata
951
     * @return lang_string[] Errors keyed on error code
952
     */
953
    protected function validate_enrolment_data(int $courseid, array $enrolmentdata): array {
954
        global $DB;
955
 
956
        // Nothing to validate.
957
        if (empty($enrolmentdata)) {
958
            return [];
959
        }
960
 
961
        $errors = [];
962
 
963
        $enrolmentplugins = tool_uploadcourse_helper::get_enrolment_plugins();
964
        $instances = enrol_get_instances($courseid, false);
965
 
966
        foreach ($enrolmentdata as $method => $options) {
967
 
968
            if (isset($options['role']) || isset($options['roleid'])) {
969
                if (isset($options['role'])) {
970
                    $role = $options['role'];
971
                    $roleid = $DB->get_field('role', 'id', ['shortname' => $role], MUST_EXIST);
972
                } else {
973
                    $roleid = $options['roleid'];
974
                    $role = $DB->get_field('role', 'shortname', ['id' => $roleid], MUST_EXIST);
975
                }
976
                if ($courseid) {
977
                    if (!$this->validate_role_context($courseid, $roleid)) {
978
                        $errors['contextrolenotallowed'] = new lang_string('contextrolenotallowed', 'core_role', $role);
979
 
980
                        break;
981
                    }
982
                } else {
983
                    // We can at least check that context level is correct while actual context not exist.
984
                    if (!$this->validate_role_context_level($roleid)) {
985
                        $errors['contextrolenotallowed'] = new lang_string('contextrolenotallowed', 'core_role', $role);
986
 
987
                        break;
988
                    }
989
                }
990
            }
991
 
992
            $plugin = $enrolmentplugins[$method];
993
            $errors += $plugin->validate_enrol_plugin_data($options, $courseid);
994
            if ($errors) {
995
                break;
996
            }
997
 
998
            if ($courseid) {
999
                // Find matching instances by enrolment method.
1000
                $methodinstances = array_filter($instances, static function (stdClass $instance) use ($method) {
1001
                    return (strcmp($instance->enrol, $method) == 0);
1002
                });
1003
 
1004
                if (!empty($options['delete'])) {
1005
                    // Ensure user is able to delete the instances.
1006
                    foreach ($methodinstances as $methodinstance) {
1007
                        if (!$plugin->can_delete_instance($methodinstance)) {
1008
                            $errors['errorcannotdeleteenrolment'] = new lang_string('errorcannotdeleteenrolment',
1009
                                'tool_uploadcourse', $plugin->get_instance_name($methodinstance));
1010
                            break;
1011
                        }
1012
                    }
1013
                } else if (!empty($options['disable'])) {
1014
                    // Ensure user is able to toggle instance statuses.
1015
                    foreach ($methodinstances as $methodinstance) {
1016
                        if (!$plugin->can_hide_show_instance($methodinstance)) {
1017
                            $errors['errorcannotdisableenrolment'] =
1018
                                new lang_string('errorcannotdisableenrolment', 'tool_uploadcourse',
1019
                                    $plugin->get_instance_name($methodinstance));
1020
 
1021
                            break;
1022
                        }
1023
                    }
1024
                } else {
1025
                    // Ensure user is able to create/update instance.
1026
                    $methodinstance = empty($methodinstances) ? null : reset($methodinstances);
1027
                    if ((empty($methodinstance) && !$plugin->can_add_instance($courseid)) ||
1028
                        (!empty($methodinstance) && !$plugin->can_edit_instance($methodinstance))) {
1029
 
1030
                        $errors['errorcannotcreateorupdateenrolment'] =
1031
                            new lang_string('errorcannotcreateorupdateenrolment', 'tool_uploadcourse',
1032
                                $plugin->get_instance_name($methodinstance));
1033
 
1034
                        break;
1035
                    }
1036
                }
1037
            }
1038
        }
1039
 
1040
        return $errors;
1041
    }
1042
 
1043
    /**
1044
     * Add the enrolment data for the course.
1045
     *
1046
     * @param object $course course record.
1047
     * @return void
1048
     */
1049
    protected function process_enrolment_data($course) {
1050
        global $DB;
1051
 
1052
        $enrolmentdata = $this->enrolmentdata;
1053
        if (empty($enrolmentdata)) {
1054
            return;
1055
        }
1056
 
1057
        $enrolmentplugins = tool_uploadcourse_helper::get_enrolment_plugins();
1058
        foreach ($enrolmentdata as $enrolmethod => $method) {
1059
 
1060
            $plugin = $enrolmentplugins[$enrolmethod];
1061
            $instance = $plugin->find_instance($method, $course->id);
1062
 
1063
            $todelete = isset($method['delete']) && $method['delete'];
1064
            $todisable = isset($method['disable']) && $method['disable'];
1065
            unset($method['delete']);
1066
            unset($method['disable']);
1067
 
1068
            if ($todelete) {
1069
                // Remove the enrolment method.
1070
                if ($instance) {
1071
                    $plugin = $enrolmentplugins[$instance->enrol];
1072
 
1073
                    // Ensure user is able to delete the instance.
1074
                    if ($plugin->can_delete_instance($instance) && $plugin->is_csv_upload_supported()) {
1075
                        $plugin->delete_instance($instance);
1076
                    } else {
1077
                        $this->error('errorcannotdeleteenrolment',
1078
                            new lang_string('errorcannotdeleteenrolment', 'tool_uploadcourse',
1079
                                $plugin->get_instance_name($instance)));
1080
                    }
1081
                }
1082
            } else {
1083
                // Create/update enrolment.
1084
                $plugin = $enrolmentplugins[$enrolmethod];
1085
 
1086
                // In case we could not properly validate enrolment data before the course existed
1087
                // let's repeat it again here.
1088
                $errors = $plugin->validate_enrol_plugin_data($method, $course->id);
1089
 
1090
                if (!$errors) {
1091
                    $status = ($todisable) ? ENROL_INSTANCE_DISABLED : ENROL_INSTANCE_ENABLED;
1092
                    $method += ['status' => $status, 'courseid' => $course->id, 'id' => $instance->id ?? null];
1093
                    $method = $plugin->fill_enrol_custom_fields($method, $course->id);
1094
 
1095
                    // Create a new instance if necessary.
1096
                    if (empty($instance) && $plugin->can_add_instance($course->id)) {
1097
                        $error = $plugin->validate_plugin_data_context($method, $course->id);
1098
                        if ($error) {
1099
                            $this->error('contextnotallowed', $error);
1100
                            break;
1101
                        }
1102
                        $instanceid = $plugin->add_default_instance($course);
1103
                        if (!$instanceid) {
1104
                            // Add instance with provided fields if plugin supports it.
1105
                            $instanceid = $plugin->add_custom_instance($course, $method);
1106
                        }
1107
 
1108
                        $instance = $DB->get_record('enrol', ['id' => $instanceid]);
1109
                        if ($instance) {
1110
                            $instance->roleid = $plugin->get_config('roleid');
1111
                            // On creation the user can decide the status.
1112
                            $plugin->update_status($instance, $status);
1113
                        }
1114
                    }
1115
 
1116
                    // Check if the we need to update the instance status.
1117
                    if ($instance && $status != $instance->status) {
1118
                        if ($plugin->can_hide_show_instance($instance)) {
1119
                            $plugin->update_status($instance, $status);
1120
                        } else {
1121
                            $this->error('errorcannotdisableenrolment',
1122
                                new lang_string('errorcannotdisableenrolment', 'tool_uploadcourse',
1123
                                    $plugin->get_instance_name($instance)));
1124
                            break;
1125
                        }
1126
                    }
1127
 
1128
                    if (empty($instance) || !$plugin->can_edit_instance($instance)) {
1129
                        $this->error('errorcannotcreateorupdateenrolment',
1130
                            new lang_string('errorcannotcreateorupdateenrolment', 'tool_uploadcourse',
1131
                                $plugin->get_instance_name($instance)));
1132
 
1133
                        break;
1134
                    }
1135
 
1136
                    // Validate role context again since course is created.
1137
                    if (isset($method['role']) || isset($method['roleid'])) {
1138
                        if (isset($method['role'])) {
1139
                            $role = $method['role'];
1140
                            $roleid = $DB->get_field('role', 'id', ['shortname' => $role], MUST_EXIST);
1141
                        } else {
1142
                            $roleid = $method['roleid'];
1143
                            $role = $DB->get_field('role', 'shortname', ['id' => $roleid], MUST_EXIST);
1144
                        }
1145
                        if (!$this->validate_role_context($course->id, $roleid)) {
1146
                            $this->error('contextrolenotallowed', new lang_string('contextrolenotallowed', 'core_role', $role));
1147
                            break;
1148
                        }
1149
                    }
1150
 
1151
                    // Now update values.
1152
                    // Sort out plugin specific fields.
1441 ariadna 1153
                    $modifiedinstance = $plugin->update_enrol_plugin_data($course->id, $method, clone $instance);
1 efrain 1154
                    $plugin->update_instance($instance, $modifiedinstance);
1155
                } else {
1156
                    foreach ($errors as $key => $message) {
1157
                        $this->error($key, $message);
1158
                    }
1159
                }
1160
            }
1161
        }
1162
    }
1163
 
1164
    /**
1165
     * Check if role is allowed in course context
1166
     *
1167
     * @param int $courseid course context.
1168
     * @param int $roleid Role ID.
1169
     * @return bool
1170
     */
1171
    protected function validate_role_context(int $courseid, int $roleid): bool {
1172
        if (empty($this->assignableroles[$courseid])) {
1173
            $coursecontext = \context_course::instance($courseid);
1174
            $this->assignableroles[$courseid] = get_assignable_roles($coursecontext, ROLENAME_SHORT);
1175
        }
1176
        if (!array_key_exists($roleid, $this->assignableroles[$courseid])) {
1177
            return false;
1178
        }
1179
        return true;
1180
    }
1181
 
1182
    /**
1183
     * Check if role is allowed at this context level.
1184
     *
1185
     * @param int $roleid Role ID.
1186
     * @return bool
1187
     */
1188
    protected function validate_role_context_level(int $roleid): bool {
1189
        if (empty($this->contextlevels[$roleid])) {
1190
            $this->contextlevels[$roleid] = get_role_contextlevels($roleid);
1191
        }
1192
 
1193
        if (!in_array(CONTEXT_COURSE, $this->contextlevels[$roleid])) {
1194
            return false;
1195
        }
1196
        return true;
1197
    }
1198
 
1199
    /**
1200
     * Reset the current course.
1201
     *
1202
     * This does not reset any of the content of the activities.
1203
     *
1204
     * @param stdClass $course the course object of the course to reset.
1205
     * @return array status array of array component, item, error.
1206
     */
1207
    protected function reset($course) {
1208
        global $DB;
1209
 
1210
        $resetdata = new stdClass();
1211
        $resetdata->id = $course->id;
1212
        $resetdata->reset_start_date = time();
1213
        $resetdata->reset_events = true;
1214
        $resetdata->reset_notes = true;
1215
        $resetdata->delete_blog_associations = true;
1216
        $resetdata->reset_completion = true;
1217
        $resetdata->reset_roles_overrides = true;
1218
        $resetdata->reset_roles_local = true;
1219
        $resetdata->reset_groups_members = true;
1220
        $resetdata->reset_groups_remove = true;
1221
        $resetdata->reset_groupings_members = true;
1222
        $resetdata->reset_groupings_remove = true;
1223
        $resetdata->reset_gradebook_items = true;
1224
        $resetdata->reset_gradebook_grades = true;
1225
        $resetdata->reset_comments = true;
1226
 
1227
        if (empty($course->startdate)) {
1228
            $course->startdate = $DB->get_field_select('course', 'startdate', 'id = :id', array('id' => $course->id));
1229
        }
1230
        $resetdata->reset_start_date_old = $course->startdate;
1231
 
1232
        if (empty($course->enddate)) {
1233
            $course->enddate = $DB->get_field_select('course', 'enddate', 'id = :id', array('id' => $course->id));
1234
        }
1235
        $resetdata->reset_end_date_old = $course->enddate;
1236
 
1237
        // Add roles.
1238
        $roles = tool_uploadcourse_helper::get_role_ids();
1239
        $resetdata->unenrol_users = array_values($roles);
1240
        $resetdata->unenrol_users[] = 0;    // Enrolled without role.
1241
 
1242
        return reset_course_userdata($resetdata);
1243
    }
1244
 
1245
    /**
1246
     * Log a status
1247
     *
1248
     * @param string $code status code.
1249
     * @param lang_string $message status message.
1250
     * @return void
1251
     */
1252
    protected function status($code, lang_string $message) {
1253
        if (array_key_exists($code, $this->statuses)) {
1254
            throw new coding_exception('Status code already defined');
1255
        }
1256
        $this->statuses[$code] = $message;
1257
    }
1258
 
1259
}