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
 
3
// This file is part of Moodle - http://moodle.org/
4
//
5
// Moodle is free software: you can redistribute it and/or modify
6
// it under the terms of the GNU General Public License as published by
7
// the Free Software Foundation, either version 3 of the License, or
8
// (at your option) any later version.
9
//
10
// Moodle is distributed in the hope that it will be useful,
11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
12
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
// GNU General Public License for more details.
14
//
15
// You should have received a copy of the GNU General Public License
16
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17
 
18
/**
19
 * Defines various restore steps that will be used by common tasks in restore
20
 *
21
 * @package     core_backup
22
 * @subpackage  moodle2
23
 * @category    backup
24
 * @copyright   2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
25
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26
 */
27
 
28
defined('MOODLE_INTERNAL') || die();
29
 
30
/**
31
 * delete old directories and conditionally create backup_temp_ids table
32
 */
33
class restore_create_and_clean_temp_stuff extends restore_execution_step {
34
 
35
    protected function define_execution() {
36
        $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
37
        // If the table already exists, it's because restore_prechecks have been executed in the same
38
        // request (without problems) and it already contains a bunch of preloaded information (users...)
39
        // that we aren't going to execute again
40
        if ($exists) { // Inform plan about preloaded information
41
            $this->task->set_preloaded_information();
42
        }
43
        // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
44
        $itemid = $this->task->get_old_contextid();
45
        $newitemid = context_course::instance($this->get_courseid())->id;
46
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
47
        // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
48
        $itemid = $this->task->get_old_system_contextid();
49
        $newitemid = context_system::instance()->id;
50
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
51
        // Create the old-course-id to new-course-id mapping, we need that available since the beginning
52
        $itemid = $this->task->get_old_courseid();
53
        $newitemid = $this->get_courseid();
54
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
55
 
56
    }
57
}
58
 
59
/**
60
 * Drop temp ids table and delete the temp dir used by backup/restore (conditionally).
61
 */
62
class restore_drop_and_clean_temp_stuff extends restore_execution_step {
63
 
64
    protected function define_execution() {
65
        global $CFG;
66
        restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
67
        if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
68
            $progress = $this->task->get_progress();
69
            $progress->start_progress('Deleting backup dir');
70
            backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir
71
            $progress->end_progress();
72
        }
73
    }
74
}
75
 
76
/**
77
 * Restore calculated grade items, grade categories etc
78
 */
79
class restore_gradebook_structure_step extends restore_structure_step {
80
 
81
    /**
82
     * To conditionally decide if this step must be executed
83
     * Note the "settings" conditions are evaluated in the
84
     * corresponding task. Here we check for other conditions
85
     * not being restore settings (files, site settings...)
86
     */
87
     protected function execute_condition() {
88
        global $CFG, $DB;
89
 
90
        if ($this->get_courseid() == SITEID) {
91
            return false;
92
        }
93
 
94
        // No gradebook info found, don't execute
95
        $fullpath = $this->task->get_taskbasepath();
96
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
97
        if (!file_exists($fullpath)) {
98
            return false;
99
        }
100
 
101
        // Some module present in backup file isn't available to restore
102
        // in this site, don't execute
103
        if ($this->task->is_missing_modules()) {
104
            return false;
105
        }
106
 
107
        // Some activity has been excluded to be restored, don't execute
108
        if ($this->task->is_excluding_activities()) {
109
            return false;
110
        }
111
 
112
        // There should only be one grade category (the 1 associated with the course itself)
113
        // If other categories already exist we're restoring into an existing course.
114
        // Restoring categories into a course with an existing category structure is unlikely to go well
115
        $category = new stdclass();
116
        $category->courseid  = $this->get_courseid();
117
        $catcount = $DB->count_records('grade_categories', (array)$category);
118
        if ($catcount>1) {
119
            return false;
120
        }
121
 
122
        $restoretask = $this->get_task();
123
 
124
        // On older versions the freeze value has to be converted.
125
        // We do this from here as it is happening right before the file is read.
126
        // This only targets the backup files that can contain the legacy freeze.
127
        if ($restoretask->backup_version_compare(20150618, '>')
128
                && $restoretask->backup_release_compare('3.0', '<')
129
                || $restoretask->backup_version_compare(20160527, '<')) {
130
            $this->rewrite_step_backup_file_for_legacy_freeze($fullpath);
131
        }
132
 
133
        // Arrived here, execute the step
134
        return true;
135
     }
136
 
137
    protected function define_structure() {
138
        $paths = array();
139
        $userinfo = $this->task->get_setting_value('users');
140
 
141
        $paths[] = new restore_path_element('attributes', '/gradebook/attributes');
142
        $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
143
 
144
        $gradeitem = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
145
        $paths[] = $gradeitem;
146
        $this->add_plugin_structure('local', $gradeitem);
147
 
148
        if ($userinfo) {
149
            $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
150
        }
151
        $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
152
        $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
153
 
154
        return $paths;
155
    }
156
 
157
    protected function process_attributes($data) {
158
        // For non-merge restore types:
159
        // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
160
        $target = $this->get_task()->get_target();
161
        if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) {
162
            set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
163
        }
164
        if (!empty($data['calculations_freeze'])) {
165
            if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING ||
166
                    $target == backup::TARGET_EXISTING_DELETING) {
167
                set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
168
            }
169
        }
170
    }
171
 
172
    protected function process_grade_item($data) {
173
        global $DB;
174
 
175
        $data = (object)$data;
176
 
177
        $oldid = $data->id;
178
        $data->course = $this->get_courseid();
179
 
180
        $data->courseid = $this->get_courseid();
181
 
182
        if ($data->itemtype=='manual') {
183
            // manual grade items store category id in categoryid
184
            $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
185
            // if mapping failed put in course's grade category
186
            if (NULL == $data->categoryid) {
187
                $coursecat = grade_category::fetch_course_category($this->get_courseid());
188
                $data->categoryid = $coursecat->id;
189
            }
190
        } else if ($data->itemtype=='course') {
191
            // course grade item stores their category id in iteminstance
192
            $coursecat = grade_category::fetch_course_category($this->get_courseid());
193
            $data->iteminstance = $coursecat->id;
194
        } else if ($data->itemtype=='category') {
195
            // category grade items store their category id in iteminstance
196
            $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
197
        } else {
198
            throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
199
        }
200
 
201
        $data->scaleid   = $this->get_mappingid('scale', $data->scaleid, NULL);
202
        $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
203
 
204
        $data->locktime = $this->apply_date_offset($data->locktime);
205
 
206
        $coursecategory = $newitemid = null;
207
        //course grade item should already exist so updating instead of inserting
208
        if($data->itemtype=='course') {
209
            //get the ID of the already created grade item
210
            $gi = new stdclass();
211
            $gi->courseid  = $this->get_courseid();
212
            $gi->itemtype  = $data->itemtype;
213
 
214
            //need to get the id of the grade_category that was automatically created for the course
215
            $category = new stdclass();
216
            $category->courseid  = $this->get_courseid();
217
            $category->parent  = null;
218
            //course category fullname starts out as ? but may be edited
219
            //$category->fullname  = '?';
220
            $coursecategory = $DB->get_record('grade_categories', (array)$category);
221
            $gi->iteminstance = $coursecategory->id;
222
 
223
            $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
224
            if (!empty($existinggradeitem)) {
225
                $data->id = $newitemid = $existinggradeitem->id;
226
                $DB->update_record('grade_items', $data);
227
            }
228
        } else if ($data->itemtype == 'manual') {
229
            // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
230
            $gi = array(
231
                'itemtype' => $data->itemtype,
232
                'courseid' => $data->courseid,
233
                'itemname' => $data->itemname,
234
                'categoryid' => $data->categoryid,
235
            );
236
            $newitemid = $DB->get_field('grade_items', 'id', $gi);
237
        }
238
 
239
        if (empty($newitemid)) {
240
            //in case we found the course category but still need to insert the course grade item
241
            if ($data->itemtype=='course' && !empty($coursecategory)) {
242
                $data->iteminstance = $coursecategory->id;
243
            }
244
 
245
            $newitemid = $DB->insert_record('grade_items', $data);
246
            $data->id = $newitemid;
247
            $gradeitem = new grade_item($data);
248
            core\event\grade_item_created::create_from_grade_item($gradeitem)->trigger();
249
        }
250
        $this->set_mapping('grade_item', $oldid, $newitemid);
251
    }
252
 
253
    protected function process_grade_grade($data) {
254
        global $DB;
255
 
256
        $data = (object)$data;
257
        $oldid = $data->id;
258
        $olduserid = $data->userid;
259
 
260
        $data->itemid = $this->get_new_parentid('grade_item');
261
 
262
        $data->userid = $this->get_mappingid('user', $data->userid, null);
263
        if (!empty($data->userid)) {
264
            $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
265
            $data->locktime     = $this->apply_date_offset($data->locktime);
266
 
267
            $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
268
            if ($gradeexists) {
269
                $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
270
                $this->log($message, backup::LOG_DEBUG);
271
            } else {
272
                $newitemid = $DB->insert_record('grade_grades', $data);
273
                $this->set_mapping('grade_grades', $oldid, $newitemid);
274
            }
275
        } else {
276
            $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
277
            $this->log($message, backup::LOG_DEBUG);
278
        }
279
    }
280
 
281
    protected function process_grade_category($data) {
282
        global $DB;
283
 
284
        $data = (object)$data;
285
        $oldid = $data->id;
286
 
287
        $data->course = $this->get_courseid();
288
        $data->courseid = $data->course;
289
 
290
        $newitemid = null;
291
        //no parent means a course level grade category. That may have been created when the course was created
292
        if(empty($data->parent)) {
293
            //parent was being saved as 0 when it should be null
294
            $data->parent = null;
295
 
296
            //get the already created course level grade category
297
            $category = new stdclass();
298
            $category->courseid = $this->get_courseid();
299
            $category->parent = null;
300
 
301
            $coursecategory = $DB->get_record('grade_categories', (array)$category);
302
            if (!empty($coursecategory)) {
303
                $data->id = $newitemid = $coursecategory->id;
304
                $DB->update_record('grade_categories', $data);
305
            }
306
        }
307
 
308
        // Add a warning about a removed setting.
309
        if (!empty($data->aggregatesubcats)) {
310
            set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
311
        }
312
 
313
        //need to insert a course category
314
        if (empty($newitemid)) {
315
            $newitemid = $DB->insert_record('grade_categories', $data);
316
        }
317
        $this->set_mapping('grade_category', $oldid, $newitemid);
318
    }
319
    protected function process_grade_letter($data) {
320
        global $DB;
321
 
322
        $data = (object)$data;
323
        $oldid = $data->id;
324
 
325
        $data->contextid = context_course::instance($this->get_courseid())->id;
326
 
327
        $gradeletter = (array)$data;
328
        unset($gradeletter['id']);
329
        if (!$DB->record_exists('grade_letters', $gradeletter)) {
330
            $newitemid = $DB->insert_record('grade_letters', $data);
331
        } else {
332
            $newitemid = $data->id;
333
        }
334
 
335
        $this->set_mapping('grade_letter', $oldid, $newitemid);
336
    }
337
    protected function process_grade_setting($data) {
338
        global $DB;
339
 
340
        $data = (object)$data;
341
        $oldid = $data->id;
342
 
343
        $data->courseid = $this->get_courseid();
344
 
345
        $target = $this->get_task()->get_target();
346
        if ($data->name == 'minmaxtouse' &&
347
                ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) {
348
            // We never restore minmaxtouse during merge.
349
            return;
350
        }
351
 
352
        if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
353
            $newitemid = $DB->insert_record('grade_settings', $data);
354
        } else {
355
            $newitemid = $data->id;
356
        }
357
 
358
        if (!empty($oldid)) {
359
            // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
360
            $this->set_mapping('grade_setting', $oldid, $newitemid);
361
        }
362
    }
363
 
364
    /**
365
     * put all activity grade items in the correct grade category and mark all for recalculation
366
     */
367
    protected function after_execute() {
368
        global $DB;
369
 
370
        $conditions = array(
371
            'backupid' => $this->get_restoreid(),
372
            'itemname' => 'grade_item'//,
373
            //'itemid'   => $itemid
374
        );
375
        $rs = $DB->get_recordset('backup_ids_temp', $conditions);
376
 
377
        // We need this for calculation magic later on.
378
        $mappings = array();
379
 
380
        if (!empty($rs)) {
381
            foreach($rs as $grade_item_backup) {
382
 
383
                // Store the oldid with the new id.
384
                $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
385
 
386
                $updateobj = new stdclass();
387
                $updateobj->id = $grade_item_backup->newitemid;
388
 
389
                //if this is an activity grade item that needs to be put back in its correct category
390
                if (!empty($grade_item_backup->parentitemid)) {
391
                    $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
392
                    if (!is_null($oldcategoryid)) {
393
                        $updateobj->categoryid = $oldcategoryid;
394
                        $DB->update_record('grade_items', $updateobj);
395
                    }
396
                } else {
397
                    //mark course and category items as needing to be recalculated
398
                    $updateobj->needsupdate=1;
399
                    $DB->update_record('grade_items', $updateobj);
400
                }
401
            }
402
        }
403
        $rs->close();
404
 
405
        // We need to update the calculations for calculated grade items that may reference old
406
        // grade item ids using ##gi\d+##.
407
        // $mappings can be empty, use 0 if so (won't match ever)
408
        list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
409
        $sql = "SELECT gi.id, gi.calculation
410
                  FROM {grade_items} gi
411
                 WHERE gi.id {$sql} AND
412
                       calculation IS NOT NULL";
413
        $rs = $DB->get_recordset_sql($sql, $params);
414
        foreach ($rs as $gradeitem) {
415
            // Collect all of the used grade item id references
416
            if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
417
                // This calculation doesn't reference any other grade items... EASY!
418
                continue;
419
            }
420
            // For this next bit we are going to do the replacement of id's in two steps:
421
            // 1. We will replace all old id references with a special mapping reference.
422
            // 2. We will replace all mapping references with id's
423
            // Why do we do this?
424
            // Because there potentially there will be an overlap of ids within the query and we
425
            // we substitute the wrong id.. safest way around this is the two step system
426
            $calculationmap = array();
427
            $mapcount = 0;
428
            foreach ($matches[1] as $match) {
429
                // Check that the old id is known to us, if not it was broken to begin with and will
430
                // continue to be broken.
431
                if (!array_key_exists($match, $mappings)) {
432
                    continue;
433
                }
434
                // Our special mapping key
435
                $mapping = '##MAPPING'.$mapcount.'##';
436
                // The old id that exists within the calculation now
437
                $oldid = '##gi'.$match.'##';
438
                // The new id that we want to replace the old one with.
439
                $newid = '##gi'.$mappings[$match].'##';
440
                // Replace in the special mapping key
441
                $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
442
                // And record the mapping
443
                $calculationmap[$mapping] = $newid;
444
                $mapcount++;
445
            }
446
            // Iterate all special mappings for this calculation and replace in the new id's
447
            foreach ($calculationmap as $mapping => $newid) {
448
                $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
449
            }
450
            // Update the calculation now that its being remapped
451
            $DB->update_record('grade_items', $gradeitem);
452
        }
453
        $rs->close();
454
 
455
        // Need to correct the grade category path and parent
456
        $conditions = array(
457
            'courseid' => $this->get_courseid()
458
        );
459
 
460
        $rs = $DB->get_recordset('grade_categories', $conditions);
461
        // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
462
        foreach ($rs as $gc) {
463
            if (!empty($gc->parent)) {
464
                $grade_category = new stdClass();
465
                $grade_category->id = $gc->id;
466
                $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
467
                $DB->update_record('grade_categories', $grade_category);
468
            }
469
        }
470
        $rs->close();
471
 
472
        // Now we can rebuild all the paths
473
        $rs = $DB->get_recordset('grade_categories', $conditions);
474
        foreach ($rs as $gc) {
475
            $grade_category = new stdClass();
476
            $grade_category->id = $gc->id;
477
            $grade_category->path = grade_category::build_path($gc);
478
            $grade_category->depth = substr_count($grade_category->path, '/') - 1;
479
            $DB->update_record('grade_categories', $grade_category);
480
        }
481
        $rs->close();
482
 
483
        // Check what to do with the minmaxtouse setting.
484
        $this->check_minmaxtouse();
485
 
486
        // Freeze gradebook calculations if needed.
487
        $this->gradebook_calculation_freeze();
488
 
489
        // Ensure the module cache is current when recalculating grades.
490
        rebuild_course_cache($this->get_courseid(), true);
491
 
492
        // Restore marks items as needing update. Update everything now.
493
        grade_regrade_final_grades($this->get_courseid());
494
    }
495
 
496
    /**
497
     * Freeze gradebook calculation if needed.
498
     *
499
     * This is similar to various upgrade scripts that check if the freeze is needed.
500
     */
501
    protected function gradebook_calculation_freeze() {
502
        global $CFG;
503
        $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
504
        $restoretask = $this->get_task();
505
 
506
        // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
507
        if (!$gradebookcalculationsfreeze && $restoretask->backup_version_compare(20141110, '>=')
508
                && $restoretask->backup_version_compare(20150619, '<')) {
509
            require_once($CFG->libdir . '/db/upgradelib.php');
510
            upgrade_extra_credit_weightoverride($this->get_courseid());
511
        }
512
        // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
513
        if (!$gradebookcalculationsfreeze && $restoretask->backup_version_compare(20141110, '>=')
514
                && $restoretask->backup_version_compare(20150627, '<')) {
515
            require_once($CFG->libdir . '/db/upgradelib.php');
516
            upgrade_calculated_grade_items($this->get_courseid());
517
        }
518
        // Courses from before 3.1 (20160518) may have a letter boundary problem and should be checked for this issue.
519
        // Backups from before and including 2.9 could have a build number that is greater than 20160518 and should
520
        // be checked for this problem.
521
        if (!$gradebookcalculationsfreeze
522
                && ($restoretask->backup_version_compare(20160518, '<') || $restoretask->backup_release_compare('2.9', '<='))) {
523
            require_once($CFG->libdir . '/db/upgradelib.php');
524
            upgrade_course_letter_boundary($this->get_courseid());
525
        }
526
 
527
    }
528
 
529
    /**
530
     * Checks what should happen with the course grade setting minmaxtouse.
531
     *
532
     * This is related to the upgrade step at the time the setting was added.
533
     *
534
     * @see MDL-48618
535
     * @return void
536
     */
537
    protected function check_minmaxtouse() {
538
        global $CFG, $DB;
539
        require_once($CFG->libdir . '/gradelib.php');
540
 
541
        $userinfo = $this->task->get_setting_value('users');
542
        $settingname = 'minmaxtouse';
543
        $courseid = $this->get_courseid();
544
        $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
545
        $version28start = 2014111000.00;
546
        $version28last = 2014111006.05;
547
        $version29start = 2015051100.00;
548
        $version29last = 2015060400.02;
549
 
550
        $target = $this->get_task()->get_target();
551
        if ($minmaxtouse === false &&
552
                ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
553
            // The setting was not found because this setting did not exist at the time the backup was made.
554
            // And we are not restoring as merge, in which case we leave the course as it was.
555
            $version = $this->get_task()->get_info()->moodle_version;
556
 
557
            if ($version < $version28start) {
558
                // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
559
                if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
560
                    grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
561
                }
562
 
563
            } else if (($version >= $version28start && $version < $version28last) ||
564
                    ($version >= $version29start && $version < $version29last)) {
565
                // They should be using grade_grade when the course has inconsistencies.
566
 
567
                $sql = "SELECT gi.id
568
                          FROM {grade_items} gi
569
                          JOIN {grade_grades} gg
570
                            ON gg.itemid = gi.id
571
                         WHERE gi.courseid = ?
572
                           AND (gi.itemtype != ? AND gi.itemtype != ?)
573
                           AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
574
 
575
                // The course can only have inconsistencies when we restore the user info,
576
                // we do not need to act on existing grades that were not restored as part of this backup.
577
                if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
578
 
579
                    // Display the notice as we do during upgrade.
580
                    set_config('show_min_max_grades_changed_' . $courseid, 1);
581
 
582
                    if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
583
                        // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
584
                        // If they are using the site-wide grade_grade setting, we only want to notice them.
585
                        grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
586
                    }
587
                }
588
 
589
            } else {
590
                // This should never happen because from now on minmaxtouse is always saved in backups.
591
            }
592
        }
593
    }
594
 
595
    /**
596
     * Rewrite step definition to handle the legacy freeze attribute.
597
     *
598
     * In previous backups the calculations_freeze property was stored as an attribute of the
599
     * top level node <gradebook>. The backup API, however, do not process grandparent nodes.
600
     * It only processes definitive children, and their parent attributes.
601
     *
602
     * We had:
603
     *
604
     * <gradebook calculations_freeze="20160511">
605
     *   <grade_categories>
606
     *     <grade_category id="10">
607
     *       <depth>1</depth>
608
     *       ...
609
     *     </grade_category>
610
     *   </grade_categories>
611
     *   ...
612
     * </gradebook>
613
     *
614
     * And this method will convert it to:
615
     *
616
     * <gradebook >
617
     *   <attributes>
618
     *     <calculations_freeze>20160511</calculations_freeze>
619
     *   </attributes>
620
     *   <grade_categories>
621
     *     <grade_category id="10">
622
     *       <depth>1</depth>
623
     *       ...
624
     *     </grade_category>
625
     *   </grade_categories>
626
     *   ...
627
     * </gradebook>
628
     *
629
     * Note that we cannot just load the XML file in memory as it could potentially be huge.
630
     * We can also completely ignore if the node <attributes> is already in the backup
631
     * file as it never existed before.
632
     *
633
     * @param string $filepath The absolute path to the XML file.
634
     * @return void
635
     */
636
    protected function rewrite_step_backup_file_for_legacy_freeze($filepath) {
637
        $foundnode = false;
638
        $newfile = make_request_directory(true) . DIRECTORY_SEPARATOR . 'file.xml';
639
        $fr = fopen($filepath, 'r');
640
        $fw = fopen($newfile, 'w');
641
        if ($fr && $fw) {
642
            while (($line = fgets($fr, 4096)) !== false) {
643
                if (!$foundnode && strpos($line, '<gradebook ') === 0) {
644
                    $foundnode = true;
645
                    $matches = array();
646
                    $pattern = '@calculations_freeze=.([0-9]+).@';
647
                    if (preg_match($pattern, $line, $matches)) {
648
                        $freeze = $matches[1];
649
                        $line = preg_replace($pattern, '', $line);
650
                        $line .= "  <attributes>\n    <calculations_freeze>$freeze</calculations_freeze>\n  </attributes>\n";
651
                    }
652
                }
653
                fputs($fw, $line);
654
            }
655
            if (!feof($fr)) {
656
                throw new restore_step_exception('Error while attempting to rewrite the gradebook step file.');
657
            }
658
            fclose($fr);
659
            fclose($fw);
660
            if (!rename($newfile, $filepath)) {
661
                throw new restore_step_exception('Error while attempting to rename the gradebook step file.');
662
            }
663
        } else {
664
            if ($fr) {
665
                fclose($fr);
666
            }
667
            if ($fw) {
668
                fclose($fw);
669
            }
670
        }
671
    }
672
 
673
}
674
 
675
/**
676
 * Step in charge of restoring the grade history of a course.
677
 *
678
 * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
679
 * we do not want to restore the history if the gradebook and its content has not been
680
 * restored. At least for now.
681
 */
682
class restore_grade_history_structure_step extends restore_structure_step {
683
 
684
     protected function execute_condition() {
685
        global $CFG, $DB;
686
 
687
        if ($this->get_courseid() == SITEID) {
688
            return false;
689
        }
690
 
691
        // No gradebook info found, don't execute.
692
        $fullpath = $this->task->get_taskbasepath();
693
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
694
        if (!file_exists($fullpath)) {
695
            return false;
696
        }
697
 
698
        // Some module present in backup file isn't available to restore in this site, don't execute.
699
        if ($this->task->is_missing_modules()) {
700
            return false;
701
        }
702
 
703
        // Some activity has been excluded to be restored, don't execute.
704
        if ($this->task->is_excluding_activities()) {
705
            return false;
706
        }
707
 
708
        // There should only be one grade category (the 1 associated with the course itself).
709
        $category = new stdclass();
710
        $category->courseid  = $this->get_courseid();
711
        $catcount = $DB->count_records('grade_categories', (array)$category);
712
        if ($catcount > 1) {
713
            return false;
714
        }
715
 
716
        // Arrived here, execute the step.
717
        return true;
718
     }
719
 
720
    protected function define_structure() {
721
        $paths = array();
722
 
723
        // Settings to use.
724
        $userinfo = $this->get_setting_value('users');
725
        $history = $this->get_setting_value('grade_histories');
726
 
727
        if ($userinfo && $history) {
728
            $paths[] = new restore_path_element('grade_grade',
729
               '/grade_history/grade_grades/grade_grade');
730
        }
731
 
732
        return $paths;
733
    }
734
 
735
    protected function process_grade_grade($data) {
736
        global $DB;
737
 
738
        $data = (object)($data);
739
        $olduserid = $data->userid;
740
        unset($data->id);
741
 
742
        $data->userid = $this->get_mappingid('user', $data->userid, null);
743
        if (!empty($data->userid)) {
744
            // Do not apply the date offsets as this is history.
745
            $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
746
            $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
747
            $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
748
            $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
749
            $DB->insert_record('grade_grades_history', $data);
750
        } else {
751
            $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
752
            $this->log($message, backup::LOG_DEBUG);
753
        }
754
    }
755
 
756
}
757
 
758
/**
759
 * decode all the interlinks present in restored content
760
 * relying 100% in the restore_decode_processor that handles
761
 * both the contents to modify and the rules to be applied
762
 */
763
class restore_decode_interlinks extends restore_execution_step {
764
 
765
    protected function define_execution() {
766
        // Get the decoder (from the plan)
767
        /** @var restore_decode_processor $decoder */
768
        $decoder = $this->task->get_decoder();
769
        restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
770
        // And launch it, everything will be processed
771
        $decoder->execute();
772
    }
773
}
774
 
775
/**
776
 * first, ensure that we have no gaps in section numbers
777
 * and then, rebuid the course cache
778
 */
779
class restore_rebuild_course_cache extends restore_execution_step {
780
 
781
    protected function define_execution() {
782
        global $DB;
783
 
784
        // Although there is some sort of auto-recovery of missing sections
785
        // present in course/formats... here we check that all the sections
786
        // from 0 to MAX(section->section) exist, creating them if necessary
787
        $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
788
        // Iterate over all sections
789
        for ($i = 0; $i <= $maxsection; $i++) {
790
            // If the section $i doesn't exist, create it
791
            if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
792
                $sectionrec = array(
793
                    'course' => $this->get_courseid(),
794
                    'section' => $i,
795
                    'timemodified' => time());
796
                $DB->insert_record('course_sections', $sectionrec); // missing section created
797
            }
798
        }
799
 
800
        // Rebuild cache now that all sections are in place
801
        rebuild_course_cache($this->get_courseid());
802
        cache_helper::purge_by_event('changesincourse');
803
        cache_helper::purge_by_event('changesincoursecat');
804
    }
805
}
806
 
807
/**
808
 * Review all the tasks having one after_restore method
809
 * executing it to perform some final adjustments of information
810
 * not available when the task was executed.
811
 */
812
class restore_execute_after_restore extends restore_execution_step {
813
 
814
    protected function define_execution() {
815
 
816
        // Simply call to the execute_after_restore() method of the task
817
        // that always is the restore_final_task
818
        $this->task->launch_execute_after_restore();
819
    }
820
}
821
 
822
 
823
/**
824
 * Review all the (pending) block positions in backup_ids, matching by
825
 * contextid, creating positions as needed. This is executed by the
826
 * final task, once all the contexts have been created
827
 */
828
class restore_review_pending_block_positions extends restore_execution_step {
829
 
830
    protected function define_execution() {
831
        global $DB;
832
 
833
        // Get all the block_position objects pending to match
834
        $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
835
        $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
836
        // Process block positions, creating them or accumulating for final step
837
        foreach($rs as $posrec) {
838
            // Get the complete position object out of the info field.
839
            $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
840
            // If position is for one already mapped (known) contextid
841
            // process it now, creating the position, else nothing to
842
            // do, position finally discarded
843
            if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
844
                $position->contextid = $newctx->newitemid;
845
                // Create the block position
846
                $DB->insert_record('block_positions', $position);
847
            }
848
        }
849
        $rs->close();
850
    }
851
}
852
 
853
 
854
/**
855
 * Updates the availability data for course modules and sections.
856
 *
857
 * Runs after the restore of all course modules, sections, and grade items has
858
 * completed. This is necessary in order to update IDs that have changed during
859
 * restore.
860
 *
861
 * @package core_backup
862
 * @copyright 2014 The Open University
863
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
864
 */
865
class restore_update_availability extends restore_execution_step {
866
 
867
    protected function define_execution() {
868
        global $CFG, $DB;
869
 
870
        // Note: This code runs even if availability is disabled when restoring.
871
        // That will ensure that if you later turn availability on for the site,
872
        // there will be no incorrect IDs. (It doesn't take long if the restored
873
        // data does not contain any availability information.)
874
 
875
        // Get modinfo with all data after resetting cache.
876
        rebuild_course_cache($this->get_courseid(), true);
877
        $modinfo = get_fast_modinfo($this->get_courseid());
878
 
879
        // Get the date offset for this restore.
880
        $dateoffset = $this->apply_date_offset(1) - 1;
881
 
882
        // Update all sections that were restored.
883
        $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
884
        $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
885
        $sectionsbyid = null;
886
        foreach ($rs as $rec) {
887
            if (is_null($sectionsbyid)) {
888
                $sectionsbyid = array();
889
                foreach ($modinfo->get_section_info_all() as $section) {
890
                    $sectionsbyid[$section->id] = $section;
891
                }
892
            }
893
            if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
894
                // If the section was not fully restored for some reason
895
                // (e.g. due to an earlier error), skip it.
896
                $this->get_logger()->process('Section not fully restored: id ' .
897
                        $rec->newitemid, backup::LOG_WARNING);
898
                continue;
899
            }
900
            $section = $sectionsbyid[$rec->newitemid];
901
            if (!is_null($section->availability)) {
902
                $info = new \core_availability\info_section($section);
903
                $info->update_after_restore($this->get_restoreid(),
904
                        $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
905
            }
906
        }
907
        $rs->close();
908
 
909
        // Update all modules that were restored.
910
        $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
911
        $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
912
        foreach ($rs as $rec) {
913
            if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
914
                // If the module was not fully restored for some reason
915
                // (e.g. due to an earlier error), skip it.
916
                $this->get_logger()->process('Module not fully restored: id ' .
917
                        $rec->newitemid, backup::LOG_WARNING);
918
                continue;
919
            }
920
            $cm = $modinfo->get_cm($rec->newitemid);
921
            if (!is_null($cm->availability)) {
922
                $info = new \core_availability\info_module($cm);
923
                $info->update_after_restore($this->get_restoreid(),
924
                        $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
925
            }
926
        }
927
        $rs->close();
928
    }
929
}
930
 
931
 
932
/**
933
 * Process legacy module availability records in backup_ids.
934
 *
935
 * Matches course modules and grade item id once all them have been already restored.
936
 * Only if all matchings are satisfied the availability condition will be created.
937
 * At the same time, it is required for the site to have that functionality enabled.
938
 *
939
 * This step is included only to handle legacy backups (2.6 and before). It does not
940
 * do anything for newer backups.
941
 *
942
 * @copyright 2014 The Open University
943
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
944
 */
945
class restore_process_course_modules_availability extends restore_execution_step {
946
 
947
    protected function define_execution() {
948
        global $CFG, $DB;
949
 
950
        // Site hasn't availability enabled
951
        if (empty($CFG->enableavailability)) {
952
            return;
953
        }
954
 
955
        // Do both modules and sections.
956
        foreach (array('module', 'section') as $table) {
957
            // Get all the availability objects to process.
958
            $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
959
            $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
960
            // Process availabilities, creating them if everything matches ok.
961
            foreach ($rs as $availrec) {
962
                $allmatchesok = true;
963
                // Get the complete legacy availability object.
964
                $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
965
 
966
                // Note: This code used to update IDs, but that is now handled by the
967
                // current code (after restore) instead of this legacy code.
968
 
969
                // Get showavailability option.
970
                $thingid = ($table === 'module') ? $availability->coursemoduleid :
971
                        $availability->coursesectionid;
972
                $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
973
                        $table . '_showavailability', $thingid);
974
                if (!$showrec) {
975
                    // Should not happen.
976
                    throw new coding_exception('No matching showavailability record');
977
                }
978
                $show = $showrec->info->showavailability;
979
 
980
                // The $availability object is now in the format used in the old
981
                // system. Interpret this and convert to new system.
982
                $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
983
                        array('id' => $thingid), MUST_EXIST);
984
                $newvalue = \core_availability\info::add_legacy_availability_condition(
985
                        $currentvalue, $availability, $show);
986
                $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
987
                        array('id' => $thingid));
988
            }
989
            $rs->close();
990
        }
991
    }
992
}
993
 
994
 
995
/*
996
 * Execution step that, *conditionally* (if there isn't preloaded information)
997
 * will load the inforef files for all the included course/section/activity tasks
998
 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
999
 */
1000
class restore_load_included_inforef_records extends restore_execution_step {
1001
 
1002
    protected function define_execution() {
1003
 
1004
        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1005
            return;
1006
        }
1007
 
1008
        // Get all the included tasks
1009
        $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
1010
        $progress = $this->task->get_progress();
1011
        $progress->start_progress($this->get_name(), count($tasks));
1012
        foreach ($tasks as $task) {
1013
            // Load the inforef.xml file if exists
1014
            $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
1015
            if (file_exists($inforefpath)) {
1016
                // Load each inforef file to temp_ids.
1017
                restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
1018
            }
1019
        }
1020
        $progress->end_progress();
1021
    }
1022
}
1023
 
1024
/*
1025
 * Execution step that will load all the needed files into backup_files_temp
1026
 *   - info: contains the whole original object (times, names...)
1027
 * (all them being original ids as loaded from xml)
1028
 */
1029
class restore_load_included_files extends restore_structure_step {
1030
 
1031
    protected function define_structure() {
1032
 
1033
        $file = new restore_path_element('file', '/files/file');
1034
 
1035
        return array($file);
1036
    }
1037
 
1038
    /**
1039
     * Process one <file> element from files.xml
1040
     *
1041
     * @param array $data the element data
1042
     */
1043
    public function process_file($data) {
1044
 
1045
        $data = (object)$data; // handy
1046
 
1047
        // load it if needed:
1048
        //   - it it is one of the annotated inforef files (course/section/activity/block)
1049
        //   - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
1050
        // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
1051
        //       but then we'll need to change it to load plugins itself (because this is executed too early in restore)
1052
        $isfileref   = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
1053
        $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
1054
                        $data->component == 'grouping' || $data->component == 'grade' ||
1055
                        $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
1056
        if ($isfileref || $iscomponent) {
1057
            restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
1058
        }
1059
    }
1060
}
1061
 
1062
/**
1063
 * Execution step that, *conditionally* (if there isn't preloaded information),
1064
 * will load all the needed roles to backup_temp_ids. They will be stored with
1065
 * "role" itemname. Also it will perform one automatic mapping to roles existing
1066
 * in the target site, based in permissions of the user performing the restore,
1067
 * archetypes and other bits. At the end, each original role will have its associated
1068
 * target role or 0 if it's going to be skipped. Note we wrap everything over one
1069
 * restore_dbops method, as far as the same stuff is going to be also executed
1070
 * by restore prechecks
1071
 */
1072
class restore_load_and_map_roles extends restore_execution_step {
1073
 
1074
    protected function define_execution() {
1075
        if ($this->task->get_preloaded_information()) { // if info is already preloaded
1076
            return;
1077
        }
1078
 
1079
        $file = $this->get_basepath() . '/roles.xml';
1080
        // Load needed toles to temp_ids
1081
        restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
1082
 
1083
        // Process roles, mapping/skipping. Any error throws exception
1084
        // Note we pass controller's info because it can contain role mapping information
1085
        // about manual mappings performed by UI
1086
        restore_dbops::process_included_roles($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_info()->role_mappings);
1087
    }
1088
}
1089
 
1090
/**
1091
 * Execution step that, *conditionally* (if there isn't preloaded information
1092
 * and users have been selected in settings, will load all the needed users
1093
 * to backup_temp_ids. They will be stored with "user" itemname and with
1094
 * their original contextid as paremitemid
1095
 */
1096
class restore_load_included_users extends restore_execution_step {
1097
 
1098
    protected function define_execution() {
1099
 
1100
        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1101
            return;
1102
        }
1103
        if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1104
            return;
1105
        }
1106
        $file = $this->get_basepath() . '/users.xml';
1107
        // Load needed users to temp_ids.
1108
        restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
1109
    }
1110
}
1111
 
1112
/**
1113
 * Execution step that, *conditionally* (if there isn't preloaded information
1114
 * and users have been selected in settings, will process all the needed users
1115
 * in order to decide and perform any action with them (create / map / error)
1116
 * Note: Any error will cause exception, as far as this is the same processing
1117
 * than the one into restore prechecks (that should have stopped process earlier)
1118
 */
1119
class restore_process_included_users extends restore_execution_step {
1120
 
1121
    protected function define_execution() {
1122
 
1123
        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1124
            return;
1125
        }
1126
        if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1127
            return;
1128
        }
1129
        restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
1130
                $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
1131
    }
1132
}
1133
 
1134
/**
1135
 * Execution step that will create all the needed users as calculated
1136
 * by @restore_process_included_users (those having newiteind = 0)
1137
 */
1138
class restore_create_included_users extends restore_execution_step {
1139
 
1140
    protected function define_execution() {
1141
 
1142
        restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
1143
                $this->task->get_userid(), $this->task->get_progress(), $this->task->get_courseid());
1144
    }
1145
}
1146
 
1147
/**
1148
 * Structure step that will create all the needed groups and groupings
1149
 * by loading them from the groups.xml file performing the required matches.
1150
 * Note group members only will be added if restoring user info
1151
 */
1152
class restore_groups_structure_step extends restore_structure_step {
1153
 
1154
    protected function define_structure() {
1155
 
1156
        $paths = array(); // Add paths here
1157
 
1158
        // Do not include group/groupings information if not requested.
1159
        $groupinfo = $this->get_setting_value('groups');
1160
        if ($groupinfo) {
1161
            $paths[] = new restore_path_element('group', '/groups/group');
1162
            $paths[] = new restore_path_element('groupcustomfield', '/groups/groupcustomfields/groupcustomfield');
1163
            $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
1164
            $paths[] = new restore_path_element('groupingcustomfield',
1165
                '/groups/groupings/groupingcustomfields/groupingcustomfield');
1166
            $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
1167
        }
1168
        return $paths;
1169
    }
1170
 
1171
    // Processing functions go here
1172
    public function process_group($data) {
1173
        global $DB;
1174
 
1175
        $data = (object)$data; // handy
1176
        $data->courseid = $this->get_courseid();
1177
 
1178
        // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1179
        // another a group in the same course
1180
        $context = context_course::instance($data->courseid);
1181
        if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1182
            if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
1183
                unset($data->idnumber);
1184
            }
1185
        } else {
1186
            unset($data->idnumber);
1187
        }
1188
 
1189
        $oldid = $data->id;    // need this saved for later
1190
 
1191
        $restorefiles = false; // Only if we end creating the group
1192
 
1193
        // This is for backwards compatibility with old backups. If the backup data for a group contains a non-empty value of
1194
        // hidepicture, then we'll exclude this group's picture from being restored.
1195
        if (!empty($data->hidepicture)) {
1196
            // Exclude the group picture from being restored if hidepicture is set to 1 in the backup data.
1197
            unset($data->picture);
1198
        }
1199
 
1200
        // Search if the group already exists (by name & description) in the target course
1201
        $description_clause = '';
1202
        $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1203
        if (!empty($data->description)) {
1204
            $description_clause = ' AND ' .
1205
                                  $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1206
           $params['description'] = $data->description;
1207
        }
1208
        if (!$groupdb = $DB->get_record_sql("SELECT *
1209
                                               FROM {groups}
1210
                                              WHERE courseid = :courseid
1211
                                                AND name = :grname $description_clause", $params)) {
1212
            // group doesn't exist, create
1213
            $newitemid = $DB->insert_record('groups', $data);
1214
            $restorefiles = true; // We'll restore the files
1215
        } else {
1216
            // group exists, use it
1217
            $newitemid = $groupdb->id;
1218
        }
1219
        // Save the id mapping
1220
        $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
1221
 
1222
        // Add the related group picture file if it's available at this point.
1223
        if (!empty($data->picture)) {
1224
            $this->add_related_files('group', 'icon', 'group', null, $oldid);
1225
        }
1226
 
1227
        // Invalidate the course group data cache just in case.
1228
        cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1229
    }
1230
 
1231
    /**
1232
     * Restore group custom field values.
1233
     * @param array $data data for group custom field
1234
     * @return void
1235
     */
1236
    public function process_groupcustomfield($data) {
1237
        $newgroup = $this->get_mapping('group', $data['groupid']);
1238
        $data['groupid'] = $newgroup->newitemid ?? $data['groupid'];
1239
        $handler = \core_group\customfield\group_handler::create();
1240
        $handler->restore_instance_data_from_backup($this->task, $data);
1241
    }
1242
 
1243
    public function process_grouping($data) {
1244
        global $DB;
1245
 
1246
        $data = (object)$data; // handy
1247
        $data->courseid = $this->get_courseid();
1248
 
1249
        // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1250
        // another a grouping in the same course
1251
        $context = context_course::instance($data->courseid);
1252
        if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1253
            if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
1254
                unset($data->idnumber);
1255
            }
1256
        } else {
1257
            unset($data->idnumber);
1258
        }
1259
 
1260
        $oldid = $data->id;    // need this saved for later
1261
        $restorefiles = false; // Only if we end creating the grouping
1262
 
1263
        // Search if the grouping already exists (by name & description) in the target course
1264
        $description_clause = '';
1265
        $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1266
        if (!empty($data->description)) {
1267
            $description_clause = ' AND ' .
1268
                                  $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1269
           $params['description'] = $data->description;
1270
        }
1271
        if (!$groupingdb = $DB->get_record_sql("SELECT *
1272
                                                  FROM {groupings}
1273
                                                 WHERE courseid = :courseid
1274
                                                   AND name = :grname $description_clause", $params)) {
1275
            // grouping doesn't exist, create
1276
            $newitemid = $DB->insert_record('groupings', $data);
1277
            $restorefiles = true; // We'll restore the files
1278
        } else {
1279
            // grouping exists, use it
1280
            $newitemid = $groupingdb->id;
1281
        }
1282
        // Save the id mapping
1283
        $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1284
        // Invalidate the course group data cache just in case.
1285
        cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1286
    }
1287
 
1288
    /**
1289
     * Restore grouping custom field values.
1290
     * @param array $data data for grouping custom field
1291
     * @return void
1292
     */
1293
    public function process_groupingcustomfield($data) {
1294
        $newgroup = $this->get_mapping('grouping', $data['groupingid']);
1295
        $data['groupingid'] = $newgroup->newitemid ?? $data['groupingid'];
1296
        $handler = \core_group\customfield\grouping_handler::create();
1297
        $handler->restore_instance_data_from_backup($this->task, $data);
1298
    }
1299
 
1300
    public function process_grouping_group($data) {
1301
        global $CFG;
1302
 
1303
        require_once($CFG->dirroot.'/group/lib.php');
1304
 
1305
        $data = (object)$data;
1306
        groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
1307
    }
1308
 
1309
    protected function after_execute() {
1310
        // Add group related files, matching with "group" mappings.
1311
        $this->add_related_files('group', 'description', 'group');
1312
        // Add grouping related files, matching with "grouping" mappings
1313
        $this->add_related_files('grouping', 'description', 'grouping');
1314
        // Invalidate the course group data.
1315
        cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1316
    }
1317
 
1318
}
1319
 
1320
/**
1321
 * Structure step that will create all the needed group memberships
1322
 * by loading them from the groups.xml file performing the required matches.
1323
 */
1324
class restore_groups_members_structure_step extends restore_structure_step {
1325
 
1326
    protected $plugins = null;
1327
 
1328
    protected function define_structure() {
1329
 
1330
        $paths = array(); // Add paths here
1331
 
1332
        if ($this->get_setting_value('groups') && $this->get_setting_value('users')) {
1333
            $paths[] = new restore_path_element('group', '/groups/group');
1334
            $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1335
        }
1336
 
1337
        return $paths;
1338
    }
1339
 
1340
    public function process_group($data) {
1341
        $data = (object)$data; // handy
1342
 
1343
        // HACK ALERT!
1344
        // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1345
        // Let's fake internal state to make $this->get_new_parentid('group') work.
1346
 
1347
        $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1348
    }
1349
 
1350
    public function process_member($data) {
1351
        global $DB, $CFG;
1352
        require_once("$CFG->dirroot/group/lib.php");
1353
 
1354
        // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1355
 
1356
        $data = (object)$data; // handy
1357
 
1358
        // get parent group->id
1359
        $data->groupid = $this->get_new_parentid('group');
1360
 
1361
        // map user newitemid and insert if not member already
1362
        if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1363
            if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1364
                // Check the component, if any, exists.
1365
                if (empty($data->component)) {
1366
                    groups_add_member($data->groupid, $data->userid);
1367
 
1368
                } else if ((strpos($data->component, 'enrol_') === 0)) {
1369
                    // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1370
                    // it is possible that enrolment was restored using different plugin type.
1371
                    if (!isset($this->plugins)) {
1372
                        $this->plugins = enrol_get_plugins(true);
1373
                    }
1374
                    if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1375
                        if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1376
                            if (isset($this->plugins[$instance->enrol])) {
1377
                                $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1378
                            }
1379
                        }
1380
                    }
1381
 
1382
                } else {
1383
                    $dir = core_component::get_component_directory($data->component);
1384
                    if ($dir and is_dir($dir)) {
1385
                        if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1386
                            return;
1387
                        }
1388
                    }
1389
                    // Bad luck, plugin could not restore the data, let's add normal membership.
1390
                    groups_add_member($data->groupid, $data->userid);
1391
                    $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1392
                    $this->log($message, backup::LOG_WARNING);
1393
                }
1394
            }
1395
        }
1396
    }
1397
}
1398
 
1399
/**
1400
 * Structure step that will create all the needed scales
1401
 * by loading them from the scales.xml
1402
 */
1403
class restore_scales_structure_step extends restore_structure_step {
1404
 
1405
    protected function define_structure() {
1406
 
1407
        $paths = array(); // Add paths here
1408
        $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1409
        return $paths;
1410
    }
1411
 
1412
    protected function process_scale($data) {
1413
        global $DB;
1414
 
1415
        $data = (object)$data;
1416
 
1417
        $restorefiles = false; // Only if we end creating the group
1418
 
1419
        $oldid = $data->id;    // need this saved for later
1420
 
1421
        // Look for scale (by 'scale' both in standard (course=0) and current course
1422
        // with priority to standard scales (ORDER clause)
1423
        // scale is not course unique, use get_record_sql to suppress warning
1424
        // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1425
        $compare_scale_clause = $DB->sql_compare_text('scale')  . ' = ' . $DB->sql_compare_text(':scaledesc');
1426
        $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1427
        if (!$scadb = $DB->get_record_sql("SELECT *
1428
                                            FROM {scale}
1429
                                           WHERE courseid IN (0, :courseid)
1430
                                             AND $compare_scale_clause
1431
                                        ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1432
            // Remap the user if possible, defaut to user performing the restore if not
1433
            $userid = $this->get_mappingid('user', $data->userid);
1434
            $data->userid = $userid ? $userid : $this->task->get_userid();
1435
            // Remap the course if course scale
1436
            $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1437
            // If global scale (course=0), check the user has perms to create it
1438
            // falling to course scale if not
1439
            $systemctx = context_system::instance();
1440
            if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1441
                $data->courseid = $this->get_courseid();
1442
            }
1443
            // scale doesn't exist, create
1444
            $newitemid = $DB->insert_record('scale', $data);
1445
            $restorefiles = true; // We'll restore the files
1446
        } else {
1447
            // scale exists, use it
1448
            $newitemid = $scadb->id;
1449
        }
1450
        // Save the id mapping (with files support at system context)
1451
        $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1452
    }
1453
 
1454
    protected function after_execute() {
1455
        // Add scales related files, matching with "scale" mappings
1456
        $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1457
    }
1458
}
1459
 
1460
 
1461
/**
1462
 * Structure step that will create all the needed outocomes
1463
 * by loading them from the outcomes.xml
1464
 */
1465
class restore_outcomes_structure_step extends restore_structure_step {
1466
 
1467
    protected function define_structure() {
1468
 
1469
        $paths = array(); // Add paths here
1470
        $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1471
        return $paths;
1472
    }
1473
 
1474
    protected function process_outcome($data) {
1475
        global $DB;
1476
 
1477
        $data = (object)$data;
1478
 
1479
        $restorefiles = false; // Only if we end creating the group
1480
 
1481
        $oldid = $data->id;    // need this saved for later
1482
 
1483
        // Look for outcome (by shortname both in standard (courseid=null) and current course
1484
        // with priority to standard outcomes (ORDER clause)
1485
        // outcome is not course unique, use get_record_sql to suppress warning
1486
        $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1487
        if (!$outdb = $DB->get_record_sql('SELECT *
1488
                                             FROM {grade_outcomes}
1489
                                            WHERE shortname = :shortname
1490
                                              AND (courseid = :courseid OR courseid IS NULL)
1491
                                         ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1492
            // Remap the user
1493
            $userid = $this->get_mappingid('user', $data->usermodified);
1494
            $data->usermodified = $userid ? $userid : $this->task->get_userid();
1495
            // Remap the scale
1496
            $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1497
            // Remap the course if course outcome
1498
            $data->courseid = $data->courseid ? $this->get_courseid() : null;
1499
            // If global outcome (course=null), check the user has perms to create it
1500
            // falling to course outcome if not
1501
            $systemctx = context_system::instance();
1502
            if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1503
                $data->courseid = $this->get_courseid();
1504
            }
1505
            // outcome doesn't exist, create
1506
            $newitemid = $DB->insert_record('grade_outcomes', $data);
1507
            $restorefiles = true; // We'll restore the files
1508
        } else {
1509
            // scale exists, use it
1510
            $newitemid = $outdb->id;
1511
        }
1512
        // Set the corresponding grade_outcomes_courses record
1513
        $outcourserec = new stdclass();
1514
        $outcourserec->courseid  = $this->get_courseid();
1515
        $outcourserec->outcomeid = $newitemid;
1516
        if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1517
            $DB->insert_record('grade_outcomes_courses', $outcourserec);
1518
        }
1519
        // Save the id mapping (with files support at system context)
1520
        $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1521
    }
1522
 
1523
    protected function after_execute() {
1524
        // Add outcomes related files, matching with "outcome" mappings
1525
        $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1526
    }
1527
}
1528
 
1529
/**
1530
 * Execution step that, *conditionally* (if there isn't preloaded information
1531
 * will load all the question categories and questions (header info only)
1532
 * to backup_temp_ids. They will be stored with "question_category" and
1533
 * "question" itemnames and with their original contextid and question category
1534
 * id as paremitemids
1535
 */
1536
class restore_load_categories_and_questions extends restore_execution_step {
1537
 
1538
    protected function define_execution() {
1539
 
1540
        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1541
            return;
1542
        }
1543
        $file = $this->get_basepath() . '/questions.xml';
1544
        restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1545
    }
1546
}
1547
 
1548
/**
1549
 * Execution step that, *conditionally* (if there isn't preloaded information)
1550
 * will process all the needed categories and questions
1551
 * in order to decide and perform any action with them (create / map / error)
1552
 * Note: Any error will cause exception, as far as this is the same processing
1553
 * than the one into restore prechecks (that should have stopped process earlier)
1554
 */
1555
class restore_process_categories_and_questions extends restore_execution_step {
1556
 
1557
    protected function define_execution() {
1558
 
1559
        if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1560
            return;
1561
        }
1562
        restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1563
    }
1564
}
1565
 
1566
/**
1567
 * Structure step that will read the section.xml creating/updating sections
1568
 * as needed, rebuilding course cache and other friends
1569
 */
1570
class restore_section_structure_step extends restore_structure_step {
1571
    /** @var array Cache: Array of id => course format */
1572
    private static $courseformats = array();
1573
 
1574
    /**
1575
     * Resets a static cache of course formats. Required for unit testing.
1576
     */
1577
    public static function reset_caches() {
1578
        self::$courseformats = array();
1579
    }
1580
 
1581
    protected function define_structure() {
1582
        global $CFG;
1583
 
1584
        $paths = array();
1585
 
1586
        $section = new restore_path_element('section', '/section');
1587
        $paths[] = $section;
1588
        if ($CFG->enableavailability) {
1589
            $paths[] = new restore_path_element('availability', '/section/availability');
1590
            $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1591
        }
1592
        $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1593
 
1594
        // Apply for 'format' plugins optional paths at section level
1595
        $this->add_plugin_structure('format', $section);
1596
 
1597
        // Apply for 'local' plugins optional paths at section level
1598
        $this->add_plugin_structure('local', $section);
1599
 
1600
        return $paths;
1601
    }
1602
 
1603
    public function process_section($data) {
1604
        global $CFG, $DB;
1605
        $data = (object)$data;
1606
        $oldid = $data->id; // We'll need this later
1607
 
1608
        $restorefiles = false;
1609
 
1610
        // Look for the section
1611
        $section = new stdclass();
1612
        $section->course  = $this->get_courseid();
1613
        $section->section = $data->number;
1614
        $section->timemodified = $data->timemodified ?? 0;
1615
        // Section doesn't exist, create it with all the info from backup
1616
        if (!$secrec = $DB->get_record('course_sections', ['course' => $this->get_courseid(), 'section' => $data->number])) {
1617
            $section->name = $data->name;
1618
            $section->summary = $data->summary;
1619
            $section->summaryformat = $data->summaryformat;
1620
            $section->sequence = '';
1621
            $section->visible = $data->visible;
1622
            if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1623
                $section->availability = null;
1624
            } else {
1625
                $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1626
                // Include legacy [<2.7] availability data if provided.
1627
                if (is_null($section->availability)) {
1628
                    $section->availability = \core_availability\info::convert_legacy_fields(
1629
                            $data, true);
1630
                }
1631
            }
11 efrain 1632
            // Moodle 4.4 implement basic delegated section logic but it is not able to restore
1633
            // them from a backup. To prevent unexpected retoration errors, all sections with
1634
            // a component will be restored as a normal section.
1635
            $section->component = null;
1636
            $section->itemid = null;
1 efrain 1637
            $newitemid = $DB->insert_record('course_sections', $section);
1638
            $section->id = $newitemid;
1639
 
1640
            core\event\course_section_created::create_from_section($section)->trigger();
1641
 
1642
            $restorefiles = true;
1643
 
1644
        // Section exists, update non-empty information
1645
        } else {
1646
            $section->id = $secrec->id;
1647
            if ((string)$secrec->name === '') {
1648
                $section->name = $data->name;
1649
            }
1650
            if (empty($secrec->summary)) {
1651
                $section->summary = $data->summary;
1652
                $section->summaryformat = $data->summaryformat;
1653
                $restorefiles = true;
1654
            }
1655
 
1656
            // Don't update availability (I didn't see a useful way to define
1657
            // whether existing or new one should take precedence).
1658
 
1659
            $DB->update_record('course_sections', $section);
1660
            $newitemid = $secrec->id;
1661
 
1662
            // Trigger an event for course section update.
1663
            $event = \core\event\course_section_updated::create(
1664
                array(
1665
                    'objectid' => $section->id,
1666
                    'courseid' => $section->course,
1667
                    'context' => context_course::instance($section->course),
1668
                    'other' => array('sectionnum' => $section->section)
1669
                )
1670
            );
1671
            $event->trigger();
1672
        }
1673
 
1674
        // Annotate the section mapping, with restorefiles option if needed
1675
        $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1676
 
1677
        // set the new course_section id in the task
1678
        $this->task->set_sectionid($newitemid);
1679
 
1680
        // If there is the legacy showavailability data, store this for later use.
1681
        // (This data is not present when restoring 'new' backups.)
1682
        if (isset($data->showavailability)) {
1683
            // Cache the showavailability flag using the backup_ids data field.
1684
            restore_dbops::set_backup_ids_record($this->get_restoreid(),
1685
                    'section_showavailability', $newitemid, 0, null,
1686
                    (object)array('showavailability' => $data->showavailability));
1687
        }
1688
 
1689
        // Commented out. We never modify course->numsections as far as that is used
1690
        // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1691
        // Note: We keep the code here, to know about and because of the possibility of making this
1692
        // optional based on some setting/attribute in the future
1693
        // If needed, adjust course->numsections
1694
        //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1695
        //    if ($numsections < $section->section) {
1696
        //        $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1697
        //    }
1698
        //}
1699
    }
1700
 
1701
    /**
1702
     * Process the legacy availability table record. This table does not exist
1703
     * in Moodle 2.7+ but we still support restore.
1704
     *
1705
     * @param stdClass $data Record data
1706
     */
1707
    public function process_availability($data) {
1708
        $data = (object)$data;
1709
        // Simply going to store the whole availability record now, we'll process
1710
        // all them later in the final task (once all activities have been restored)
1711
        // Let's call the low level one to be able to store the whole object.
1712
        $data->coursesectionid = $this->task->get_sectionid();
1713
        restore_dbops::set_backup_ids_record($this->get_restoreid(),
1714
                'section_availability', $data->id, 0, null, $data);
1715
    }
1716
 
1717
    /**
1718
     * Process the legacy availability fields table record. This table does not
1719
     * exist in Moodle 2.7+ but we still support restore.
1720
     *
1721
     * @param stdClass $data Record data
1722
     */
1723
    public function process_availability_field($data) {
1724
        global $DB, $CFG;
1725
        require_once($CFG->dirroot.'/user/profile/lib.php');
1726
 
1727
        $data = (object)$data;
1728
        // Mark it is as passed by default
1729
        $passed = true;
1730
        $customfieldid = null;
1731
 
1732
        // If a customfield has been used in order to pass we must be able to match an existing
1733
        // customfield by name (data->customfield) and type (data->customfieldtype)
1734
        if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1735
            // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1736
            // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1737
            $passed = false;
1738
        } else if (!is_null($data->customfield)) {
1739
            $field = profile_get_custom_field_data_by_shortname($data->customfield);
1740
            $passed = $field && $field->datatype == $data->customfieldtype;
1741
        }
1742
 
1743
        if ($passed) {
1744
            // Create the object to insert into the database
1745
            $availfield = new stdClass();
1746
            $availfield->coursesectionid = $this->task->get_sectionid();
1747
            $availfield->userfield = $data->userfield;
1748
            $availfield->customfieldid = $customfieldid;
1749
            $availfield->operator = $data->operator;
1750
            $availfield->value = $data->value;
1751
 
1752
            // Get showavailability option.
1753
            $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1754
                    'section_showavailability', $availfield->coursesectionid);
1755
            if (!$showrec) {
1756
                // Should not happen.
1757
                throw new coding_exception('No matching showavailability record');
1758
            }
1759
            $show = $showrec->info->showavailability;
1760
 
1761
            // The $availfield object is now in the format used in the old
1762
            // system. Interpret this and convert to new system.
1763
            $currentvalue = $DB->get_field('course_sections', 'availability',
1764
                    array('id' => $availfield->coursesectionid), MUST_EXIST);
1765
            $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1766
                    $currentvalue, $availfield, $show);
1767
 
1768
            $section = new stdClass();
1769
            $section->id = $availfield->coursesectionid;
1770
            $section->availability = $newvalue;
1771
            $section->timemodified = time();
1772
            $DB->update_record('course_sections', $section);
1773
        }
1774
    }
1775
 
1776
    public function process_course_format_options($data) {
1777
        global $DB;
1778
        $courseid = $this->get_courseid();
1779
        if (!array_key_exists($courseid, self::$courseformats)) {
1780
            // It is safe to have a static cache of course formats because format can not be changed after this point.
1781
            self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1782
        }
1783
        $data = (array)$data;
1784
        if (self::$courseformats[$courseid] === $data['format']) {
1785
            // Import section format options only if both courses (the one that was backed up
1786
            // and the one we are restoring into) have same formats.
1787
            $params = array(
1788
                'courseid' => $this->get_courseid(),
1789
                'sectionid' => $this->task->get_sectionid(),
1790
                'format' => $data['format'],
1791
                'name' => $data['name']
1792
            );
1793
            if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1794
                // Do not overwrite existing information.
1795
                $newid = $record->id;
1796
            } else {
1797
                $params['value'] = $data['value'];
1798
                $newid = $DB->insert_record('course_format_options', $params);
1799
            }
1800
            $this->set_mapping('course_format_options', $data['id'], $newid);
1801
        }
1802
    }
1803
 
1804
    protected function after_execute() {
1805
        // Add section related files, with 'course_section' itemid to match
1806
        $this->add_related_files('course', 'section', 'course_section');
1807
    }
1808
}
1809
 
1810
/**
1811
 * Structure step that will read the course.xml file, loading it and performing
1812
 * various actions depending of the site/restore settings. Note that target
1813
 * course always exist before arriving here so this step will be updating
1814
 * the course record (never inserting)
1815
 */
1816
class restore_course_structure_step extends restore_structure_step {
1817
    /**
1818
     * @var bool this gets set to true by {@link process_course()} if we are
1819
     * restoring an old coures that used the legacy 'module security' feature.
1820
     * If so, we have to do more work in {@link after_execute()}.
1821
     */
1822
    protected $legacyrestrictmodules = false;
1823
 
1824
    /**
1825
     * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1826
     * array with array keys the module names ('forum', 'quiz', etc.). These are
1827
     * the modules that are allowed according to the data in the backup file.
1828
     * In {@link after_execute()} we then have to prevent adding of all the other
1829
     * types of activity.
1830
     */
1831
    protected $legacyallowedmodules = array();
1832
 
1833
    protected function define_structure() {
1834
 
1835
        $course = new restore_path_element('course', '/course');
1836
        $category = new restore_path_element('category', '/course/category');
1837
        $tag = new restore_path_element('tag', '/course/tags/tag');
1838
        $customfield = new restore_path_element('customfield', '/course/customfields/customfield');
1839
        $courseformatoptions = new restore_path_element('course_format_option', '/course/courseformatoptions/courseformatoption');
1840
        $allowedmodule = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1841
 
1842
        // Apply for 'format' plugins optional paths at course level
1843
        $this->add_plugin_structure('format', $course);
1844
 
1845
        // Apply for 'theme' plugins optional paths at course level
1846
        $this->add_plugin_structure('theme', $course);
1847
 
1848
        // Apply for 'report' plugins optional paths at course level
1849
        $this->add_plugin_structure('report', $course);
1850
 
1851
        // Apply for 'course report' plugins optional paths at course level
1852
        $this->add_plugin_structure('coursereport', $course);
1853
 
1854
        // Apply for plagiarism plugins optional paths at course level
1855
        $this->add_plugin_structure('plagiarism', $course);
1856
 
1857
        // Apply for local plugins optional paths at course level
1858
        $this->add_plugin_structure('local', $course);
1859
 
1860
        // Apply for admin tool plugins optional paths at course level.
1861
        $this->add_plugin_structure('tool', $course);
1862
 
1863
        return array($course, $category, $tag, $customfield, $allowedmodule, $courseformatoptions);
1864
    }
1865
 
1866
    /**
1867
     * Processing functions go here
1868
     *
1869
     * @global moodledatabase $DB
1870
     * @param stdClass $data
1871
     */
1872
    public function process_course($data) {
1873
        global $CFG, $DB;
1874
        $context = context::instance_by_id($this->task->get_contextid());
1875
        $userid = $this->task->get_userid();
1876
        $target = $this->get_task()->get_target();
1877
        $isnewcourse = $target == backup::TARGET_NEW_COURSE;
1878
 
1879
        // When restoring to a new course we can set all the things except for the ID number.
1880
        $canchangeidnumber = $isnewcourse || has_capability('moodle/course:changeidnumber', $context, $userid);
1881
        $canchangesummary = $isnewcourse || has_capability('moodle/course:changesummary', $context, $userid);
1882
        $canforcelanguage = has_capability('moodle/course:setforcedlanguage', $context, $userid);
1883
 
1884
        $data = (object)$data;
1885
        $data->id = $this->get_courseid();
1886
 
1887
        // Calculate final course names, to avoid dupes.
1888
        $fullname  = $this->get_setting_value('course_fullname');
1889
        $shortname = $this->get_setting_value('course_shortname');
1890
        list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names($this->get_courseid(),
1891
            $fullname === false ? $data->fullname : $fullname,
1892
            $shortname === false ? $data->shortname : $shortname);
1893
        // Do not modify the course names at all when merging and user selected to keep the names (or prohibited by cap).
1894
        if (!$isnewcourse && $fullname === false) {
1895
            unset($data->fullname);
1896
        }
1897
        if (!$isnewcourse && $shortname === false) {
1898
            unset($data->shortname);
1899
        }
1900
 
1901
        // Unset summary if user can't change it.
1902
        if (!$canchangesummary) {
1903
            unset($data->summary);
1904
            unset($data->summaryformat);
1905
        }
1906
 
1907
        // Unset lang if user can't change it.
1908
        if (!$canforcelanguage) {
1909
            unset($data->lang);
1910
        }
1911
 
1912
        // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1913
        // another course on this site.
1914
        if (!empty($data->idnumber) && $canchangeidnumber && $this->task->is_samesite()
1915
                && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1916
            // Do not reset idnumber.
1917
 
1918
        } else if (!$isnewcourse) {
1919
            // Prevent override when restoring as merge.
1920
            unset($data->idnumber);
1921
 
1922
        } else {
1923
            $data->idnumber = '';
1924
        }
1925
 
1926
        // If we restore a course from this site, let's capture the original course id.
1927
        if ($isnewcourse && $this->get_task()->is_samesite()) {
1928
            $data->originalcourseid = $this->get_task()->get_old_courseid();
1929
        }
1930
 
1931
        // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1932
        // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1933
        if (empty($data->hiddensections)) {
1934
            $data->hiddensections = 0;
1935
        }
1936
 
1937
        // Set legacyrestrictmodules to true if the course was resticting modules. If so
1938
        // then we will need to process restricted modules after execution.
1939
        $this->legacyrestrictmodules = !empty($data->restrictmodules);
1940
 
1941
        $data->startdate= $this->apply_date_offset($data->startdate);
1942
        if (isset($data->enddate)) {
1943
            $data->enddate = $this->apply_date_offset($data->enddate);
1944
        }
1945
 
1946
        if ($data->defaultgroupingid) {
1947
            $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1948
        }
1949
 
1950
        $courseconfig = get_config('moodlecourse');
1951
 
1952
        if (empty($CFG->enablecompletion)) {
1953
            // Completion is disabled globally.
1954
            $data->enablecompletion = 0;
1955
            $data->completionstartonenrol = 0;
1956
            $data->completionnotify = 0;
1957
            $data->showcompletionconditions = null;
1958
        } else {
1959
            $showcompletionconditionsdefault = ($courseconfig->showcompletionconditions ?? null);
1960
            $data->showcompletionconditions = $data->showcompletionconditions ?? $showcompletionconditionsdefault;
1961
        }
1962
 
1963
        $showactivitydatesdefault = ($courseconfig->showactivitydates ?? null);
1964
        $data->showactivitydates = $data->showactivitydates ?? $showactivitydatesdefault;
1965
 
1966
        $pdffontdefault = ($courseconfig->pdfexportfont ?? null);
1967
        $data->pdfexportfont = $data->pdfexportfont ?? $pdffontdefault;
1968
 
1969
        $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1970
        if (isset($data->lang) && !array_key_exists($data->lang, $languages)) {
1971
            $data->lang = '';
1972
        }
1973
 
1974
        $themes = get_list_of_themes(); // Get themes for quick search later
1975
        if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1976
            $data->theme = '';
1977
        }
1978
 
1979
        // Check if this is an old SCORM course format.
1980
        if ($data->format == 'scorm') {
1981
            $data->format = 'singleactivity';
1982
            $data->activitytype = 'scorm';
1983
        }
1984
 
1985
        // Course record ready, update it
1986
        $DB->update_record('course', $data);
1987
 
1988
        // Apply any course format options that may be saved against the course
1989
        // entity in earlier-version backups.
1990
        course_get_format($data)->update_course_format_options($data);
1991
 
1992
        // Role name aliases
1993
        restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1994
    }
1995
 
1996
    public function process_category($data) {
1997
        // Nothing to do with the category. UI sets it before restore starts
1998
    }
1999
 
2000
    public function process_tag($data) {
2001
        global $CFG, $DB;
2002
 
2003
        $data = (object)$data;
2004
 
2005
        core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
2006
                context_course::instance($this->get_courseid()), $data->rawname);
2007
    }
2008
 
2009
    /**
2010
     * Process custom fields
2011
     *
2012
     * @param array $data
2013
     */
2014
    public function process_customfield($data) {
2015
        $handler = core_course\customfield\course_handler::create();
2016
        $newid = $handler->restore_instance_data_from_backup($this->task, $data);
2017
 
2018
        if ($newid) {
2019
            $handler->restore_define_structure($this, $newid, $data['id']);
2020
        }
2021
    }
2022
 
2023
    /**
2024
     * Processes a course format option.
2025
     *
2026
     * @param array $data The record being restored.
2027
     * @throws base_step_exception
2028
     * @throws dml_exception
2029
     */
2030
    public function process_course_format_option(array $data): void {
2031
        global $DB;
2032
 
2033
        if ($data['sectionid']) {
2034
            // Ignore section-level format options saved course-level in earlier-version backups.
2035
            return;
2036
        }
2037
 
2038
        $courseid = $this->get_courseid();
2039
        $record = $DB->get_record('course_format_options', [ 'courseid' => $courseid, 'name' => $data['name'],
2040
                'format' => $data['format'], 'sectionid' => 0 ], 'id');
2041
        if ($record !== false) {
2042
            $DB->update_record('course_format_options', (object) [ 'id' => $record->id, 'value' => $data['value'] ]);
2043
        } else {
2044
            $data['courseid'] = $courseid;
2045
            $DB->insert_record('course_format_options', (object) $data);
2046
        }
2047
    }
2048
 
2049
    public function process_allowed_module($data) {
2050
        $data = (object)$data;
2051
 
2052
        // Backwards compatiblity support for the data that used to be in the
2053
        // course_allowed_modules table.
2054
        if ($this->legacyrestrictmodules) {
2055
            $this->legacyallowedmodules[$data->modulename] = 1;
2056
        }
2057
    }
2058
 
2059
    protected function after_execute() {
2060
        global $DB;
2061
 
2062
        // Add course related files, without itemid to match
2063
        $this->add_related_files('course', 'summary', null);
2064
        $this->add_related_files('course', 'overviewfiles', null);
2065
 
2066
        // Deal with legacy allowed modules.
2067
        if ($this->legacyrestrictmodules) {
2068
            $context = context_course::instance($this->get_courseid());
2069
 
2070
            list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
2071
            list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
2072
            foreach ($managerroleids as $roleid) {
2073
                unset($roleids[$roleid]);
2074
            }
2075
 
2076
            foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
2077
                if (isset($this->legacyallowedmodules[$modname])) {
2078
                    // Module is allowed, no worries.
2079
                    continue;
2080
                }
2081
 
2082
                $capability = 'mod/' . $modname . ':addinstance';
2083
 
2084
                if (!get_capability_info($capability)) {
2085
                    $this->log("Capability '{$capability}' was not found!", backup::LOG_WARNING);
2086
                    continue;
2087
                }
2088
 
2089
                foreach ($roleids as $roleid) {
2090
                    assign_capability($capability, CAP_PREVENT, $roleid, $context);
2091
                }
2092
            }
2093
        }
2094
    }
2095
}
2096
 
2097
/**
2098
 * Execution step that will migrate legacy files if present.
2099
 */
2100
class restore_course_legacy_files_step extends restore_execution_step {
2101
    public function define_execution() {
2102
        global $DB;
2103
 
2104
        // Do a check for legacy files and skip if there are none.
2105
        $sql = 'SELECT count(*)
2106
                  FROM {backup_files_temp}
2107
                 WHERE backupid = ?
2108
                   AND contextid = ?
2109
                   AND component = ?
2110
                   AND filearea  = ?';
2111
        $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
2112
 
2113
        if ($DB->count_records_sql($sql, $params)) {
2114
            $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
2115
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
2116
                'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
2117
        }
2118
    }
2119
}
2120
 
2121
/*
2122
 * Structure step that will read the roles.xml file (at course/activity/block levels)
2123
 * containing all the role_assignments and overrides for that context. If corresponding to
2124
 * one mapped role, they will be applied to target context. Will observe the role_assignments
2125
 * setting to decide if ras are restored.
2126
 *
2127
 * Note: this needs to be executed after all users are enrolled.
2128
 */
2129
class restore_ras_and_caps_structure_step extends restore_structure_step {
2130
    protected $plugins = null;
2131
 
2132
    protected function define_structure() {
2133
 
2134
        $paths = array();
2135
 
2136
        // Observe the role_assignments setting
2137
        if ($this->get_setting_value('role_assignments')) {
2138
            $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
2139
        }
2140
        if ($this->get_setting_value('permissions')) {
2141
            $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
2142
        }
2143
 
2144
        return $paths;
2145
    }
2146
 
2147
    /**
2148
     * Assign roles
2149
     *
2150
     * This has to be called after enrolments processing.
2151
     *
2152
     * @param mixed $data
2153
     * @return void
2154
     */
2155
    public function process_assignment($data) {
2156
        global $DB;
2157
 
2158
        $data = (object)$data;
2159
 
2160
        // Check roleid, userid are one of the mapped ones
2161
        if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
2162
            return;
2163
        }
2164
        if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
2165
            return;
2166
        }
2167
        if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
2168
            // Only assign roles to not deleted users
2169
            return;
2170
        }
2171
        if (!$contextid = $this->task->get_contextid()) {
2172
            return;
2173
        }
2174
 
2175
        if (empty($data->component)) {
2176
            // assign standard manual roles
2177
            // TODO: role_assign() needs one userid param to be able to specify our restore userid
2178
            role_assign($newroleid, $newuserid, $contextid);
2179
 
2180
        } else if ((strpos($data->component, 'enrol_') === 0)) {
2181
            // Deal with enrolment roles - ignore the component and just find out the instance via new id,
2182
            // it is possible that enrolment was restored using different plugin type.
2183
            if (!isset($this->plugins)) {
2184
                $this->plugins = enrol_get_plugins(true);
2185
            }
2186
            if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
2187
                if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2188
                    if (isset($this->plugins[$instance->enrol])) {
2189
                        $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
2190
                    }
2191
                }
2192
            }
2193
 
2194
        } else {
2195
            $data->roleid    = $newroleid;
2196
            $data->userid    = $newuserid;
2197
            $data->contextid = $contextid;
2198
            $dir = core_component::get_component_directory($data->component);
2199
            if ($dir and is_dir($dir)) {
2200
                if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
2201
                    return;
2202
                }
2203
            }
2204
            // Bad luck, plugin could not restore the data, let's add normal membership.
2205
            role_assign($data->roleid, $data->userid, $data->contextid);
2206
            $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
2207
            $this->log($message, backup::LOG_WARNING);
2208
        }
2209
    }
2210
 
2211
    public function process_override($data) {
2212
        $data = (object)$data;
2213
        // Check roleid is one of the mapped ones
2214
        $newrole = $this->get_mapping('role', $data->roleid);
2215
        $newroleid = $newrole->newitemid ?? false;
2216
        $userid = $this->task->get_userid();
2217
 
2218
        // If newroleid and context are valid assign it via API (it handles dupes and so on)
2219
        if ($newroleid && $this->task->get_contextid()) {
2220
            if (!$capability = get_capability_info($data->capability)) {
2221
                $this->log("Capability '{$data->capability}' was not found!", backup::LOG_WARNING);
2222
            } else {
2223
                $context = context::instance_by_id($this->task->get_contextid());
2224
                $overrideableroles = get_overridable_roles($context, ROLENAME_SHORT);
2225
                $safecapability = is_safe_capability($capability);
2226
 
2227
                // Check if the new role is an overrideable role AND if the user performing the restore has the
2228
                // capability to assign the capability.
2229
                if (in_array($newrole->info['shortname'], $overrideableroles) &&
2230
                    (has_capability('moodle/role:override', $context, $userid) ||
2231
                            ($safecapability && has_capability('moodle/role:safeoverride', $context, $userid)))
2232
                ) {
2233
                    assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
2234
                } else {
2235
                    $this->log("Insufficient capability to assign capability '{$data->capability}' to role!", backup::LOG_WARNING);
2236
                }
2237
            }
2238
        }
2239
    }
2240
}
2241
 
2242
/**
2243
 * If no instances yet add default enrol methods the same way as when creating new course in UI.
2244
 */
2245
class restore_default_enrolments_step extends restore_execution_step {
2246
 
2247
    public function define_execution() {
2248
        global $DB;
2249
 
2250
        // No enrolments in front page.
2251
        if ($this->get_courseid() == SITEID) {
2252
            return;
2253
        }
2254
 
2255
        $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
2256
        // Return any existing course enrolment instances.
2257
        $enrolinstances = enrol_get_instances($course->id, false);
2258
 
2259
        if ($enrolinstances) {
2260
            // Something already added instances.
2261
            // Get the existing enrolment methods in the course.
2262
            $enrolmethods = array_map(function($enrolinstance) {
2263
                return $enrolinstance->enrol;
2264
            }, $enrolinstances);
2265
 
2266
            $plugins = enrol_get_plugins(true);
2267
            foreach ($plugins as $pluginname => $plugin) {
2268
                // Make sure all default enrolment methods exist in the course.
2269
                if (!in_array($pluginname, $enrolmethods)) {
2270
                    $plugin->course_updated(true, $course, null);
2271
                }
2272
                $plugin->restore_sync_course($course);
2273
            }
2274
 
2275
        } else {
2276
            // Looks like a newly created course.
2277
            enrol_course_updated(true, $course, null);
2278
        }
2279
    }
2280
}
2281
 
2282
/**
2283
 * This structure steps restores the enrol plugins and their underlying
2284
 * enrolments, performing all the mappings and/or movements required
2285
 */
2286
class restore_enrolments_structure_step extends restore_structure_step {
2287
    protected $enrolsynced = false;
2288
    protected $plugins = null;
2289
    protected $originalstatus = array();
2290
 
2291
    /**
2292
     * Conditionally decide if this step should be executed.
2293
     *
2294
     * This function checks the following parameter:
2295
     *
2296
     *   1. the course/enrolments.xml file exists
2297
     *
2298
     * @return bool true is safe to execute, false otherwise
2299
     */
2300
    protected function execute_condition() {
2301
 
2302
        if ($this->get_courseid() == SITEID) {
2303
            return false;
2304
        }
2305
 
2306
        // Check it is included in the backup
2307
        $fullpath = $this->task->get_taskbasepath();
2308
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2309
        if (!file_exists($fullpath)) {
2310
            // Not found, can't restore enrolments info
2311
            return false;
2312
        }
2313
 
2314
        return true;
2315
    }
2316
 
2317
    protected function define_structure() {
2318
 
2319
        $userinfo = $this->get_setting_value('users');
2320
 
2321
        $paths = [];
2322
        $paths[] = $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2323
        if ($userinfo) {
2324
            $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2325
        }
2326
        // Attach local plugin stucture to enrol element.
2327
        $this->add_plugin_structure('enrol', $enrol);
2328
 
2329
        return $paths;
2330
    }
2331
 
2332
    /**
2333
     * Create enrolment instances.
2334
     *
2335
     * This has to be called after creation of roles
2336
     * and before adding of role assignments.
2337
     *
2338
     * @param mixed $data
2339
     * @return void
2340
     */
2341
    public function process_enrol($data) {
2342
        global $DB;
2343
 
2344
        $data = (object)$data;
2345
        $oldid = $data->id; // We'll need this later.
2346
        unset($data->id);
2347
 
2348
        $this->originalstatus[$oldid] = $data->status;
2349
 
2350
        if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2351
            $this->set_mapping('enrol', $oldid, 0);
2352
            return;
2353
        }
2354
 
2355
        if (!isset($this->plugins)) {
2356
            $this->plugins = enrol_get_plugins(true);
2357
        }
2358
 
2359
        if (!$this->enrolsynced) {
2360
            // Make sure that all plugin may create instances and enrolments automatically
2361
            // before the first instance restore - this is suitable especially for plugins
2362
            // that synchronise data automatically using course->idnumber or by course categories.
2363
            foreach ($this->plugins as $plugin) {
2364
                $plugin->restore_sync_course($courserec);
2365
            }
2366
            $this->enrolsynced = true;
2367
        }
2368
 
2369
        // Map standard fields - plugin has to process custom fields manually.
2370
        $data->roleid   = $this->get_mappingid('role', $data->roleid);
2371
        $data->courseid = $courserec->id;
2372
 
2373
        if (!$this->get_setting_value('users') && $this->get_setting_value('enrolments') == backup::ENROL_WITHUSERS) {
2374
            $converttomanual = true;
2375
        } else {
2376
            $converttomanual = ($this->get_setting_value('enrolments') == backup::ENROL_NEVER);
2377
        }
2378
 
2379
        if ($converttomanual) {
2380
            // Restore enrolments as manual enrolments.
2381
            unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2382
            if (!enrol_is_enabled('manual')) {
2383
                $this->set_mapping('enrol', $oldid, 0);
2384
                return;
2385
            }
2386
            if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2387
                $instance = reset($instances);
2388
                $this->set_mapping('enrol', $oldid, $instance->id);
2389
            } else {
2390
                if ($data->enrol === 'manual') {
2391
                    $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2392
                } else {
2393
                    $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2394
                }
2395
                $this->set_mapping('enrol', $oldid, $instanceid);
2396
            }
2397
 
2398
        } else {
2399
            if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2400
                $this->set_mapping('enrol', $oldid, 0);
2401
                $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, consider restoring without enrolment methods";
2402
                $this->log($message, backup::LOG_WARNING);
2403
                return;
2404
            }
2405
            if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2406
                // Let's keep the sortorder in old backups.
2407
            } else {
2408
                // Prevent problems with colliding sortorders in old backups,
2409
                // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2410
                unset($data->sortorder);
2411
            }
2412
            // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2413
            $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2414
        }
2415
    }
2416
 
2417
    /**
2418
     * Create user enrolments.
2419
     *
2420
     * This has to be called after creation of enrolment instances
2421
     * and before adding of role assignments.
2422
     *
2423
     * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2424
     *
2425
     * @param mixed $data
2426
     * @return void
2427
     */
2428
    public function process_enrolment($data) {
2429
        global $DB;
2430
 
2431
        if (!isset($this->plugins)) {
2432
            $this->plugins = enrol_get_plugins(true);
2433
        }
2434
 
2435
        $data = (object)$data;
2436
 
2437
        // Process only if parent instance have been mapped.
2438
        if ($enrolid = $this->get_new_parentid('enrol')) {
2439
            $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2440
            $oldenrolid = $this->get_old_parentid('enrol');
2441
            if (isset($this->originalstatus[$oldenrolid])) {
2442
                $oldinstancestatus = $this->originalstatus[$oldenrolid];
2443
            }
2444
            if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2445
                // And only if user is a mapped one.
2446
                if ($userid = $this->get_mappingid('user', $data->userid)) {
2447
                    if (isset($this->plugins[$instance->enrol])) {
2448
                        $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2449
                    }
2450
                }
2451
            }
2452
        }
2453
    }
2454
}
2455
 
2456
 
2457
/**
2458
 * Make sure the user restoring the course can actually access it.
2459
 */
2460
class restore_fix_restorer_access_step extends restore_execution_step {
2461
    protected function define_execution() {
2462
        global $CFG, $DB;
2463
 
2464
        if (!$userid = $this->task->get_userid()) {
2465
            return;
2466
        }
2467
 
2468
        if (empty($CFG->restorernewroleid)) {
2469
            // Bad luck, no fallback role for restorers specified
2470
            return;
2471
        }
2472
 
2473
        $courseid = $this->get_courseid();
2474
        $context = context_course::instance($courseid);
2475
 
2476
        if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2477
            // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2478
            return;
2479
        }
2480
 
2481
        // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2482
        role_assign($CFG->restorernewroleid, $userid, $context);
2483
 
2484
        if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2485
            // Extra role is enough, yay!
2486
            return;
2487
        }
2488
 
2489
        // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2490
        // hopefully admin selected suitable $CFG->restorernewroleid ...
2491
        if (!enrol_is_enabled('manual')) {
2492
            return;
2493
        }
2494
        if (!$enrol = enrol_get_plugin('manual')) {
2495
            return;
2496
        }
2497
        if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2498
            $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2499
            $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2500
            $enrol->add_instance($course, $fields);
2501
        }
2502
 
2503
        enrol_try_internal_enrol($courseid, $userid);
2504
    }
2505
}
2506
 
2507
 
2508
/**
2509
 * This structure steps restores the filters and their configs
2510
 */
2511
class restore_filters_structure_step extends restore_structure_step {
2512
 
2513
    protected function define_structure() {
2514
 
2515
        $paths = array();
2516
 
2517
        $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2518
        $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2519
 
2520
        return $paths;
2521
    }
2522
 
2523
    public function process_active($data) {
2524
 
2525
        $data = (object)$data;
2526
 
2527
        if (strpos($data->filter, 'filter/') === 0) {
2528
            $data->filter = substr($data->filter, 7);
2529
 
2530
        } else if (strpos($data->filter, '/') !== false) {
2531
            // Unsupported old filter.
2532
            return;
2533
        }
2534
 
2535
        if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2536
            return;
2537
        }
2538
        filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2539
    }
2540
 
2541
    public function process_config($data) {
2542
 
2543
        $data = (object)$data;
2544
 
2545
        if (strpos($data->filter, 'filter/') === 0) {
2546
            $data->filter = substr($data->filter, 7);
2547
 
2548
        } else if (strpos($data->filter, '/') !== false) {
2549
            // Unsupported old filter.
2550
            return;
2551
        }
2552
 
2553
        if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2554
            return;
2555
        }
2556
        filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2557
    }
2558
}
2559
 
2560
 
2561
/**
2562
 * This structure steps restores the comments
2563
 * Note: Cannot use the comments API because defaults to USER->id.
2564
 * That should change allowing to pass $userid
2565
 */
2566
class restore_comments_structure_step extends restore_structure_step {
2567
 
2568
    protected function define_structure() {
2569
 
2570
        $paths = array();
2571
 
2572
        $paths[] = new restore_path_element('comment', '/comments/comment');
2573
 
2574
        return $paths;
2575
    }
2576
 
2577
    public function process_comment($data) {
2578
        global $DB;
2579
 
2580
        $data = (object)$data;
2581
 
2582
        // First of all, if the comment has some itemid, ask to the task what to map
2583
        $mapping = false;
2584
        if ($data->itemid) {
2585
            $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2586
            $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2587
        }
2588
        // Only restore the comment if has no mapping OR we have found the matching mapping
2589
        if (!$mapping || $data->itemid) {
2590
            // Only if user mapping and context
2591
            $data->userid = $this->get_mappingid('user', $data->userid);
2592
            if ($data->userid && $this->task->get_contextid()) {
2593
                $data->contextid = $this->task->get_contextid();
2594
                // Only if there is another comment with same context/user/timecreated
2595
                $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2596
                if (!$DB->record_exists('comments', $params)) {
2597
                    $DB->insert_record('comments', $data);
2598
                }
2599
            }
2600
        }
2601
    }
2602
}
2603
 
2604
/**
2605
 * This structure steps restores the badges and their configs
2606
 */
2607
class restore_badges_structure_step extends restore_structure_step {
2608
 
2609
    /**
2610
     * Conditionally decide if this step should be executed.
2611
     *
2612
     * This function checks the following parameters:
2613
     *
2614
     *   1. Badges and course badges are enabled on the site.
2615
     *   2. The course/badges.xml file exists.
2616
     *   3. All modules are restorable.
2617
     *   4. All modules are marked for restore.
2618
     *
2619
     * @return bool True is safe to execute, false otherwise
2620
     */
2621
    protected function execute_condition() {
2622
        global $CFG;
2623
 
2624
        // First check is badges and course level badges are enabled on this site.
2625
        if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2626
            // Disabled, don't restore course badges.
2627
            return false;
2628
        }
2629
 
2630
        // Check if badges.xml is included in the backup.
2631
        $fullpath = $this->task->get_taskbasepath();
2632
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2633
        if (!file_exists($fullpath)) {
2634
            // Not found, can't restore course badges.
2635
            return false;
2636
        }
2637
 
2638
        // Check we are able to restore all backed up modules.
2639
        if ($this->task->is_missing_modules()) {
2640
            return false;
2641
        }
2642
 
2643
        // Finally check all modules within the backup are being restored.
2644
        if ($this->task->is_excluding_activities()) {
2645
            return false;
2646
        }
2647
 
2648
        return true;
2649
    }
2650
 
2651
    protected function define_structure() {
2652
        $paths = array();
2653
        $paths[] = new restore_path_element('badge', '/badges/badge');
2654
        $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2655
        $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2656
        $paths[] = new restore_path_element('endorsement', '/badges/badge/endorsement');
2657
        $paths[] = new restore_path_element('alignment', '/badges/badge/alignments/alignment');
2658
        $paths[] = new restore_path_element('relatedbadge', '/badges/badge/relatedbadges/relatedbadge');
2659
        $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2660
        $paths[] = new restore_path_element('tag', '/badges/badge/tags/tag');
2661
 
2662
        return $paths;
2663
    }
2664
 
2665
    public function process_badge($data) {
2666
        global $DB, $CFG;
2667
 
2668
        require_once($CFG->libdir . '/badgeslib.php');
2669
 
2670
        $data = (object)$data;
2671
        $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2672
        if (empty($data->usercreated)) {
2673
            $data->usercreated = $this->task->get_userid();
2674
        }
2675
        $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2676
        if (empty($data->usermodified)) {
2677
            $data->usermodified = $this->task->get_userid();
2678
        }
2679
 
2680
        // We'll restore the badge image.
2681
        $restorefiles = true;
2682
 
2683
        $courseid = $this->get_courseid();
2684
 
2685
        $params = array(
2686
                'name'           => $data->name,
2687
                'description'    => $data->description,
2688
                'timecreated'    => $data->timecreated,
2689
                'timemodified'   => $data->timemodified,
2690
                'usercreated'    => $data->usercreated,
2691
                'usermodified'   => $data->usermodified,
2692
                'issuername'     => $data->issuername,
2693
                'issuerurl'      => $data->issuerurl,
2694
                'issuercontact'  => $data->issuercontact,
2695
                'expiredate'     => $this->apply_date_offset($data->expiredate),
2696
                'expireperiod'   => $data->expireperiod,
2697
                'type'           => BADGE_TYPE_COURSE,
2698
                'courseid'       => $courseid,
2699
                'message'        => $data->message,
2700
                'messagesubject' => $data->messagesubject,
2701
                'attachment'     => $data->attachment,
2702
                'notification'   => $data->notification,
2703
                'status'         => BADGE_STATUS_INACTIVE,
2704
                'nextcron'       => $data->nextcron,
2705
                'version'        => $data->version,
2706
                'language'       => $data->language,
2707
                'imageauthorname' => $data->imageauthorname,
2708
                'imageauthoremail' => $data->imageauthoremail,
2709
                'imageauthorurl' => $data->imageauthorurl,
2710
                'imagecaption'   => $data->imagecaption
2711
        );
2712
 
2713
        $newid = $DB->insert_record('badge', $params);
2714
        $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2715
    }
2716
 
2717
    /**
2718
     * Create an endorsement for a badge.
2719
     *
2720
     * @param mixed $data
2721
     * @return void
2722
     */
2723
    public function process_endorsement($data) {
2724
        global $DB;
2725
 
2726
        $data = (object)$data;
2727
 
2728
        $params = [
2729
            'badgeid' => $this->get_new_parentid('badge'),
2730
            'issuername' => $data->issuername,
2731
            'issuerurl' => $data->issuerurl,
2732
            'issueremail' => $data->issueremail,
2733
            'claimid' => $data->claimid,
2734
            'claimcomment' => $data->claimcomment,
2735
            'dateissued' => $this->apply_date_offset($data->dateissued)
2736
        ];
2737
        $newid = $DB->insert_record('badge_endorsement', $params);
2738
        $this->set_mapping('endorsement', $data->id, $newid);
2739
    }
2740
 
2741
    /**
2742
     * Link to related badges for a badge. This relies on post processing in after_execute().
2743
     *
2744
     * @param mixed $data
2745
     * @return void
2746
     */
2747
    public function process_relatedbadge($data) {
2748
        global $DB;
2749
 
2750
        $data = (object)$data;
2751
        $relatedbadgeid = $data->relatedbadgeid;
2752
 
2753
        if ($relatedbadgeid) {
2754
            // Only backup and restore related badges if they are contained in the backup file.
2755
            $params = array(
2756
                    'badgeid'           => $this->get_new_parentid('badge'),
2757
                    'relatedbadgeid'    => $relatedbadgeid
2758
            );
2759
            $newid = $DB->insert_record('badge_related', $params);
2760
        }
2761
    }
2762
 
2763
    /**
2764
     * Link to an alignment for a badge.
2765
     *
2766
     * @param mixed $data
2767
     * @return void
2768
     */
2769
    public function process_alignment($data) {
2770
        global $DB;
2771
 
2772
        $data = (object)$data;
2773
        $params = array(
2774
                'badgeid'           => $this->get_new_parentid('badge'),
2775
                'targetname'        => $data->targetname,
2776
                'targeturl'         => $data->targeturl,
2777
                'targetdescription' => $data->targetdescription,
2778
                'targetframework'   => $data->targetframework,
2779
                'targetcode'        => $data->targetcode
2780
        );
2781
        $newid = $DB->insert_record('badge_alignment', $params);
2782
        $this->set_mapping('alignment', $data->id, $newid);
2783
    }
2784
 
2785
    public function process_criterion($data) {
2786
        global $DB;
2787
 
2788
        $data = (object)$data;
2789
 
2790
        $params = array(
2791
                'badgeid'           => $this->get_new_parentid('badge'),
2792
                'criteriatype'      => $data->criteriatype,
2793
                'method'            => $data->method,
2794
                'description'       => isset($data->description) ? $data->description : '',
2795
                'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0,
2796
        );
2797
 
2798
        $newid = $DB->insert_record('badge_criteria', $params);
2799
        $this->set_mapping('criterion', $data->id, $newid);
2800
    }
2801
 
2802
    public function process_parameter($data) {
2803
        global $DB, $CFG;
2804
 
2805
        require_once($CFG->libdir . '/badgeslib.php');
2806
 
2807
        $data = (object)$data;
2808
        $criteriaid = $this->get_new_parentid('criterion');
2809
 
2810
        // Parameter array that will go to database.
2811
        $params = array();
2812
        $params['critid'] = $criteriaid;
2813
 
2814
        $oldparam = explode('_', $data->name);
2815
 
2816
        if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2817
            $module = $this->get_mappingid('course_module', $oldparam[1]);
2818
            $params['name'] = $oldparam[0] . '_' . $module;
2819
            $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2820
        } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2821
            $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2822
            $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2823
        } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2824
            $role = $this->get_mappingid('role', $data->value);
2825
            if (!empty($role)) {
2826
                $params['name'] = 'role_' . $role;
2827
                $params['value'] = $role;
2828
            } else {
2829
                return;
2830
            }
2831
        } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COMPETENCY) {
2832
            $competencyid = $this->get_mappingid('competency', $data->value);
2833
            if (!empty($competencyid)) {
2834
                $params['name'] = 'competency_' . $competencyid;
2835
                $params['value'] = $competencyid;
2836
            } else {
2837
                return;
2838
            }
2839
        }
2840
 
2841
        if (!$DB->record_exists('badge_criteria_param', $params)) {
2842
            $DB->insert_record('badge_criteria_param', $params);
2843
        }
2844
    }
2845
 
2846
    public function process_manual_award($data) {
2847
        global $DB;
2848
 
2849
        $data = (object)$data;
2850
        $role = $this->get_mappingid('role', $data->issuerrole);
2851
 
2852
        if (!empty($role)) {
2853
            $award = array(
2854
                'badgeid'     => $this->get_new_parentid('badge'),
2855
                'recipientid' => $this->get_mappingid('user', $data->recipientid),
2856
                'issuerid'    => $this->get_mappingid('user', $data->issuerid),
2857
                'issuerrole'  => $role,
2858
                'datemet'     => $this->apply_date_offset($data->datemet)
2859
            );
2860
 
2861
            // Skip the manual award if recipient or issuer can not be mapped to.
2862
            if (empty($award['recipientid']) || empty($award['issuerid'])) {
2863
                return;
2864
            }
2865
 
2866
            $DB->insert_record('badge_manual_award', $award);
2867
        }
2868
    }
2869
 
2870
    /**
2871
     * Process tag.
2872
     *
2873
     * @param array $data The data.
2874
     * @throws base_step_exception
2875
     */
2876
    public function process_tag(array $data): void {
2877
        $data = (object)$data;
2878
        $badgeid = $this->get_new_parentid('badge');
2879
 
2880
        if (!empty($data->rawname)) {
2881
            core_tag_tag::add_item_tag('core_badges', 'badge', $badgeid,
2882
                context_course::instance($this->get_courseid()), $data->rawname);
2883
        }
2884
    }
2885
 
2886
    protected function after_execute() {
2887
        global $DB;
2888
        // Add related files.
2889
        $this->add_related_files('badges', 'badgeimage', 'badge');
2890
 
2891
        $badgeid = $this->get_new_parentid('badge');
2892
        // Remap any related badges.
2893
        // We do this in the DB directly because this is backup/restore it is not valid to call into
2894
        // the component API.
2895
        $params = array('badgeid' => $badgeid);
2896
        $query = "SELECT DISTINCT br.id, br.badgeid, br.relatedbadgeid
2897
                    FROM {badge_related} br
2898
                   WHERE (br.badgeid = :badgeid)";
2899
        $relatedbadges = $DB->get_records_sql($query, $params);
2900
        $newrelatedids = [];
2901
        foreach ($relatedbadges as $relatedbadge) {
2902
            $relatedid = $this->get_mappingid('badge', $relatedbadge->relatedbadgeid);
2903
            $params['relatedbadgeid'] = $relatedbadge->relatedbadgeid;
2904
            $DB->delete_records_select('badge_related', '(badgeid = :badgeid AND relatedbadgeid = :relatedbadgeid)', $params);
2905
            if ($relatedid) {
2906
                $newrelatedids[] = $relatedid;
2907
            }
2908
        }
2909
        if (!empty($newrelatedids)) {
2910
            $relatedbadges = [];
2911
            foreach ($newrelatedids as $relatedid) {
2912
                $relatedbadge = new stdClass();
2913
                $relatedbadge->badgeid = $badgeid;
2914
                $relatedbadge->relatedbadgeid = $relatedid;
2915
                $relatedbadges[] = $relatedbadge;
2916
            }
2917
            $DB->insert_records('badge_related', $relatedbadges);
2918
        }
2919
    }
2920
}
2921
 
2922
/**
2923
 * This structure steps restores the calendar events
2924
 */
2925
class restore_calendarevents_structure_step extends restore_structure_step {
2926
 
2927
    protected function define_structure() {
2928
 
2929
        $paths = array();
2930
 
2931
        $paths[] = new restore_path_element('calendarevents', '/events/event');
2932
 
2933
        return $paths;
2934
    }
2935
 
2936
    public function process_calendarevents($data) {
2937
        global $DB, $SITE, $USER;
2938
 
2939
        $data = (object)$data;
2940
        $oldid = $data->id;
2941
        $restorefiles = true; // We'll restore the files
2942
 
2943
        // If this is a new action event, it will automatically be populated by the adhoc task.
2944
        // Nothing to do here.
2945
        if (isset($data->type) && $data->type == CALENDAR_EVENT_TYPE_ACTION) {
2946
            return;
2947
        }
2948
 
2949
        // User overrides for activities are identified by having a courseid of zero with
2950
        // both a modulename and instance value set.
2951
        $isuseroverride = !$data->courseid && $data->modulename && $data->instance;
2952
 
2953
        // If we don't want to include user data and this record is a user override event
2954
        // for an activity then we should not create it. (Only activity events can be user override events - which must have this
2955
        // setting).
2956
        if ($isuseroverride && $this->task->setting_exists('userinfo') && !$this->task->get_setting_value('userinfo')) {
2957
            return;
2958
        }
2959
 
2960
        // Find the userid and the groupid associated with the event.
2961
        $data->userid = $this->get_mappingid('user', $data->userid);
2962
        if ($data->userid === false) {
2963
            // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2964
            // Use the current user ID for these events.
2965
            $data->userid = $USER->id;
2966
        }
2967
        if (!empty($data->groupid)) {
2968
            $data->groupid = $this->get_mappingid('group', $data->groupid);
2969
            if ($data->groupid === false) {
2970
                return;
2971
            }
2972
        }
2973
        // Handle events with empty eventtype //MDL-32827
2974
        if(empty($data->eventtype)) {
2975
            if ($data->courseid == $SITE->id) {                                // Site event
2976
                $data->eventtype = "site";
2977
            } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2978
                // Course assingment event
2979
                $data->eventtype = "due";
2980
            } else if ($data->courseid != 0 && $data->groupid == 0) {      // Course event
2981
                $data->eventtype = "course";
2982
            } else if ($data->groupid) {                                      // Group event
2983
                $data->eventtype = "group";
2984
            } else if ($data->userid) {                                       // User event
2985
                $data->eventtype = "user";
2986
            } else {
2987
                return;
2988
            }
2989
        }
2990
 
2991
        $params = array(
2992
                'name'           => $data->name,
2993
                'description'    => $data->description,
2994
                'format'         => $data->format,
2995
                // User overrides in activities use a course id of zero. All other event types
2996
                // must use the mapped course id.
2997
                'courseid'       => $data->courseid ? $this->get_courseid() : 0,
2998
                'groupid'        => $data->groupid,
2999
                'userid'         => $data->userid,
3000
                'repeatid'       => $this->get_mappingid('event', $data->repeatid),
3001
                'modulename'     => $data->modulename,
3002
                'type'           => isset($data->type) ? $data->type : 0,
3003
                'eventtype'      => $data->eventtype,
3004
                'timestart'      => $this->apply_date_offset($data->timestart),
3005
                'timeduration'   => $data->timeduration,
3006
                'timesort'       => isset($data->timesort) ? $this->apply_date_offset($data->timesort) : null,
3007
                'visible'        => $data->visible,
3008
                'uuid'           => $data->uuid,
3009
                'sequence'       => $data->sequence,
3010
                'timemodified'   => $data->timemodified,
3011
                'priority'       => isset($data->priority) ? $data->priority : null,
3012
                'location'       => isset($data->location) ? $data->location : null);
3013
        if ($this->name == 'activity_calendar') {
3014
            $params['instance'] = $this->task->get_activityid();
3015
        } else {
3016
            $params['instance'] = 0;
3017
        }
3018
        $sql = "SELECT id
3019
                  FROM {event}
3020
                 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
3021
                   AND courseid = ?
3022
                   AND modulename = ?
3023
                   AND instance = ?
3024
                   AND timestart = ?
3025
                   AND timeduration = ?
3026
                   AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
3027
        $arg = array ($params['name'], $params['courseid'], $params['modulename'], $params['instance'], $params['timestart'], $params['timeduration'], $params['description']);
3028
        $result = $DB->record_exists_sql($sql, $arg);
3029
        if (empty($result)) {
3030
            $newitemid = $DB->insert_record('event', $params);
3031
            $this->set_mapping('event', $oldid, $newitemid);
3032
            $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
3033
        }
3034
        // With repeating events, each event has the repeatid pointed at the first occurrence.
3035
        // Since the repeatid will be empty when the first occurrence is restored,
3036
        // Get the repeatid from the second occurrence of the repeating event and use that to update the first occurrence.
3037
        // Then keep a list of repeatids so we only perform this update once.
3038
        static $repeatids = array();
3039
        if (!empty($params['repeatid']) && !in_array($params['repeatid'], $repeatids)) {
3040
            // This entry is repeated so the repeatid field must be set.
3041
            $DB->set_field('event', 'repeatid', $params['repeatid'], array('id' => $params['repeatid']));
3042
            $repeatids[] = $params['repeatid'];
3043
        }
3044
 
3045
    }
3046
    protected function after_execute() {
3047
        // Add related files
3048
        $this->add_related_files('calendar', 'event_description', 'event_description');
3049
    }
3050
}
3051
 
3052
class restore_course_completion_structure_step extends restore_structure_step {
3053
 
3054
    /**
3055
     * Conditionally decide if this step should be executed.
3056
     *
3057
     * This function checks parameters that are not immediate settings to ensure
3058
     * that the enviroment is suitable for the restore of course completion info.
3059
     *
3060
     * This function checks the following four parameters:
3061
     *
3062
     *   1. Course completion is enabled on the site
3063
     *   2. The backup includes course completion information
3064
     *   3. All modules are restorable
3065
     *   4. All modules are marked for restore.
3066
     *   5. No completion criteria already exist for the course.
3067
     *
3068
     * @return bool True is safe to execute, false otherwise
3069
     */
3070
    protected function execute_condition() {
3071
        global $CFG, $DB;
3072
 
3073
        // First check course completion is enabled on this site
3074
        if (empty($CFG->enablecompletion)) {
3075
            // Disabled, don't restore course completion
3076
            return false;
3077
        }
3078
 
3079
        // No course completion on the front page.
3080
        if ($this->get_courseid() == SITEID) {
3081
            return false;
3082
        }
3083
 
3084
        // Check it is included in the backup
3085
        $fullpath = $this->task->get_taskbasepath();
3086
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3087
        if (!file_exists($fullpath)) {
3088
            // Not found, can't restore course completion
3089
            return false;
3090
        }
3091
 
3092
        // Check we are able to restore all backed up modules
3093
        if ($this->task->is_missing_modules()) {
3094
            return false;
3095
        }
3096
 
3097
        // Check all modules within the backup are being restored.
3098
        if ($this->task->is_excluding_activities()) {
3099
            return false;
3100
        }
3101
 
3102
        // Check that no completion criteria is already set for the course.
3103
        if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
3104
            return false;
3105
        }
3106
 
3107
        return true;
3108
    }
3109
 
3110
    /**
3111
     * Define the course completion structure
3112
     *
3113
     * @return array Array of restore_path_element
3114
     */
3115
    protected function define_structure() {
3116
 
3117
        // To know if we are including user completion info
3118
        $userinfo = $this->get_setting_value('userscompletion');
3119
 
3120
        $paths = array();
3121
        $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
3122
        $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
3123
 
3124
        if ($userinfo) {
3125
            $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
3126
            $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
3127
        }
3128
 
3129
        return $paths;
3130
 
3131
    }
3132
 
3133
    /**
3134
     * Process course completion criteria
3135
     *
3136
     * @global moodle_database $DB
3137
     * @param stdClass $data
3138
     */
3139
    public function process_course_completion_criteria($data) {
3140
        global $DB;
3141
 
3142
        $data = (object)$data;
3143
        $data->course = $this->get_courseid();
3144
 
3145
        // Apply the date offset to the time end field
3146
        $data->timeend = $this->apply_date_offset($data->timeend);
3147
 
3148
        // Map the role from the criteria
3149
        if (isset($data->role) && $data->role != '') {
3150
            // Newer backups should include roleshortname, which makes this much easier.
3151
            if (!empty($data->roleshortname)) {
3152
                $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
3153
                if (!$roleinstanceid) {
3154
                    $this->log(
3155
                        'Could not match the role shortname in course_completion_criteria, so skipping',
3156
                        backup::LOG_DEBUG
3157
                    );
3158
                    return;
3159
                }
3160
                $data->role = $roleinstanceid;
3161
            } else {
3162
                $data->role = $this->get_mappingid('role', $data->role);
3163
            }
3164
 
3165
            // Check we have an id, otherwise it causes all sorts of bugs.
3166
            if (!$data->role) {
3167
                $this->log(
3168
                    'Could not match role in course_completion_criteria, so skipping',
3169
                    backup::LOG_DEBUG
3170
                );
3171
                return;
3172
            }
3173
        }
3174
 
3175
        // If the completion criteria is for a module we need to map the module instance
3176
        // to the new module id.
3177
        if (!empty($data->moduleinstance) && !empty($data->module)) {
3178
            $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
3179
            if (empty($data->moduleinstance)) {
3180
                $this->log(
3181
                    'Could not match the module instance in course_completion_criteria, so skipping',
3182
                    backup::LOG_DEBUG
3183
                );
3184
                return;
3185
            }
3186
        } else {
3187
            $data->module = null;
3188
            $data->moduleinstance = null;
3189
        }
3190
 
3191
        // We backup the course shortname rather than the ID so that we can match back to the course
3192
        if (!empty($data->courseinstanceshortname)) {
3193
            $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
3194
            if (!$courseinstanceid) {
3195
                $this->log(
3196
                    'Could not match the course instance in course_completion_criteria, so skipping',
3197
                    backup::LOG_DEBUG
3198
                );
3199
                return;
3200
            }
3201
        } else {
3202
            $courseinstanceid = null;
3203
        }
3204
        $data->courseinstance = $courseinstanceid;
3205
 
3206
        $params = array(
3207
            'course'         => $data->course,
3208
            'criteriatype'   => $data->criteriatype,
3209
            'enrolperiod'    => $data->enrolperiod,
3210
            'courseinstance' => $data->courseinstance,
3211
            'module'         => $data->module,
3212
            'moduleinstance' => $data->moduleinstance,
3213
            'timeend'        => $data->timeend,
3214
            'gradepass'      => $data->gradepass,
3215
            'role'           => $data->role
3216
        );
3217
        $newid = $DB->insert_record('course_completion_criteria', $params);
3218
        $this->set_mapping('course_completion_criteria', $data->id, $newid);
3219
    }
3220
 
3221
    /**
3222
     * Processes course compltion criteria complete records
3223
     *
3224
     * @global moodle_database $DB
3225
     * @param stdClass $data
3226
     */
3227
    public function process_course_completion_crit_compl($data) {
3228
        global $DB;
3229
 
3230
        $data = (object)$data;
3231
 
3232
        // This may be empty if criteria could not be restored
3233
        $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
3234
 
3235
        $data->course = $this->get_courseid();
3236
        $data->userid = $this->get_mappingid('user', $data->userid);
3237
 
3238
        if (!empty($data->criteriaid) && !empty($data->userid)) {
3239
            $params = array(
3240
                'userid' => $data->userid,
3241
                'course' => $data->course,
3242
                'criteriaid' => $data->criteriaid,
3243
                'timecompleted' => $data->timecompleted
3244
            );
3245
            if (isset($data->gradefinal)) {
3246
                $params['gradefinal'] = $data->gradefinal;
3247
            }
3248
            if (isset($data->unenroled)) {
3249
                $params['unenroled'] = $data->unenroled;
3250
            }
3251
            $DB->insert_record('course_completion_crit_compl', $params);
3252
        }
3253
    }
3254
 
3255
    /**
3256
     * Process course completions
3257
     *
3258
     * @global moodle_database $DB
3259
     * @param stdClass $data
3260
     */
3261
    public function process_course_completions($data) {
3262
        global $DB;
3263
 
3264
        $data = (object)$data;
3265
 
3266
        $data->course = $this->get_courseid();
3267
        $data->userid = $this->get_mappingid('user', $data->userid);
3268
 
3269
        if (!empty($data->userid)) {
3270
            $params = array(
3271
                'userid' => $data->userid,
3272
                'course' => $data->course,
3273
                'timeenrolled' => $data->timeenrolled,
3274
                'timestarted' => $data->timestarted,
3275
                'timecompleted' => $data->timecompleted,
3276
                'reaggregate' => $data->reaggregate
3277
            );
3278
 
3279
            $existing = $DB->get_record('course_completions', array(
3280
                'userid' => $data->userid,
3281
                'course' => $data->course
3282
            ));
3283
 
3284
            // MDL-46651 - If cron writes out a new record before we get to it
3285
            // then we should replace it with the Truth data from the backup.
3286
            // This may be obsolete after MDL-48518 is resolved
3287
            if ($existing) {
3288
                $params['id'] = $existing->id;
3289
                $DB->update_record('course_completions', $params);
3290
            } else {
3291
                $DB->insert_record('course_completions', $params);
3292
            }
3293
        }
3294
    }
3295
 
3296
    /**
3297
     * Process course completion aggregate methods
3298
     *
3299
     * @global moodle_database $DB
3300
     * @param stdClass $data
3301
     */
3302
    public function process_course_completion_aggr_methd($data) {
3303
        global $DB;
3304
 
3305
        $data = (object)$data;
3306
 
3307
        $data->course = $this->get_courseid();
3308
 
3309
        // Only create the course_completion_aggr_methd records if
3310
        // the target course has not them defined. MDL-28180
3311
        if (!$DB->record_exists('course_completion_aggr_methd', array(
3312
                    'course' => $data->course,
3313
                    'criteriatype' => $data->criteriatype))) {
3314
            $params = array(
3315
                'course' => $data->course,
3316
                'criteriatype' => $data->criteriatype,
3317
                'method' => $data->method,
3318
                'value' => $data->value,
3319
            );
3320
            $DB->insert_record('course_completion_aggr_methd', $params);
3321
        }
3322
    }
3323
}
3324
 
3325
 
3326
/**
3327
 * This structure step restores course logs (cmid = 0), delegating
3328
 * the hard work to the corresponding {@link restore_logs_processor} passing the
3329
 * collection of {@link restore_log_rule} rules to be observed as they are defined
3330
 * by the task. Note this is only executed based in the 'logs' setting.
3331
 *
3332
 * NOTE: This is executed by final task, to have all the activities already restored
3333
 *
3334
 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
3335
 * records are. There are others like 'calendar' and 'upload' that will be handled
3336
 * later.
3337
 *
3338
 * NOTE: All the missing actions (not able to be restored) are sent to logs for
3339
 * debugging purposes
3340
 */
3341
class restore_course_logs_structure_step extends restore_structure_step {
3342
 
3343
    /**
3344
     * Conditionally decide if this step should be executed.
3345
     *
3346
     * This function checks the following parameter:
3347
     *
3348
     *   1. the course/logs.xml file exists
3349
     *
3350
     * @return bool true is safe to execute, false otherwise
3351
     */
3352
    protected function execute_condition() {
3353
 
3354
        // Check it is included in the backup
3355
        $fullpath = $this->task->get_taskbasepath();
3356
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3357
        if (!file_exists($fullpath)) {
3358
            // Not found, can't restore course logs
3359
            return false;
3360
        }
3361
 
3362
        return true;
3363
    }
3364
 
3365
    protected function define_structure() {
3366
 
3367
        $paths = array();
3368
 
3369
        // Simple, one plain level of information contains them
3370
        $paths[] = new restore_path_element('log', '/logs/log');
3371
 
3372
        return $paths;
3373
    }
3374
 
3375
    protected function process_log($data) {
3376
        global $DB;
3377
 
3378
        $data = (object)($data);
3379
 
3380
        // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3381
 
3382
        $data->userid = $this->get_mappingid('user', $data->userid);
3383
        $data->course = $this->get_courseid();
3384
        $data->cmid = 0;
3385
 
3386
        // For any reason user wasn't remapped ok, stop processing this
3387
        if (empty($data->userid)) {
3388
            return;
3389
        }
3390
 
3391
        // Everything ready, let's delegate to the restore_logs_processor
3392
 
3393
        // Set some fixed values that will save tons of DB requests
3394
        $values = array(
3395
            'course' => $this->get_courseid());
3396
        // Get instance and process log record
3397
        $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3398
 
3399
        // If we have data, insert it, else something went wrong in the restore_logs_processor
3400
        if ($data) {
3401
            if (empty($data->url)) {
3402
                $data->url = '';
3403
            }
3404
            if (empty($data->info)) {
3405
                $data->info = '';
3406
            }
3407
            // Store the data in the legacy log table if we are still using it.
3408
            $manager = get_log_manager();
3409
            if (method_exists($manager, 'legacy_add_to_log')) {
3410
                $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3411
                    $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3412
            }
3413
        }
3414
    }
3415
}
3416
 
3417
/**
3418
 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
3419
 * sharing its same structure but modifying the way records are handled
3420
 */
3421
class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
3422
 
3423
    protected function process_log($data) {
3424
        global $DB;
3425
 
3426
        $data = (object)($data);
3427
 
3428
        // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3429
 
3430
        $data->userid = $this->get_mappingid('user', $data->userid);
3431
        $data->course = $this->get_courseid();
3432
        $data->cmid = $this->task->get_moduleid();
3433
 
3434
        // For any reason user wasn't remapped ok, stop processing this
3435
        if (empty($data->userid)) {
3436
            return;
3437
        }
3438
 
3439
        // Everything ready, let's delegate to the restore_logs_processor
3440
 
3441
        // Set some fixed values that will save tons of DB requests
3442
        $values = array(
3443
            'course' => $this->get_courseid(),
3444
            'course_module' => $this->task->get_moduleid(),
3445
            $this->task->get_modulename() => $this->task->get_activityid());
3446
        // Get instance and process log record
3447
        $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3448
 
3449
        // If we have data, insert it, else something went wrong in the restore_logs_processor
3450
        if ($data) {
3451
            if (empty($data->url)) {
3452
                $data->url = '';
3453
            }
3454
            if (empty($data->info)) {
3455
                $data->info = '';
3456
            }
3457
            // Store the data in the legacy log table if we are still using it.
3458
            $manager = get_log_manager();
3459
            if (method_exists($manager, 'legacy_add_to_log')) {
3460
                $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3461
                    $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3462
            }
3463
        }
3464
    }
3465
}
3466
 
3467
/**
3468
 * Structure step in charge of restoring the logstores.xml file for the course logs.
3469
 *
3470
 * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3471
 * it, for logs belonging to the course level.
3472
 */
3473
class restore_course_logstores_structure_step extends restore_structure_step {
3474
 
3475
    /**
3476
     * Conditionally decide if this step should be executed.
3477
     *
3478
     * This function checks the following parameter:
3479
     *
3480
     *   1. the logstores.xml file exists
3481
     *
3482
     * @return bool true is safe to execute, false otherwise
3483
     */
3484
    protected function execute_condition() {
3485
 
3486
        // Check it is included in the backup.
3487
        $fullpath = $this->task->get_taskbasepath();
3488
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3489
        if (!file_exists($fullpath)) {
3490
            // Not found, can't restore logstores.xml information.
3491
            return false;
3492
        }
3493
 
3494
        return true;
3495
    }
3496
 
3497
    /**
3498
     * Return the elements to be processed on restore of logstores.
3499
     *
3500
     * @return restore_path_element[] array of elements to be processed on restore.
3501
     */
3502
    protected function define_structure() {
3503
 
3504
        $paths = array();
3505
 
3506
        $logstore = new restore_path_element('logstore', '/logstores/logstore');
3507
        $paths[] = $logstore;
3508
 
3509
        // Add logstore subplugin support to the 'logstore' element.
3510
        $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3511
 
3512
        return array($logstore);
3513
    }
3514
 
3515
    /**
3516
     * Process the 'logstore' element,
3517
     *
3518
     * Note: This is empty by definition in backup, because stores do not share any
3519
     * data between them, so there is nothing to process here.
3520
     *
3521
     * @param array $data element data
3522
     */
3523
    protected function process_logstore($data) {
3524
        return;
3525
    }
3526
}
3527
 
3528
/**
3529
 * Structure step in charge of restoring the loglastaccess.xml file for the course logs.
3530
 *
3531
 * This restore step will rebuild the table for user_lastaccess table.
3532
 */
3533
class restore_course_loglastaccess_structure_step extends restore_structure_step {
3534
 
3535
    /**
3536
     * Conditionally decide if this step should be executed.
3537
     *
3538
     * This function checks the following parameter:
3539
     *
3540
     *   1. the loglastaccess.xml file exists
3541
     *
3542
     * @return bool true is safe to execute, false otherwise
3543
     */
3544
    protected function execute_condition() {
3545
        // Check it is included in the backup.
3546
        $fullpath = $this->task->get_taskbasepath();
3547
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3548
        if (!file_exists($fullpath)) {
3549
            // Not found, can't restore loglastaccess.xml information.
3550
            return false;
3551
        }
3552
 
3553
        return true;
3554
    }
3555
 
3556
    /**
3557
     * Return the elements to be processed on restore of loglastaccess.
3558
     *
3559
     * @return restore_path_element[] array of elements to be processed on restore.
3560
     */
3561
    protected function define_structure() {
3562
 
3563
        $paths = array();
3564
        // To know if we are including userinfo.
3565
        $userinfo = $this->get_setting_value('users');
3566
 
3567
        if ($userinfo) {
3568
            $paths[] = new restore_path_element('lastaccess', '/lastaccesses/lastaccess');
3569
        }
3570
        // Return the paths wrapped.
3571
        return $paths;
3572
    }
3573
 
3574
    /**
3575
     * Process the 'lastaccess' elements.
3576
     *
3577
     * @param array $data element data
3578
     */
3579
    protected function process_lastaccess($data) {
3580
        global $DB;
3581
 
3582
        $data = (object)$data;
3583
 
3584
        $data->courseid = $this->get_courseid();
3585
        if (!$data->userid = $this->get_mappingid('user', $data->userid)) {
3586
            return; // Nothing to do, not able to find the user to set the lastaccess time.
3587
        }
3588
 
3589
        // Check if record does exist.
3590
        $exists = $DB->get_record('user_lastaccess', array('courseid' => $data->courseid, 'userid' => $data->userid));
3591
        if ($exists) {
3592
            // If the time of last access of the restore is newer, then replace and update.
3593
            if ($exists->timeaccess < $data->timeaccess) {
3594
                $exists->timeaccess = $data->timeaccess;
3595
                $DB->update_record('user_lastaccess', $exists);
3596
            }
3597
        } else {
3598
            $DB->insert_record('user_lastaccess', $data);
3599
        }
3600
    }
3601
}
3602
 
3603
/**
3604
 * Structure step in charge of restoring the logstores.xml file for the activity logs.
3605
 *
3606
 * Note: Activity structure is completely equivalent to the course one, so just extend it.
3607
 */
3608
class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3609
}
3610
 
3611
/**
3612
 * Restore course competencies structure step.
3613
 */
3614
class restore_course_competencies_structure_step extends restore_structure_step {
3615
 
3616
    /**
3617
     * Returns the structure.
3618
     *
3619
     * @return array
3620
     */
3621
    protected function define_structure() {
3622
        $userinfo = $this->get_setting_value('users');
3623
        $paths = array(
3624
            new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3625
            new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3626
        );
3627
        if ($userinfo) {
3628
            $paths[] = new restore_path_element('user_competency_course',
3629
                '/course_competencies/user_competencies/user_competency');
3630
        }
3631
        return $paths;
3632
    }
3633
 
3634
    /**
3635
     * Process a course competency settings.
3636
     *
3637
     * @param array $data The data.
3638
     */
3639
    public function process_course_competency_settings($data) {
3640
        global $DB;
3641
        $data = (object) $data;
3642
 
3643
        // We do not restore the course settings during merge.
3644
        $target = $this->get_task()->get_target();
3645
        if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) {
3646
            return;
3647
        }
3648
 
3649
        $courseid = $this->task->get_courseid();
3650
        $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3651
            array('courseid' => $courseid));
3652
 
3653
        // Strangely the course settings already exist, let's just leave them as is then.
3654
        if ($exists) {
3655
            $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING);
3656
            return;
3657
        }
3658
 
3659
        $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3660
        $settings = new \core_competency\course_competency_settings(0, $data);
3661
        $settings->create();
3662
    }
3663
 
3664
    /**
3665
     * Process a course competency.
3666
     *
3667
     * @param array $data The data.
3668
     */
3669
    public function process_course_competency($data) {
3670
        $data = (object) $data;
3671
 
3672
        // Mapping the competency by ID numbers.
3673
        $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3674
        if (!$framework) {
3675
            return;
3676
        }
3677
        $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3678
            'competencyframeworkid' => $framework->get('id')));
3679
        if (!$competency) {
3680
            return;
3681
        }
3682
        $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get('id'));
3683
 
3684
        $params = array(
3685
            'competencyid' => $competency->get('id'),
3686
            'courseid' => $this->task->get_courseid()
3687
        );
3688
        $query = 'competencyid = :competencyid AND courseid = :courseid';
3689
        $existing = \core_competency\course_competency::record_exists_select($query, $params);
3690
 
3691
        if (!$existing) {
3692
            // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3693
            $record = (object) $params;
3694
            $record->ruleoutcome = $data->ruleoutcome;
3695
            $coursecompetency = new \core_competency\course_competency(0, $record);
3696
            $coursecompetency->create();
3697
        }
3698
    }
3699
 
3700
    /**
3701
     * Process the user competency course.
3702
     *
3703
     * @param array $data The data.
3704
     */
3705
    public function process_user_competency_course($data) {
3706
        global $USER, $DB;
3707
        $data = (object) $data;
3708
 
3709
        $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid);
3710
        if (!$data->competencyid) {
3711
            // This is strange, the competency does not belong to the course.
3712
            return;
3713
        } else if ($data->grade === null) {
3714
            // We do not need to do anything when there is no grade.
3715
            return;
3716
        }
3717
 
3718
        $data->userid = $this->get_mappingid('user', $data->userid);
3719
        $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
3720
 
3721
        // The method add_evidence also sets the course rating.
3722
        \core_competency\api::add_evidence($data->userid,
3723
                                           $data->competencyid,
3724
                                           $this->task->get_contextid(),
3725
                                           \core_competency\evidence::ACTION_OVERRIDE,
3726
                                           'evidence_courserestored',
3727
                                           'core_competency',
3728
                                           $shortname,
3729
                                           false,
3730
                                           null,
3731
                                           $data->grade,
3732
                                           $USER->id);
3733
    }
3734
 
3735
    /**
3736
     * Execute conditions.
3737
     *
3738
     * @return bool
3739
     */
3740
    protected function execute_condition() {
3741
 
3742
        // Do not execute if competencies are not included.
3743
        if (!$this->get_setting_value('competencies')) {
3744
            return false;
3745
        }
3746
 
3747
        // Do not execute if the competencies XML file is not found.
3748
        $fullpath = $this->task->get_taskbasepath();
3749
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3750
        if (!file_exists($fullpath)) {
3751
            return false;
3752
        }
3753
 
3754
        return true;
3755
    }
3756
}
3757
 
3758
/**
3759
 * Restore activity competencies structure step.
3760
 */
3761
class restore_activity_competencies_structure_step extends restore_structure_step {
3762
 
3763
    /**
3764
     * Defines the structure.
3765
     *
3766
     * @return array
3767
     */
3768
    protected function define_structure() {
3769
        $paths = array(
3770
            new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3771
        );
3772
        return $paths;
3773
    }
3774
 
3775
    /**
3776
     * Process a course module competency.
3777
     *
3778
     * @param array $data The data.
3779
     */
3780
    public function process_course_module_competency($data) {
3781
        $data = (object) $data;
3782
 
3783
        // Mapping the competency by ID numbers.
3784
        $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3785
        if (!$framework) {
3786
            return;
3787
        }
3788
        $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3789
            'competencyframeworkid' => $framework->get('id')));
3790
        if (!$competency) {
3791
            return;
3792
        }
3793
 
3794
        $params = array(
3795
            'competencyid' => $competency->get('id'),
3796
            'cmid' => $this->task->get_moduleid()
3797
        );
3798
        $query = 'competencyid = :competencyid AND cmid = :cmid';
3799
        $existing = \core_competency\course_module_competency::record_exists_select($query, $params);
3800
 
3801
        if (!$existing) {
3802
            // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3803
            $record = (object) $params;
3804
            $record->ruleoutcome = $data->ruleoutcome;
3805
            $record->overridegrade = $data->overridegrade ?? 0;
3806
            $coursemodulecompetency = new \core_competency\course_module_competency(0, $record);
3807
            $coursemodulecompetency->create();
3808
        }
3809
    }
3810
 
3811
    /**
3812
     * Execute conditions.
3813
     *
3814
     * @return bool
3815
     */
3816
    protected function execute_condition() {
3817
 
3818
        // Do not execute if competencies are not included.
3819
        if (!$this->get_setting_value('competencies')) {
3820
            return false;
3821
        }
3822
 
3823
        // Do not execute if the competencies XML file is not found.
3824
        $fullpath = $this->task->get_taskbasepath();
3825
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3826
        if (!file_exists($fullpath)) {
3827
            return false;
3828
        }
3829
 
3830
        return true;
3831
    }
3832
}
3833
 
3834
/**
3835
 * Defines the restore step for advanced grading methods attached to the activity module
3836
 */
3837
class restore_activity_grading_structure_step extends restore_structure_step {
3838
 
3839
    /**
3840
     * This step is executed only if the grading file is present
3841
     */
3842
     protected function execute_condition() {
3843
 
3844
        if ($this->get_courseid() == SITEID) {
3845
            return false;
3846
        }
3847
 
3848
        $fullpath = $this->task->get_taskbasepath();
3849
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3850
        if (!file_exists($fullpath)) {
3851
            return false;
3852
        }
3853
 
3854
        return true;
3855
    }
3856
 
3857
 
3858
    /**
3859
     * Declares paths in the grading.xml file we are interested in
3860
     */
3861
    protected function define_structure() {
3862
 
3863
        $paths = array();
3864
        $userinfo = $this->get_setting_value('userinfo');
3865
 
3866
        $area = new restore_path_element('grading_area', '/areas/area');
3867
        $paths[] = $area;
3868
        // attach local plugin stucture to $area element
3869
        $this->add_plugin_structure('local', $area);
3870
 
3871
        $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
3872
        $paths[] = $definition;
3873
        $this->add_plugin_structure('gradingform', $definition);
3874
        // attach local plugin stucture to $definition element
3875
        $this->add_plugin_structure('local', $definition);
3876
 
3877
 
3878
        if ($userinfo) {
3879
            $instance = new restore_path_element('grading_instance',
3880
                '/areas/area/definitions/definition/instances/instance');
3881
            $paths[] = $instance;
3882
            $this->add_plugin_structure('gradingform', $instance);
3883
            // attach local plugin stucture to $intance element
3884
            $this->add_plugin_structure('local', $instance);
3885
        }
3886
 
3887
        return $paths;
3888
    }
3889
 
3890
    /**
3891
     * Processes one grading area element
3892
     *
3893
     * @param array $data element data
3894
     */
3895
    protected function process_grading_area($data) {
3896
        global $DB;
3897
 
3898
        $task = $this->get_task();
3899
        $data = (object)$data;
3900
        $oldid = $data->id;
3901
        $data->component = 'mod_'.$task->get_modulename();
3902
        $data->contextid = $task->get_contextid();
3903
 
3904
        $newid = $DB->insert_record('grading_areas', $data);
3905
        $this->set_mapping('grading_area', $oldid, $newid);
3906
    }
3907
 
3908
    /**
3909
     * Processes one grading definition element
3910
     *
3911
     * @param array $data element data
3912
     */
3913
    protected function process_grading_definition($data) {
3914
        global $DB;
3915
 
3916
        $task = $this->get_task();
3917
        $data = (object)$data;
3918
        $oldid = $data->id;
3919
        $data->areaid = $this->get_new_parentid('grading_area');
3920
        $data->copiedfromid = null;
3921
        $data->timecreated = time();
3922
        $data->usercreated = $task->get_userid();
3923
        $data->timemodified = $data->timecreated;
3924
        $data->usermodified = $data->usercreated;
3925
 
3926
        $newid = $DB->insert_record('grading_definitions', $data);
3927
        $this->set_mapping('grading_definition', $oldid, $newid, true);
3928
    }
3929
 
3930
    /**
3931
     * Processes one grading form instance element
3932
     *
3933
     * @param array $data element data
3934
     */
3935
    protected function process_grading_instance($data) {
3936
        global $DB;
3937
 
3938
        $data = (object)$data;
3939
 
3940
        // new form definition id
3941
        $newformid = $this->get_new_parentid('grading_definition');
3942
 
3943
        // get the name of the area we are restoring to
3944
        $sql = "SELECT ga.areaname
3945
                  FROM {grading_definitions} gd
3946
                  JOIN {grading_areas} ga ON gd.areaid = ga.id
3947
                 WHERE gd.id = ?";
3948
        $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
3949
 
3950
        // get the mapped itemid - the activity module is expected to define the mappings
3951
        // for each gradable area
3952
        $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
3953
 
3954
        $oldid = $data->id;
3955
        $data->definitionid = $newformid;
3956
        $data->raterid = $this->get_mappingid('user', $data->raterid);
3957
        $data->itemid = $newitemid;
3958
 
3959
        $newid = $DB->insert_record('grading_instances', $data);
3960
        $this->set_mapping('grading_instance', $oldid, $newid);
3961
    }
3962
 
3963
    /**
3964
     * Final operations when the database records are inserted
3965
     */
3966
    protected function after_execute() {
3967
        // Add files embedded into the definition description
3968
        $this->add_related_files('grading', 'description', 'grading_definition');
3969
    }
3970
}
3971
 
3972
 
3973
/**
3974
 * This structure step restores the grade items associated with one activity
3975
 * All the grade items are made child of the "course" grade item but the original
3976
 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3977
 * the complete gradebook (categories and calculations), that information is
3978
 * available there
3979
 */
3980
class restore_activity_grades_structure_step extends restore_structure_step {
3981
 
3982
    /**
3983
     * No grades in front page.
3984
     * @return bool
3985
     */
3986
    protected function execute_condition() {
3987
        return ($this->get_courseid() != SITEID);
3988
    }
3989
 
3990
    protected function define_structure() {
3991
 
3992
        $paths = array();
3993
        $userinfo = $this->get_setting_value('userinfo');
3994
 
3995
        $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3996
        $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3997
        if ($userinfo) {
3998
            $paths[] = new restore_path_element('grade_grade',
3999
                           '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
4000
        }
4001
        return $paths;
4002
    }
4003
 
4004
    protected function process_grade_item($data) {
4005
        global $DB;
4006
 
4007
        $data = (object)($data);
4008
        $oldid       = $data->id;        // We'll need these later
4009
        $oldparentid = $data->categoryid;
4010
        $courseid = $this->get_courseid();
4011
 
4012
        $idnumber = null;
4013
        if (!empty($data->idnumber)) {
4014
            // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
4015
            // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
4016
            // so the best is to keep the ones already in the gradebook
4017
            // Potential problem: duplicates if same items are restored more than once. :-(
4018
            // This needs to be fixed in some way (outcomes & activities with multiple items)
4019
            // $data->idnumber     = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
4020
            // In any case, verify always for uniqueness
4021
            $sql = "SELECT cm.id
4022
                      FROM {course_modules} cm
4023
                     WHERE cm.course = :courseid AND
4024
                           cm.idnumber = :idnumber AND
4025
                           cm.id <> :cmid";
4026
            $params = array(
4027
                'courseid' => $courseid,
4028
                'idnumber' => $data->idnumber,
4029
                'cmid' => $this->task->get_moduleid()
4030
            );
4031
            if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
4032
                $idnumber = $data->idnumber;
4033
            }
4034
        }
4035
 
4036
        if (!empty($data->categoryid)) {
4037
            // If the grade category id of the grade item being restored belongs to this course
4038
            // then it is a fair assumption that this is the correct grade category for the activity
4039
            // and we should leave it in place, if not then unset it.
4040
            // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
4041
            $conditions = array('id' => $data->categoryid, 'courseid' => $courseid);
4042
            if (!$this->task->is_samesite() || !$DB->record_exists('grade_categories', $conditions)) {
4043
                unset($data->categoryid);
4044
            }
4045
        }
4046
 
4047
        unset($data->id);
4048
        $data->courseid     = $this->get_courseid();
4049
        $data->iteminstance = $this->task->get_activityid();
4050
        $data->idnumber     = $idnumber;
4051
        $data->scaleid      = $this->get_mappingid('scale', $data->scaleid);
4052
        $data->outcomeid    = $this->get_mappingid('outcome', $data->outcomeid);
4053
 
4054
        $gradeitem = new grade_item($data, false);
4055
        $gradeitem->insert('restore');
4056
 
4057
        //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
4058
        $gradeitem->sortorder = $data->sortorder;
4059
        $gradeitem->update('restore');
4060
 
4061
        // Set mapping, saving the original category id into parentitemid
4062
        // gradebook restore (final task) will need it to reorganise items
4063
        $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
4064
    }
4065
 
4066
    protected function process_grade_grade($data) {
4067
        global $CFG;
4068
 
4069
        require_once($CFG->libdir . '/grade/constants.php');
4070
 
4071
        $data = (object)($data);
4072
        $olduserid = $data->userid;
4073
        $oldid = $data->id;
4074
        unset($data->id);
4075
 
4076
        $data->itemid = $this->get_new_parentid('grade_item');
4077
 
4078
        $data->userid = $this->get_mappingid('user', $data->userid, null);
4079
        if (!empty($data->userid)) {
4080
            $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4081
            $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4082
 
4083
            $grade = new grade_grade($data, false);
4084
            $grade->insert('restore');
4085
 
4086
            $this->set_mapping('grade_grades', $oldid, $grade->id, true);
4087
 
4088
            $this->add_related_files(
4089
                GRADE_FILE_COMPONENT,
4090
                GRADE_FEEDBACK_FILEAREA,
4091
                'grade_grades',
4092
                null,
4093
                $oldid
4094
            );
4095
        } else {
4096
            debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
4097
        }
4098
    }
4099
 
4100
    /**
4101
     * process activity grade_letters. Note that, while these are possible,
4102
     * because grade_letters are contextid based, in practice, only course
4103
     * context letters can be defined. So we keep here this method knowing
4104
     * it won't be executed ever. gradebook restore will restore course letters.
4105
     */
4106
    protected function process_grade_letter($data) {
4107
        global $DB;
4108
 
4109
        $data['contextid'] = $this->task->get_contextid();
4110
        $gradeletter = (object)$data;
4111
 
4112
        // Check if it exists before adding it
4113
        unset($data['id']);
4114
        if (!$DB->record_exists('grade_letters', $data)) {
4115
            $newitemid = $DB->insert_record('grade_letters', $gradeletter);
4116
        }
4117
        // no need to save any grade_letter mapping
4118
    }
4119
 
4120
    public function after_restore() {
4121
        // Fix grade item's sortorder after restore, as it might have duplicates.
4122
        $courseid = $this->get_task()->get_courseid();
4123
        grade_item::fix_duplicate_sortorder($courseid);
4124
    }
4125
}
4126
 
4127
/**
4128
 * Step in charge of restoring the grade history of an activity.
4129
 *
4130
 * This step is added to the task regardless of the setting 'grade_histories'.
4131
 * The reason is to allow for a more flexible step in case the logic needs to be
4132
 * split accross different settings to control the history of items and/or grades.
4133
 */
4134
class restore_activity_grade_history_structure_step extends restore_structure_step {
4135
 
4136
    /**
4137
     * This step is executed only if the grade history file is present.
4138
     */
4139
     protected function execute_condition() {
4140
 
4141
        if ($this->get_courseid() == SITEID) {
4142
            return false;
4143
        }
4144
 
4145
        $fullpath = $this->task->get_taskbasepath();
4146
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4147
        if (!file_exists($fullpath)) {
4148
            return false;
4149
        }
4150
        return true;
4151
    }
4152
 
4153
    protected function define_structure() {
4154
        $paths = array();
4155
 
4156
        // Settings to use.
4157
        $userinfo = $this->get_setting_value('userinfo');
4158
        $history = $this->get_setting_value('grade_histories');
4159
 
4160
        if ($userinfo && $history) {
4161
            $paths[] = new restore_path_element('grade_grade',
4162
               '/grade_history/grade_grades/grade_grade');
4163
        }
4164
 
4165
        return $paths;
4166
    }
4167
 
4168
    protected function process_grade_grade($data) {
4169
        global $CFG, $DB;
4170
 
4171
        require_once($CFG->libdir . '/grade/constants.php');
4172
 
4173
        $data = (object) $data;
4174
        $oldhistoryid = $data->id;
4175
        $olduserid = $data->userid;
4176
        unset($data->id);
4177
 
4178
        $data->userid = $this->get_mappingid('user', $data->userid, null);
4179
        if (!empty($data->userid)) {
4180
            // Do not apply the date offsets as this is history.
4181
            $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
4182
            $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
4183
            $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4184
            $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4185
 
4186
            $newhistoryid = $DB->insert_record('grade_grades_history', $data);
4187
 
4188
            $this->set_mapping('grade_grades_history', $oldhistoryid, $newhistoryid, true);
4189
 
4190
            $this->add_related_files(
4191
                GRADE_FILE_COMPONENT,
4192
                GRADE_HISTORY_FEEDBACK_FILEAREA,
4193
                'grade_grades_history',
4194
                null,
4195
                $oldhistoryid
4196
            );
4197
        } else {
4198
            $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
4199
            $this->log($message, backup::LOG_DEBUG);
4200
        }
4201
    }
4202
}
4203
 
4204
/**
4205
 * This structure steps restores the content bank content
4206
 */
4207
class restore_contentbankcontent_structure_step extends restore_structure_step {
4208
 
4209
    /**
4210
     * Define structure for content bank step
4211
     */
4212
    protected function define_structure() {
4213
 
4214
        $paths = [];
4215
        $paths[] = new restore_path_element('contentbankcontent', '/contents/content');
4216
 
4217
        return $paths;
4218
    }
4219
 
4220
    /**
4221
     * Define data processed for content bank
4222
     *
4223
     * @param mixed  $data
4224
     */
4225
    public function process_contentbankcontent($data) {
4226
        global $DB;
4227
 
4228
        $data = (object)$data;
4229
        $oldid = $data->id;
4230
 
4231
        $params = [
4232
            'name'           => $data->name,
4233
            'contextid'      => $this->task->get_contextid(),
4234
            'contenttype'    => $data->contenttype,
4235
            'instanceid'     => $data->instanceid,
4236
            'timecreated'    => $data->timecreated,
4237
        ];
4238
        $exists = $DB->record_exists('contentbank_content', $params);
4239
        if (!$exists) {
4240
            $params['configdata'] = $data->configdata;
4241
            $params['timemodified'] = time();
4242
 
4243
            // Trying to map users. Users cannot always be mapped, e.g. when copying.
4244
            $params['usercreated'] = $this->get_mappingid('user', $data->usercreated);
4245
            if (!$params['usercreated']) {
4246
                // Leave the content creator unchanged when we are restoring the same site.
4247
                // Otherwise use current user id.
4248
                if ($this->task->is_samesite()) {
4249
                    $params['usercreated'] = $data->usercreated;
4250
                } else {
4251
                    $params['usercreated'] = $this->task->get_userid();
4252
                }
4253
            }
4254
            $params['usermodified'] = $this->get_mappingid('user', $data->usermodified);
4255
            if (!$params['usermodified']) {
4256
                // Leave the content modifier unchanged when we are restoring the same site.
4257
                // Otherwise use current user id.
4258
                if ($this->task->is_samesite()) {
4259
                    $params['usermodified'] = $data->usermodified;
4260
                } else {
4261
                    $params['usermodified'] = $this->task->get_userid();
4262
                }
4263
            }
4264
 
4265
            $newitemid = $DB->insert_record('contentbank_content', $params);
4266
            $this->set_mapping('contentbank_content', $oldid, $newitemid, true);
4267
        }
4268
    }
4269
 
4270
    /**
4271
     * Define data processed after execute for content bank
4272
     */
4273
    protected function after_execute() {
4274
        // Add related files.
4275
        $this->add_related_files('contentbank', 'public', 'contentbank_content');
4276
    }
4277
}
4278
 
4279
/**
4280
 * This structure steps restores the xAPI states.
4281
 */
4282
class restore_xapistate_structure_step extends restore_structure_step {
4283
 
4284
    /**
4285
     * Define structure for xAPI state step
4286
     */
4287
    protected function define_structure() {
4288
        return [new restore_path_element('xapistate', '/states/state')];
4289
    }
4290
 
4291
    /**
4292
     * Define data processed for xAPI state.
4293
     *
4294
     * @param array|stdClass $data
4295
     */
4296
    public function process_xapistate($data) {
4297
        global $DB;
4298
 
4299
        $data = (object)$data;
4300
        $oldid = $data->id;
4301
        $exists = false;
4302
 
4303
        $params = [
4304
            'component' => $data->component,
4305
            'itemid' => $this->task->get_contextid(),
4306
            // Set stateid to 'restored', to let plugins identify the origin of this state is a backup.
4307
            'stateid' => 'restored',
4308
            'statedata' => $data->statedata,
4309
            'registration' => $data->registration,
4310
            'timecreated' => $data->timecreated,
4311
            'timemodified' => time(),
4312
        ];
4313
 
4314
        // Trying to map users. Users cannot always be mapped, for instance, when copying.
4315
        $params['userid'] = $this->get_mappingid('user', $data->userid);
4316
        if (!$params['userid']) {
4317
            // Leave the userid unchanged when we are restoring the same site.
4318
            if ($this->task->is_samesite()) {
4319
                $params['userid'] = $data->userid;
4320
            }
4321
            $filter = $params;
4322
            unset($filter['statedata']);
4323
            $exists = $DB->record_exists('xapi_states', $filter);
4324
        }
4325
 
4326
        if (!$exists && $params['userid']) {
4327
            // Only insert the record if the user exists or can be mapped.
4328
            $newitemid = $DB->insert_record('xapi_states', $params);
4329
            $this->set_mapping('xapi_states', $oldid, $newitemid, true);
4330
        }
4331
    }
4332
}
4333
 
4334
/**
4335
 * This structure steps restores one instance + positions of one block
4336
 * Note: Positions corresponding to one existing context are restored
4337
 * here, but all the ones having unknown contexts are sent to backup_ids
4338
 * for a later chance to be restored at the end (final task)
4339
 */
4340
class restore_block_instance_structure_step extends restore_structure_step {
4341
 
4342
    protected function define_structure() {
4343
 
4344
        $paths = array();
4345
 
4346
        $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
4347
        $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
4348
 
4349
        return $paths;
4350
    }
4351
 
4352
    public function process_block($data) {
4353
        global $DB, $CFG;
4354
 
4355
        $data = (object)$data; // Handy
4356
        $oldcontextid = $data->contextid;
4357
        $oldid        = $data->id;
4358
        $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
4359
 
4360
        // Look for the parent contextid
4361
        if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
4362
            // Parent contextid does not exist, ignore this block.
4363
            return false;
4364
        }
4365
 
4366
        // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
4367
        // If there is already one block of that type in the parent context
4368
        // and the block is not multiple, stop processing
4369
        // Use blockslib loader / method executor
4370
        if (!$bi = block_instance($data->blockname)) {
4371
            return false;
4372
        }
4373
 
4374
        if (!$bi->instance_allow_multiple()) {
4375
            // The block cannot be added twice, so we will check if the same block is already being
4376
            // displayed on the same page. For this, rather than mocking a page and using the block_manager
4377
            // we use a similar query to the one in block_manager::load_blocks(), this will give us
4378
            // a very good idea of the blocks already displayed in the context.
4379
            $params =  array(
4380
                'blockname' => $data->blockname
4381
            );
4382
 
4383
            // Context matching test.
4384
            $context = context::instance_by_id($data->parentcontextid);
4385
            $contextsql = 'bi.parentcontextid = :contextid';
4386
            $params['contextid'] = $context->id;
4387
 
4388
            $parentcontextids = $context->get_parent_context_ids();
4389
            if ($parentcontextids) {
4390
                list($parentcontextsql, $parentcontextparams) =
4391
                        $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
4392
                $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
4393
                $params = array_merge($params, $parentcontextparams);
4394
            }
4395
 
4396
            // Page type pattern test.
4397
            $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
4398
            list($pagetypepatternsql, $pagetypepatternparams) =
4399
                $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
4400
            $params = array_merge($params, $pagetypepatternparams);
4401
 
4402
            // Sub page pattern test.
4403
            $subpagepatternsql = 'bi.subpagepattern IS NULL';
4404
            if ($data->subpagepattern !== null) {
4405
                $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
4406
                $params['subpagepattern'] = $data->subpagepattern;
4407
            }
4408
 
4409
            $existingblock = $DB->get_records_sql("SELECT bi.id
4410
                                                FROM {block_instances} bi
4411
                                                JOIN {block} b ON b.name = bi.blockname
4412
                                               WHERE bi.blockname = :blockname
4413
                                                 AND $contextsql
4414
                                                 AND bi.pagetypepattern $pagetypepatternsql
4415
                                                 AND $subpagepatternsql", $params);
4416
            if (!empty($existingblock)) {
4417
                // Save the context mapping in case something else is linking to this block's context.
4418
                $newcontext = context_block::instance(reset($existingblock)->id);
4419
                $this->set_mapping('context', $oldcontextid, $newcontext->id);
4420
                // There is at least one very similar block visible on the page where we
4421
                // are trying to restore the block. In these circumstances the block API
4422
                // would not allow the user to add another instance of the block, so we
4423
                // apply the same rule here.
4424
                return false;
4425
            }
4426
        }
4427
 
4428
        // If there is already one block of that type in the parent context
4429
        // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
4430
        // stop processing
4431
        $params = array(
4432
            'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
4433
            'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
4434
            'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
4435
        if ($birecs = $DB->get_records('block_instances', $params)) {
4436
            foreach($birecs as $birec) {
4437
                if ($birec->configdata == $data->configdata) {
4438
                    // Save the context mapping in case something else is linking to this block's context.
4439
                    $newcontext = context_block::instance($birec->id);
4440
                    $this->set_mapping('context', $oldcontextid, $newcontext->id);
4441
                    return false;
4442
                }
4443
            }
4444
        }
4445
 
4446
        // Set task old contextid, blockid and blockname once we know them
4447
        $this->task->set_old_contextid($oldcontextid);
4448
        $this->task->set_old_blockid($oldid);
4449
        $this->task->set_blockname($data->blockname);
4450
 
4451
        // Let's look for anything within configdata neededing processing
4452
        // (nulls and uses of legacy file.php)
4453
        if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
4454
            $configdata = array_filter(
4455
                (array) unserialize_object(base64_decode($data->configdata)),
4456
                static function($value): bool {
4457
                    return !($value instanceof __PHP_Incomplete_Class);
4458
                }
4459
            );
4460
 
4461
            foreach ($configdata as $attribute => $value) {
4462
                if (in_array($attribute, $attrstotransform)) {
4463
                    $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
4464
                }
4465
            }
4466
            $data->configdata = base64_encode(serialize((object)$configdata));
4467
        }
4468
 
4469
        // Set timecreated, timemodified if not included (older backup).
4470
        if (empty($data->timecreated)) {
4471
            $data->timecreated = time();
4472
        }
4473
        if (empty($data->timemodified)) {
4474
            $data->timemodified = $data->timecreated;
4475
        }
4476
 
4477
        // Create the block instance
4478
        $newitemid = $DB->insert_record('block_instances', $data);
4479
        // Save the mapping (with restorefiles support)
4480
        $this->set_mapping('block_instance', $oldid, $newitemid, true);
4481
        // Create the block context
4482
        $newcontextid = context_block::instance($newitemid)->id;
4483
        // Save the block contexts mapping and sent it to task
4484
        $this->set_mapping('context', $oldcontextid, $newcontextid);
4485
        $this->task->set_contextid($newcontextid);
4486
        $this->task->set_blockid($newitemid);
4487
 
4488
        // Restore block fileareas if declared
4489
        $component = 'block_' . $this->task->get_blockname();
4490
        foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
4491
            $this->add_related_files($component, $filearea, null);
4492
        }
4493
 
4494
        // Process block positions, creating them or accumulating for final step
4495
        foreach($positions as $position) {
4496
            $position = (object)$position;
4497
            $position->blockinstanceid = $newitemid; // The instance is always the restored one
4498
            // If position is for one already mapped (known) contextid
4499
            // process it now, creating the position
4500
            if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
4501
                $position->contextid = $newpositionctxid;
4502
                // Create the block position
4503
                $DB->insert_record('block_positions', $position);
4504
 
4505
            // The position belongs to an unknown context, send it to backup_ids
4506
            // to process them as part of the final steps of restore. We send the
4507
            // whole $position object there, hence use the low level method.
4508
            } else {
4509
                restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
4510
            }
4511
        }
4512
    }
4513
}
4514
 
4515
/**
4516
 * Structure step to restore common course_module information
4517
 *
4518
 * This step will process the module.xml file for one activity, in order to restore
4519
 * the corresponding information to the course_modules table, skipping various bits
4520
 * of information based on CFG settings (groupings, completion...) in order to fullfill
4521
 * all the reqs to be able to create the context to be used by all the rest of steps
4522
 * in the activity restore task
4523
 */
4524
class restore_module_structure_step extends restore_structure_step {
4525
 
4526
    protected function define_structure() {
4527
        global $CFG;
4528
 
4529
        $paths = array();
4530
 
4531
        $module = new restore_path_element('module', '/module');
4532
        $paths[] = $module;
4533
        if ($CFG->enableavailability) {
4534
            $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
4535
            $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
4536
        }
4537
 
4538
        $paths[] = new restore_path_element('tag', '/module/tags/tag');
4539
 
4540
        // Apply for 'format' plugins optional paths at module level
4541
        $this->add_plugin_structure('format', $module);
4542
 
4543
        // Apply for 'report' plugins optional paths at module level.
4544
        $this->add_plugin_structure('report', $module);
4545
 
4546
        // Apply for 'plagiarism' plugins optional paths at module level
4547
        $this->add_plugin_structure('plagiarism', $module);
4548
 
4549
        // Apply for 'local' plugins optional paths at module level
4550
        $this->add_plugin_structure('local', $module);
4551
 
4552
        // Apply for 'admin tool' plugins optional paths at module level.
4553
        $this->add_plugin_structure('tool', $module);
4554
 
4555
        return $paths;
4556
    }
4557
 
4558
    protected function process_module($data) {
4559
        global $CFG, $DB;
4560
 
4561
        $data = (object)$data;
4562
        $oldid = $data->id;
4563
        $this->task->set_old_moduleversion($data->version);
4564
 
4565
        $data->course = $this->task->get_courseid();
4566
        $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
4567
        // Map section (first try by course_section mapping match. Useful in course and section restores)
4568
        $data->section = $this->get_mappingid('course_section', $data->sectionid);
4569
        if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
4570
            $params = array(
4571
                'course' => $this->get_courseid(),
4572
                'section' => $data->sectionnumber);
4573
            $data->section = $DB->get_field('course_sections', 'id', $params);
4574
        }
4575
        if (!$data->section) { // sectionnumber failed, try to get first section in course
4576
            $params = array(
4577
                'course' => $this->get_courseid());
4578
            $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
4579
        }
4580
        if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
4581
            $sectionrec = array(
4582
                'course' => $this->get_courseid(),
4583
                'section' => 0,
4584
                'timemodified' => time());
4585
            $DB->insert_record('course_sections', $sectionrec); // section 0
4586
            $sectionrec = array(
4587
                'course' => $this->get_courseid(),
4588
                'section' => 1,
4589
                'timemodified' => time());
4590
            $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
4591
        }
4592
        $data->groupingid= $this->get_mappingid('grouping', $data->groupingid);      // grouping
4593
        if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) {        // idnumber uniqueness
4594
            $data->idnumber = '';
4595
        }
4596
        if (empty($CFG->enablecompletion)) { // completion
4597
            $data->completion = 0;
4598
            $data->completiongradeitemnumber = null;
4599
            $data->completionview = 0;
4600
            $data->completionexpected = 0;
4601
        } else {
4602
            $data->completionexpected = $this->apply_date_offset($data->completionexpected);
4603
        }
4604
        if (empty($CFG->enableavailability)) {
4605
            $data->availability = null;
4606
        }
4607
        // Backups that did not include showdescription, set it to default 0
4608
        // (this is not totally necessary as it has a db default, but just to
4609
        // be explicit).
4610
        if (!isset($data->showdescription)) {
4611
            $data->showdescription = 0;
4612
        }
4613
        $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
4614
 
4615
        if (empty($data->availability)) {
4616
            // If there are legacy availablility data fields (and no new format data),
4617
            // convert the old fields.
4618
            $data->availability = \core_availability\info::convert_legacy_fields(
4619
                    $data, false);
4620
        } else if (!empty($data->groupmembersonly)) {
4621
            // There is current availability data, but it still has groupmembersonly
4622
            // as well (2.7 backups), convert just that part.
4623
            require_once($CFG->dirroot . '/lib/db/upgradelib.php');
4624
            $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
4625
        }
4626
 
4627
        if (!has_capability('moodle/course:setforcedlanguage', context_course::instance($data->course))) {
4628
            unset($data->lang);
4629
        }
4630
 
4631
        // course_module record ready, insert it
4632
        $newitemid = $DB->insert_record('course_modules', $data);
4633
        // save mapping
4634
        $this->set_mapping('course_module', $oldid, $newitemid);
4635
        // set the new course_module id in the task
4636
        $this->task->set_moduleid($newitemid);
4637
        // we can now create the context safely
4638
        $ctxid = context_module::instance($newitemid)->id;
4639
        // set the new context id in the task
4640
        $this->task->set_contextid($ctxid);
4641
        // update sequence field in course_section
4642
        if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
4643
            $sequence .= ',' . $newitemid;
4644
        } else {
4645
            $sequence = $newitemid;
4646
        }
4647
 
4648
        $updatesection = new \stdClass();
4649
        $updatesection->id = $data->section;
4650
        $updatesection->sequence = $sequence;
4651
        $updatesection->timemodified = time();
4652
        $DB->update_record('course_sections', $updatesection);
4653
 
4654
        // If there is the legacy showavailability data, store this for later use.
4655
        // (This data is not present when restoring 'new' backups.)
4656
        if (isset($data->showavailability)) {
4657
            // Cache the showavailability flag using the backup_ids data field.
4658
            restore_dbops::set_backup_ids_record($this->get_restoreid(),
4659
                    'module_showavailability', $newitemid, 0, null,
4660
                    (object)array('showavailability' => $data->showavailability));
4661
        }
4662
    }
4663
 
4664
    /**
4665
     * Fetch all the existing because tag_set() deletes them
4666
     * so everything must be reinserted on each call.
4667
     *
4668
     * @param stdClass $data Record data
4669
     */
4670
    protected function process_tag($data) {
4671
        global $CFG;
4672
 
4673
        $data = (object)$data;
4674
 
4675
        if (core_tag_tag::is_enabled('core', 'course_modules')) {
4676
            $modcontext = context::instance_by_id($this->task->get_contextid());
4677
            $instanceid = $this->task->get_moduleid();
4678
 
4679
            core_tag_tag::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname);
4680
        }
4681
    }
4682
 
4683
    /**
4684
     * Process the legacy availability table record. This table does not exist
4685
     * in Moodle 2.7+ but we still support restore.
4686
     *
4687
     * @param stdClass $data Record data
4688
     */
4689
    protected function process_availability($data) {
4690
        $data = (object)$data;
4691
        // Simply going to store the whole availability record now, we'll process
4692
        // all them later in the final task (once all activities have been restored)
4693
        // Let's call the low level one to be able to store the whole object
4694
        $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
4695
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
4696
    }
4697
 
4698
    /**
4699
     * Process the legacy availability fields table record. This table does not
4700
     * exist in Moodle 2.7+ but we still support restore.
4701
     *
4702
     * @param stdClass $data Record data
4703
     */
4704
    protected function process_availability_field($data) {
4705
        global $DB, $CFG;
4706
        require_once($CFG->dirroot.'/user/profile/lib.php');
4707
 
4708
        $data = (object)$data;
4709
        // Mark it is as passed by default
4710
        $passed = true;
4711
        $customfieldid = null;
4712
 
4713
        // If a customfield has been used in order to pass we must be able to match an existing
4714
        // customfield by name (data->customfield) and type (data->customfieldtype)
4715
        if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
4716
            // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
4717
            // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
4718
            $passed = false;
4719
        } else if (!empty($data->customfield)) {
4720
            $field = profile_get_custom_field_data_by_shortname($data->customfield);
4721
            $passed = $field && $field->datatype == $data->customfieldtype;
4722
        }
4723
 
4724
        if ($passed) {
4725
            // Create the object to insert into the database
4726
            $availfield = new stdClass();
4727
            $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
4728
            $availfield->userfield = $data->userfield;
4729
            $availfield->customfieldid = $customfieldid;
4730
            $availfield->operator = $data->operator;
4731
            $availfield->value = $data->value;
4732
 
4733
            // Get showavailability option.
4734
            $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4735
                    'module_showavailability', $availfield->coursemoduleid);
4736
            if (!$showrec) {
4737
                // Should not happen.
4738
                throw new coding_exception('No matching showavailability record');
4739
            }
4740
            $show = $showrec->info->showavailability;
4741
 
4742
            // The $availfieldobject is now in the format used in the old
4743
            // system. Interpret this and convert to new system.
4744
            $currentvalue = $DB->get_field('course_modules', 'availability',
4745
                    array('id' => $availfield->coursemoduleid), MUST_EXIST);
4746
            $newvalue = \core_availability\info::add_legacy_availability_field_condition(
4747
                    $currentvalue, $availfield, $show);
4748
            $DB->set_field('course_modules', 'availability', $newvalue,
4749
                    array('id' => $availfield->coursemoduleid));
4750
        }
4751
    }
4752
    /**
4753
     * This method will be executed after the rest of the restore has been processed.
4754
     *
4755
     * Update old tag instance itemid(s).
4756
     */
4757
    protected function after_restore() {
4758
        global $DB;
4759
 
4760
        $contextid = $this->task->get_contextid();
4761
        $instanceid = $this->task->get_activityid();
4762
        $olditemid = $this->task->get_old_activityid();
4763
 
4764
        $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
4765
    }
4766
}
4767
 
4768
/**
4769
 * Structure step that will process the user activity completion
4770
 * information if all these conditions are met:
4771
 *  - Target site has completion enabled ($CFG->enablecompletion)
4772
 *  - Activity includes completion info (file_exists)
4773
 */
4774
class restore_userscompletion_structure_step extends restore_structure_step {
4775
    /**
4776
     * To conditionally decide if this step must be executed
4777
     * Note the "settings" conditions are evaluated in the
4778
     * corresponding task. Here we check for other conditions
4779
     * not being restore settings (files, site settings...)
4780
     */
4781
     protected function execute_condition() {
4782
         global $CFG;
4783
 
4784
         // Completion disabled in this site, don't execute
4785
         if (empty($CFG->enablecompletion)) {
4786
             return false;
4787
         }
4788
 
4789
        // No completion on the front page.
4790
        if ($this->get_courseid() == SITEID) {
4791
            return false;
4792
        }
4793
 
4794
         // No user completion info found, don't execute
4795
        $fullpath = $this->task->get_taskbasepath();
4796
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4797
         if (!file_exists($fullpath)) {
4798
             return false;
4799
         }
4800
 
4801
         // Arrived here, execute the step
4802
         return true;
4803
     }
4804
 
4805
     protected function define_structure() {
4806
 
4807
        $paths = array();
4808
 
4809
        // Restore completion.
4810
        $paths[] = new restore_path_element('completion', '/completions/completion');
4811
 
4812
        // Restore completion view.
4813
        $paths[] = new restore_path_element('completionview', '/completions/completionviews/completionview');
4814
 
4815
        return $paths;
4816
    }
4817
 
4818
    protected function process_completion($data) {
4819
        global $DB;
4820
 
4821
        $data = (object)$data;
4822
 
4823
        $data->coursemoduleid = $this->task->get_moduleid();
4824
        $data->userid = $this->get_mappingid('user', $data->userid);
4825
 
4826
        // Find the existing record
4827
        $existing = $DB->get_record('course_modules_completion', array(
4828
                'coursemoduleid' => $data->coursemoduleid,
4829
                'userid' => $data->userid), 'id, timemodified');
4830
        // Check we didn't already insert one for this cmid and userid
4831
        // (there aren't supposed to be duplicates in that field, but
4832
        // it was possible until MDL-28021 was fixed).
4833
        if ($existing) {
4834
            // Update it to these new values, but only if the time is newer
4835
            if ($existing->timemodified < $data->timemodified) {
4836
                $data->id = $existing->id;
4837
                $DB->update_record('course_modules_completion', $data);
4838
            }
4839
        } else {
4840
            // Normal entry where it doesn't exist already
4841
            $DB->insert_record('course_modules_completion', $data);
4842
        }
4843
 
4844
        // Add viewed to course_modules_viewed.
4845
        if (isset($data->viewed) && $data->viewed) {
4846
            $dataview = clone($data);
4847
            unset($dataview->id);
4848
            unset($dataview->viewed);
4849
            $dataview->timecreated = $data->timemodified;
4850
            $DB->insert_record('course_modules_viewed', $dataview);
4851
        }
4852
    }
4853
 
4854
    /**
4855
     * Process the completioinview data.
4856
     * @param array $data The data from the XML file.
4857
     */
4858
    protected function process_completionview(array $data) {
4859
        global $DB;
4860
 
4861
        $data = (object)$data;
4862
        $data->coursemoduleid = $this->task->get_moduleid();
4863
        $data->userid = $this->get_mappingid('user', $data->userid);
4864
 
4865
        $DB->insert_record('course_modules_viewed', $data);
4866
    }
4867
}
4868
 
4869
/**
4870
 * Abstract structure step, parent of all the activity structure steps. Used to support
4871
 * the main <activity ...> tag and process it.
4872
 */
4873
abstract class restore_activity_structure_step extends restore_structure_step {
4874
 
4875
    /**
4876
     * Adds support for the 'activity' path that is common to all the activities
4877
     * and will be processed globally here
4878
     */
4879
    protected function prepare_activity_structure($paths) {
4880
 
4881
        $paths[] = new restore_path_element('activity', '/activity');
4882
 
4883
        return $paths;
4884
    }
4885
 
4886
    /**
4887
     * Process the activity path, informing the task about various ids, needed later
4888
     */
4889
    protected function process_activity($data) {
4890
        $data = (object)$data;
4891
        $this->task->set_old_contextid($data->contextid); // Save old contextid in task
4892
        $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
4893
        $this->task->set_old_activityid($data->id); // Save old activityid in task
4894
    }
4895
 
4896
    /**
4897
     * This must be invoked immediately after creating the "module" activity record (forum, choice...)
4898
     * and will adjust the new activity id (the instance) in various places
4899
     */
4900
    protected function apply_activity_instance($newitemid) {
4901
        global $DB;
4902
 
4903
        $this->task->set_activityid($newitemid); // Save activity id in task
4904
        // Apply the id to course_sections->instanceid
4905
        $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
4906
        // Do the mapping for modulename, preparing it for files by oldcontext
4907
        $modulename = $this->task->get_modulename();
4908
        $oldid = $this->task->get_old_activityid();
4909
        $this->set_mapping($modulename, $oldid, $newitemid, true);
4910
    }
4911
}
4912
 
4913
/**
4914
 * Structure step in charge of creating/mapping all the qcats and qs
4915
 * by parsing the questions.xml file and checking it against the
4916
 * results calculated by {@link restore_process_categories_and_questions}
4917
 * and stored in backup_ids_temp.
4918
 */
4919
class restore_create_categories_and_questions extends restore_structure_step {
4920
 
4921
    /** @var array $cachedcategory store a question category */
4922
    protected $cachedcategory = null;
4923
 
4924
    protected function define_structure() {
4925
 
4926
        // Check if the backup is a pre 4.0 one.
4927
        $restoretask = $this->get_task();
4928
        $before40 = $restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<');
4929
        // Start creating the path, category should be the first one.
4930
        $paths = [];
4931
        $paths [] = new restore_path_element('question_category', '/question_categories/question_category');
4932
        // For the backups done before 4.0.
4933
        if ($before40) {
4934
            // This path is to recreate the bank entry and version for the legacy question objets.
4935
            $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
4936
 
4937
            // Apply for 'qtype' plugins optional paths at question level.
4938
            $this->add_plugin_structure('qtype', $question);
4939
 
4940
            // Apply for 'local' plugins optional paths at question level.
4941
            $this->add_plugin_structure('local', $question);
4942
 
4943
            $paths [] = $question;
4944
            $paths [] = new restore_path_element('question_hint',
4945
                '/question_categories/question_category/questions/question/question_hints/question_hint');
4946
            $paths [] = new restore_path_element('tag', '/question_categories/question_category/questions/question/tags/tag');
4947
        } else {
4948
            // For all the new backups.
4949
            $paths [] = new restore_path_element('question_bank_entry',
4950
                '/question_categories/question_category/question_bank_entries/question_bank_entry');
4951
            $paths [] = new restore_path_element('question_versions', '/question_categories/question_category/'.
4952
                'question_bank_entries/question_bank_entry/question_version/question_versions');
4953
            $question = new restore_path_element('question', '/question_categories/question_category/'.
4954
                'question_bank_entries/question_bank_entry/question_version/question_versions/questions/question');
4955
 
4956
            // Apply for 'qtype' plugins optional paths at question level.
4957
            $this->add_plugin_structure('qtype', $question);
4958
 
4959
            // Apply for 'qbank' plugins optional paths at question level.
4960
            $this->add_plugin_structure('qbank', $question);
4961
 
4962
            // Apply for 'local' plugins optional paths at question level.
4963
            $this->add_plugin_structure('local', $question);
4964
 
4965
            $paths [] = $question;
4966
            $paths [] = new restore_path_element('question_hint', '/question_categories/question_category/question_bank_entries/'.
4967
                'question_bank_entry/question_version/question_versions/questions/question/question_hints/question_hint');
4968
            $paths [] = new restore_path_element('tag', '/question_categories/question_category/question_bank_entries/'.
4969
                'question_bank_entry/question_version/question_versions/questions/question/tags/tag');
4970
        }
4971
 
4972
        return $paths;
4973
    }
4974
 
4975
    /**
4976
     * Process question category restore.
4977
     *
4978
     * @param array $data the data from the XML file.
4979
     */
4980
    protected function process_question_category($data) {
4981
        global $DB;
4982
 
4983
        $data = (object)$data;
4984
        $oldid = $data->id;
4985
 
4986
        // Check we have one mapping for this category.
4987
        if (!$mapping = $this->get_mapping('question_category', $oldid)) {
4988
            return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
4989
        }
4990
 
4991
        // Check we have to create the category (newitemid = 0).
4992
        if ($mapping->newitemid) {
4993
            // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4994
            // children elements of the 'question_category' one.
4995
            $this->set_mapping('question_category', $oldid, $mapping->newitemid);
4996
            return; // newitemid != 0, this category is going to be mapped. Nothing to do
4997
        }
4998
 
4999
        // Arrived here, newitemid = 0, we need to create the category
5000
        // we'll do it at parentitemid context, but for CONTEXT_MODULE
5001
        // categories, that will be created at CONTEXT_COURSE and moved
5002
        // to module context later when the activity is created.
5003
        if ($mapping->info->contextlevel == CONTEXT_MODULE) {
5004
            $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
5005
        }
5006
        $data->contextid = $mapping->parentitemid;
5007
 
5008
        // Before 3.5, question categories could be created at top level.
5009
        // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
5010
        $restoretask = $this->get_task();
5011
        $before35 = $restoretask->backup_release_compare('3.5', '<') || $restoretask->backup_version_compare(20180205, '<');
5012
        if (empty($mapping->info->parent) && $before35) {
5013
            $top = question_get_top_category($data->contextid, true);
5014
            $data->parent = $top->id;
5015
        }
5016
 
5017
        if (empty($data->parent)) {
5018
            if (!$top = question_get_top_category($data->contextid)) {
5019
                $top = question_get_top_category($data->contextid, true);
5020
                $this->set_mapping('question_category_created', $oldid, $top->id, false, null, $data->contextid);
5021
            }
5022
            $this->set_mapping('question_category', $oldid, $top->id);
5023
        } else {
5024
 
5025
            // Before 3.1, the 'stamp' field could be erroneously duplicated.
5026
            // From 3.1 onwards, there's a unique index of (contextid, stamp).
5027
            // If we encounter a duplicate in an old restore file, just generate a new stamp.
5028
            // This is the same as what happens during an upgrade to 3.1+ anyway.
5029
            if ($DB->record_exists('question_categories', ['stamp' => $data->stamp, 'contextid' => $data->contextid])) {
5030
                $data->stamp = make_unique_id_code();
5031
            }
5032
 
5033
            // The idnumber if it exists also needs to be unique within a context or reset it to null.
5034
            if (!empty($data->idnumber) && $DB->record_exists('question_categories',
5035
                    ['idnumber' => $data->idnumber, 'contextid' => $data->contextid])) {
5036
                unset($data->idnumber);
5037
            }
5038
 
5039
            // Let's create the question_category and save mapping.
5040
            $newitemid = $DB->insert_record('question_categories', $data);
5041
            $this->set_mapping('question_category', $oldid, $newitemid);
5042
            // Also annotate them as question_category_created, we need
5043
            // that later when remapping parents.
5044
            $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
5045
        }
5046
    }
5047
 
5048
    /**
5049
     * Process pre 4.0 question data where in creates the record for version and entry table.
5050
     *
5051
     * @param array $data the data from the XML file.
5052
     */
5053
    protected function process_question_legacy_data($data) {
5054
        global $DB;
5055
 
5056
        $oldid = $data->id;
5057
        // Process question bank entry.
5058
        $entrydata = new stdClass();
5059
        $entrydata->questioncategoryid = $data->category;
5060
        $userid = $this->get_mappingid('user', $data->createdby);
5061
        if ($userid) {
5062
            $entrydata->ownerid = $userid;
5063
        } else {
5064
            if (!$this->task->is_samesite()) {
5065
                $entrydata->ownerid = $this->task->get_userid();
5066
            }
5067
        }
5068
        // The idnumber if it exists also needs to be unique within a category or reset it to null.
5069
        if (isset($data->idnumber) && !$DB->record_exists('question_bank_entries',
5070
                ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->category])) {
5071
            $entrydata->idnumber = $data->idnumber;
5072
        }
5073
 
5074
        $newentryid = $DB->insert_record('question_bank_entries', $entrydata);
5075
        // Process question versions.
5076
        $versiondata = new stdClass();
5077
        $versiondata->questionbankentryid = $newentryid;
5078
        $versiondata->version = 1;
5079
        // Question id is updated after inserting the question.
5080
        $versiondata->questionid = 0;
5081
        $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
5082
        if ((int)$data->hidden === 1) {
5083
            $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_HIDDEN;
5084
        }
5085
        $versiondata->status = $versionstatus;
5086
        $newversionid = $DB->insert_record('question_versions', $versiondata);
5087
        $this->set_mapping('question_version_created', $oldid, $newversionid);
5088
    }
5089
 
5090
    /**
5091
     * Process question bank entry data.
5092
     *
5093
     * @param array $data the data from the XML file.
5094
     */
5095
    protected function process_question_bank_entry($data) {
5096
        global $DB;
5097
 
5098
        $data = (object)$data;
5099
        $oldid = $data->id;
5100
 
5101
        $questioncreated = $this->get_mappingid('question_category_created', $data->questioncategoryid) ? true : false;
5102
        $recordexist = $DB->record_exists('question_bank_entries', ['id' => $data->id,
5103
            'questioncategoryid' => $data->questioncategoryid]);
5104
        // Check we have category created.
5105
        if (!$questioncreated && $recordexist) {
5106
            return self::SKIP_ALL_CHILDREN;
5107
        }
5108
 
5109
        $data->questioncategoryid = $this->get_new_parentid('question_category');
5110
        $userid = $this->get_mappingid('user', $data->ownerid);
5111
        if ($userid) {
5112
            $data->ownerid = $userid;
5113
        } else {
5114
            if (!$this->task->is_samesite()) {
5115
                $data->ownerid = $this->task->get_userid();
5116
            }
5117
        }
5118
 
5119
        // The idnumber if it exists also needs to be unique within a category or reset it to null.
5120
        if (!empty($data->idnumber) && $DB->record_exists('question_bank_entries',
5121
                ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->questioncategoryid])) {
5122
            unset($data->idnumber);
5123
        }
5124
 
5125
        $newitemid = $DB->insert_record('question_bank_entries', $data);
5126
        $this->set_mapping('question_bank_entry', $oldid, $newitemid);
5127
    }
5128
 
5129
    /**
5130
     * Process question versions.
5131
     *
5132
     * @param array $data the data from the XML file.
5133
     */
5134
    protected function process_question_versions($data) {
5135
        global $DB;
5136
 
5137
        $data = (object)$data;
5138
        $oldid = $data->id;
5139
 
5140
        $data->questionbankentryid = $this->get_new_parentid('question_bank_entry');
5141
        // Question id is updated after inserting the question.
5142
        $data->questionid = 0;
5143
        $newitemid = $DB->insert_record('question_versions', $data);
5144
        $this->set_mapping('question_versions', $oldid, $newitemid);
5145
    }
5146
 
5147
    /**
5148
     * Process the actual question.
5149
     *
5150
     * @param array $data the data from the XML file.
5151
     */
5152
    protected function process_question($data) {
5153
        global $DB;
5154
 
5155
        $data = (object)$data;
5156
        $oldid = $data->id;
5157
 
5158
        // Check if the backup is a pre 4.0 one.
5159
        $restoretask = $this->get_task();
5160
        if ($restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<')) {
5161
            // Check we have one mapping for this question.
5162
            if (!$questionmapping = $this->get_mapping('question', $oldid)) {
5163
                return; // No mapping = this question doesn't need to be created/mapped.
5164
            }
5165
 
5166
            // Get the mapped category (cannot use get_new_parentid() because not
5167
            // all the categories have been created, so it is not always available
5168
            // Instead we get the mapping for the question->parentitemid because
5169
            // we have loaded qcatids there for all parsed questions.
5170
            $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
5171
            $this->process_question_legacy_data($data);
5172
        }
5173
 
5174
        // In the past, there were some very sloppy values of penalty. Fix them.
5175
        if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
5176
            $data->penalty = 0.3333333;
5177
        }
5178
        if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
5179
            $data->penalty = 0.6666667;
5180
        }
5181
        if ($data->penalty >= 1) {
5182
            $data->penalty = 1;
5183
        }
5184
 
5185
        $userid = $this->get_mappingid('user', $data->createdby);
5186
        if ($userid) {
5187
            // The question creator is included in the backup, so we can use their mapping id.
5188
            $data->createdby = $userid;
5189
        } else {
5190
            // Leave the question creator unchanged when we are restoring the same site.
5191
            // Otherwise use current user id.
5192
            if (!$this->task->is_samesite()) {
5193
                $data->createdby = $this->task->get_userid();
5194
            }
5195
        }
5196
 
5197
        $userid = $this->get_mappingid('user', $data->modifiedby);
5198
        if ($userid) {
5199
            // The question modifier is included in the backup, so we can use their mapping id.
5200
            $data->modifiedby = $userid;
5201
        } else {
5202
            // Leave the question modifier unchanged when we are restoring the same site.
5203
            // Otherwise use current user id.
5204
            if (!$this->task->is_samesite()) {
5205
                $data->modifiedby = $this->task->get_userid();
5206
            }
5207
        }
5208
 
5209
        $newitemid = $DB->insert_record('question', $data);
5210
        $this->set_mapping('question', $oldid, $newitemid);
5211
        // Also annotate them as question_created, we need
5212
        // that later when remapping parents (keeping the old categoryid as parentid).
5213
        $parentcatid = $this->get_old_parentid('question_category');
5214
        $this->set_mapping('question_created', $oldid, $newitemid, false, null, $parentcatid);
5215
        // Now update the question_versions table with the new question id. we dont need to do that for random qtypes.
5216
        $legacyquestiondata = $this->get_mappingid('question_version_created', $oldid) ? true : false;
5217
        if ($legacyquestiondata) {
5218
            $parentitemid = $this->get_mappingid('question_version_created', $oldid);
5219
        } else {
5220
            $parentitemid = $this->get_new_parentid('question_versions');
5221
        }
5222
        $version = new stdClass();
5223
        $version->id = $parentitemid;
5224
        $version->questionid = $newitemid;
5225
        $DB->update_record('question_versions', $version);
5226
 
5227
        // Note, we don't restore any question files yet
5228
        // as far as the CONTEXT_MODULE categories still
5229
        // haven't their contexts to be restored to
5230
        // The {@link restore_create_question_files}, executed in the final step
5231
        // step will be in charge of restoring all the question files.
5232
    }
5233
 
5234
    protected function process_question_hint($data) {
5235
        global $DB;
5236
 
5237
        $data = (object)$data;
5238
        $oldid = $data->id;
5239
 
5240
        // Detect if the question is created or mapped
5241
        $oldquestionid   = $this->get_old_parentid('question');
5242
        $newquestionid   = $this->get_new_parentid('question');
5243
        $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
5244
 
5245
        // If the question has been created by restore, we need to create its question_answers too
5246
        if ($questioncreated) {
5247
            // Adjust some columns
5248
            $data->questionid = $newquestionid;
5249
            // Insert record
5250
            $newitemid = $DB->insert_record('question_hints', $data);
5251
 
5252
        // The question existed, we need to map the existing question_hints
5253
        } else {
5254
            // Look in question_hints by hint text matching
5255
            $sql = 'SELECT id
5256
                      FROM {question_hints}
5257
                     WHERE questionid = ?
5258
                       AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
5259
            $params = array($newquestionid, $data->hint);
5260
            $newitemid = $DB->get_field_sql($sql, $params);
5261
 
5262
            // Not able to find the hint, let's try cleaning the hint text
5263
            // of all the question's hints in DB as slower fallback. MDL-33863.
5264
            if (!$newitemid) {
5265
                $potentialhints = $DB->get_records('question_hints',
5266
                        array('questionid' => $newquestionid), '', 'id, hint');
5267
                foreach ($potentialhints as $potentialhint) {
5268
                    // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
5269
                    $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
5270
                    $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
5271
                    if ($cleanhint === $data->hint) {
5272
                        $newitemid = $data->id;
5273
                    }
5274
                }
5275
            }
5276
 
5277
            // If we haven't found the newitemid, something has gone really wrong, question in DB
5278
            // is missing hints, exception
5279
            if (!$newitemid) {
5280
                $info = new stdClass();
5281
                $info->filequestionid = $oldquestionid;
5282
                $info->dbquestionid   = $newquestionid;
5283
                $info->hint           = $data->hint;
5284
                throw new restore_step_exception('error_question_hint_missing_in_db', $info);
5285
            }
5286
        }
5287
        // Create mapping (I'm not sure if this is really needed?)
5288
        $this->set_mapping('question_hint', $oldid, $newitemid);
5289
    }
5290
 
5291
    protected function process_tag($data) {
5292
        global $DB;
5293
 
5294
        $data = (object)$data;
5295
        $newquestion = $this->get_new_parentid('question');
5296
        $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
5297
        if (!$questioncreated) {
5298
            // This question already exists in the question bank. Nothing for us to do.
5299
            return;
5300
        }
5301
 
5302
        if (core_tag_tag::is_enabled('core_question', 'question')) {
5303
            $tagname = $data->rawname;
5304
            if (!empty($data->contextid) && $newcontextid = $this->get_mappingid('context', $data->contextid)) {
5305
                    $tagcontextid = $newcontextid;
5306
            } else {
5307
                // Get the category, so we can then later get the context.
5308
                $categoryid = $this->get_new_parentid('question_category');
5309
                if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
5310
                    $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
5311
                }
5312
                $tagcontextid = $this->cachedcategory->contextid;
5313
            }
5314
            // Add the tag to the question.
5315
            core_tag_tag::add_item_tag('core_question', 'question', $newquestion,
5316
                    context::instance_by_id($tagcontextid),
5317
                    $tagname);
5318
        }
5319
    }
5320
 
5321
    protected function after_execute() {
5322
        global $DB;
5323
 
5324
        // First of all, recode all the created question_categories->parent fields
5325
        $qcats = $DB->get_records('backup_ids_temp', array(
5326
                     'backupid' => $this->get_restoreid(),
5327
                     'itemname' => 'question_category_created'));
5328
        foreach ($qcats as $qcat) {
5329
            $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
5330
            // Get new parent (mapped or created, so we look in quesiton_category mappings)
5331
            if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5332
                                 'backupid' => $this->get_restoreid(),
5333
                                 'itemname' => 'question_category',
5334
                                 'itemid'   => $dbcat->parent))) {
5335
                // contextids must match always, as far as we always include complete qbanks, just check it
5336
                $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
5337
                if ($dbcat->contextid == $newparentctxid) {
5338
                    $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
5339
                } else {
5340
                    $newparent = 0; // No ctx match for both cats, no parent relationship
5341
                }
5342
            }
5343
            // Here with $newparent empty, problem with contexts or remapping, set it to top cat
5344
            if (!$newparent && $dbcat->parent) {
5345
                $topcat = question_get_top_category($dbcat->contextid, true);
5346
                if ($dbcat->parent != $topcat->id) {
5347
                    $DB->set_field('question_categories', 'parent', $topcat->id, array('id' => $dbcat->id));
5348
                }
5349
            }
5350
        }
5351
 
5352
        // Now, recode all the created question->parent fields
5353
        $qs = $DB->get_records('backup_ids_temp', array(
5354
                  'backupid' => $this->get_restoreid(),
5355
                  'itemname' => 'question_created'));
5356
        foreach ($qs as $q) {
5357
            $dbq = $DB->get_record('question', array('id' => $q->newitemid));
5358
            // Get new parent (mapped or created, so we look in question mappings)
5359
            if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5360
                                 'backupid' => $this->get_restoreid(),
5361
                                 'itemname' => 'question',
5362
                                 'itemid'   => $dbq->parent))) {
5363
                $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
5364
            }
5365
        }
5366
 
5367
        // Note, we don't restore any question files yet
5368
        // as far as the CONTEXT_MODULE categories still
5369
        // haven't their contexts to be restored to
5370
        // The {@link restore_create_question_files}, executed in the final step
5371
        // step will be in charge of restoring all the question files
5372
    }
5373
}
5374
 
5375
/**
5376
 * Execution step that will move all the CONTEXT_MODULE question categories
5377
 * created at early stages of restore in course context (because modules weren't
5378
 * created yet) to their target module (matching by old-new-contextid mapping)
5379
 */
5380
class restore_move_module_questions_categories extends restore_execution_step {
5381
 
5382
    protected function define_execution() {
5383
        global $DB;
5384
 
5385
        $after35 = $this->task->backup_release_compare('3.5', '>=') && $this->task->backup_version_compare(20180205, '>');
5386
 
5387
        $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
5388
        foreach ($contexts as $contextid => $contextlevel) {
5389
            // Only if context mapping exists (i.e. the module has been restored)
5390
            if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
5391
                // Update all the qcats having their parentitemid set to the original contextid
5392
                $modulecats = $DB->get_records_sql("SELECT itemid, newitemid, info
5393
                                                      FROM {backup_ids_temp}
5394
                                                     WHERE backupid = ?
5395
                                                       AND itemname = 'question_category'
5396
                                                       AND parentitemid = ?", array($this->get_restoreid(), $contextid));
5397
                $top = question_get_top_category($newcontext->newitemid, true);
5398
                $oldtopid = 0;
5399
                $categoryids = [];
5400
                foreach ($modulecats as $modulecat) {
5401
                    // Before 3.5, question categories could be created at top level.
5402
                    // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
5403
                    $info = backup_controller_dbops::decode_backup_temp_info($modulecat->info);
5404
                    if ($after35 && empty($info->parent)) {
5405
                        $oldtopid = $modulecat->newitemid;
5406
                        $modulecat->newitemid = $top->id;
5407
                    } else {
5408
                        $cat = new stdClass();
5409
                        $cat->id = $modulecat->newitemid;
5410
                        $cat->contextid = $newcontext->newitemid;
5411
                        if (empty($info->parent)) {
5412
                            $cat->parent = $top->id;
5413
                        }
5414
                        $DB->update_record('question_categories', $cat);
5415
                        $categoryids[] = (int)$cat->id;
5416
                    }
5417
 
5418
                    // And set new contextid (and maybe update newitemid) also in question_category mapping (will be
5419
                    // used by {@link restore_create_question_files} later.
5420
                    restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid,
5421
                            $modulecat->newitemid, $newcontext->newitemid);
5422
                }
5423
 
5424
                // Update the context id of any tags applied to any questions in these categories.
5425
                if ($categoryids) {
5426
                    [$categorysql, $categoryidparams] = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
5427
                    $sqlupdate = "UPDATE {tag_instance}
5428
                                     SET contextid = :newcontext
5429
                                   WHERE component = :component
5430
                                         AND itemtype = :itemtype
5431
                                         AND itemid IN (SELECT DISTINCT bi.newitemid as questionid
5432
                                                          FROM {backup_ids_temp} bi
5433
                                                          JOIN {question} q ON q.id = bi.newitemid
5434
                                                          JOIN {question_versions} qv ON qv.questionid = q.id
5435
                                                          JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
5436
                                                         WHERE bi.backupid = :backupid AND bi.itemname = 'question_created'
5437
                                                               AND qbe.questioncategoryid {$categorysql}) ";
5438
                    $params = [
5439
                        'newcontext' => $newcontext->newitemid,
5440
                        'component' => 'core_question',
5441
                        'itemtype' => 'question',
5442
                        'backupid' => $this->get_restoreid(),
5443
                    ];
5444
                    $params += $categoryidparams;
5445
                    $DB->execute($sqlupdate, $params);
5446
 
5447
                    // As explained in {@see restore_quiz_activity_structure_step::process_quiz_question_legacy_instance()}
5448
                    // question_set_references relating to random questions restored from old backups,
5449
                    // which pick from context_module question_categores, will have been restored with the wrong questioncontextid.
5450
                    // So, now, we need to find those, and updated the questioncontextid.
5451
                    // We can only find them by picking apart the filter conditions, and seeign which categories they refer to.
5452
 
5453
                    // We need to check all the question_set_references belonging to this context_module.
5454
                    $references = $DB->get_records('question_set_references', ['usingcontextid' => $newcontext->newitemid]);
5455
                    foreach ($references as $reference) {
5456
                        $filtercondition = json_decode($reference->filtercondition);
5457
                        if (!empty($filtercondition->questioncategoryid) &&
5458
                                in_array($filtercondition->questioncategoryid, $categoryids)) {
5459
                            // This is one of ours, update the questionscontextid.
5460
                            $DB->set_field('question_set_references',
5461
                                'questionscontextid', $newcontext->newitemid,
5462
                                ['id' => $reference->id]);
5463
                        }
5464
                    }
5465
                }
5466
 
5467
                // Now set the parent id for the question categories that were in the top category in the course context
5468
                // and have been moved now.
5469
                if ($oldtopid) {
5470
                    $DB->set_field('question_categories', 'parent', $top->id,
5471
                            array('contextid' => $newcontext->newitemid, 'parent' => $oldtopid));
5472
                }
5473
            }
5474
        }
5475
    }
5476
}
5477
 
5478
/**
5479
 * Execution step that will create all the question/answers/qtype-specific files for the restored
5480
 * questions. It must be executed after {@link restore_move_module_questions_categories}
5481
 * because only then each question is in its final category and only then the
5482
 * contexts can be determined.
5483
 */
5484
class restore_create_question_files extends restore_execution_step {
5485
 
5486
    /** @var array Question-type specific component items cache. */
5487
    private $qtypecomponentscache = array();
5488
 
5489
    /**
5490
     * Preform the restore_create_question_files step.
5491
     */
5492
    protected function define_execution() {
5493
        global $DB;
5494
 
5495
        // Track progress, as this task can take a long time.
5496
        $progress = $this->task->get_progress();
5497
        $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
5498
 
5499
        // Parentitemids of question_createds in backup_ids_temp are the category it is in.
5500
        // MUST use a recordset, as there is no unique key in the first (or any) column.
5501
        $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
5502
                                                   FROM {backup_ids_temp} bi
5503
                                                   JOIN {question} q ON q.id = bi.newitemid
5504
                                                  WHERE bi.backupid = ?
5505
                                                        AND bi.itemname = 'question_created'
5506
                                               ORDER BY categoryid ASC", array($this->get_restoreid()));
5507
 
5508
        $currentcatid = -1;
5509
        foreach ($catqtypes as $categoryid => $row) {
5510
            $qtype = $row->qtype;
5511
 
5512
            // Check if we are in a new category.
5513
            if ($currentcatid !== $categoryid) {
5514
                // Report progress for each category.
5515
                $progress->progress();
5516
 
5517
                if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
5518
                        'question_category', $categoryid)) {
5519
                    // Something went really wrong, cannot find the question_category for the question_created records.
5520
                    debugging('Error fetching target context for question', DEBUG_DEVELOPER);
5521
                    continue;
5522
                }
5523
 
5524
                // Calculate source and target contexts.
5525
                $oldctxid = $qcatmapping->info->contextid;
5526
                $newctxid = $qcatmapping->parentitemid;
5527
 
5528
                $this->send_common_files($oldctxid, $newctxid, $progress);
5529
                $currentcatid = $categoryid;
5530
            }
5531
 
5532
            $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
5533
        }
5534
        $catqtypes->close();
5535
        $progress->end_progress();
5536
    }
5537
 
5538
    /**
5539
     * Send the common question files to a new context.
5540
     *
5541
     * @param int             $oldctxid Old context id.
5542
     * @param int             $newctxid New context id.
5543
     * @param \core\progress\base  $progress Progress object to use.
5544
     */
5545
    private function send_common_files($oldctxid, $newctxid, $progress) {
5546
        // Add common question files (question and question_answer ones).
5547
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
5548
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5549
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
5550
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5551
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
5552
                $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5553
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
5554
                $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5555
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
5556
                $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
5557
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
5558
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5559
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
5560
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5561
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
5562
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5563
    }
5564
 
5565
    /**
5566
     * Send the question type specific files to a new context.
5567
     *
5568
     * @param text            $qtype The qtype name to send.
5569
     * @param int             $oldctxid Old context id.
5570
     * @param int             $newctxid New context id.
5571
     * @param \core\progress\base  $progress Progress object to use.
5572
     */
5573
    private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
5574
        if (!isset($this->qtypecomponentscache[$qtype])) {
5575
            $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
5576
        }
5577
        $components = $this->qtypecomponentscache[$qtype];
5578
        foreach ($components as $component => $fileareas) {
5579
            foreach ($fileareas as $filearea => $mapping) {
5580
                restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
5581
                        $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
5582
            }
5583
        }
5584
    }
5585
}
5586
 
5587
/**
5588
 * Try to restore aliases and references to external files.
5589
 *
5590
 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
5591
 * We expect that all regular (non-alias) files have already been restored. Make sure
5592
 * there is no restore step executed after this one that would call send_files_to_pool() again.
5593
 *
5594
 * You may notice we have hardcoded support for Server files, Legacy course files
5595
 * and user Private files here at the moment. This could be eventually replaced with a set of
5596
 * callbacks in the future if needed.
5597
 *
5598
 * @copyright 2012 David Mudrak <david@moodle.com>
5599
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5600
 */
5601
class restore_process_file_aliases_queue extends restore_execution_step {
5602
 
5603
    /** @var array internal cache for {@link choose_repository()} */
5604
    private $cachereposbyid = array();
5605
 
5606
    /** @var array internal cache for {@link choose_repository()} */
5607
    private $cachereposbytype = array();
5608
 
5609
    /**
5610
     * What to do when this step is executed.
5611
     */
5612
    protected function define_execution() {
5613
        global $DB;
5614
 
5615
        $fs = get_file_storage();
5616
 
5617
        // Load the queue.
5618
        $aliascount = $DB->count_records('backup_ids_temp',
5619
            ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue']);
5620
        $rs = $DB->get_recordset('backup_ids_temp',
5621
            ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'],
5622
            '', 'info');
5623
 
5624
        $this->log('processing file aliases queue. ' . $aliascount . ' entries.', backup::LOG_DEBUG);
5625
        $progress = $this->task->get_progress();
5626
        $progress->start_progress('Processing file aliases queue', $aliascount);
5627
 
5628
        // Iterate over aliases in the queue.
5629
        foreach ($rs as $record) {
5630
            $progress->increment_progress();
5631
            $info = backup_controller_dbops::decode_backup_temp_info($record->info);
5632
 
5633
            // Try to pick a repository instance that should serve the alias.
5634
            $repository = $this->choose_repository($info);
5635
 
5636
            if (is_null($repository)) {
5637
                $this->notify_failure($info, 'unable to find a matching repository instance');
5638
                continue;
5639
            }
5640
 
5641
            if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5642
                    || $info->oldfile->repositorytype === 'contentbank') {
5643
                // Aliases to Server files and Legacy course files may refer to a file
5644
                // contained in the backup file or to some existing file (if we are on the
5645
                // same site).
5646
                try {
5647
                    $reference = file_storage::unpack_reference($info->oldfile->reference);
5648
                } catch (Exception $e) {
5649
                    $this->notify_failure($info, 'invalid reference field format');
5650
                    continue;
5651
                }
5652
 
5653
                // Let's see if the referred source file was also included in the backup.
5654
                $candidates = $DB->get_recordset('backup_files_temp', array(
5655
                        'backupid' => $this->get_restoreid(),
5656
                        'contextid' => $reference['contextid'],
5657
                        'component' => $reference['component'],
5658
                        'filearea' => $reference['filearea'],
5659
                        'itemid' => $reference['itemid'],
5660
                    ), '', 'info, newcontextid, newitemid');
5661
 
5662
                $source = null;
5663
 
5664
                foreach ($candidates as $candidate) {
5665
                    $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
5666
                    if ($candidateinfo->filename === $reference['filename']
5667
                            and $candidateinfo->filepath === $reference['filepath']
5668
                            and !is_null($candidate->newcontextid)
5669
                            and !is_null($candidate->newitemid) ) {
5670
                        $source = $candidateinfo;
5671
                        $source->contextid = $candidate->newcontextid;
5672
                        $source->itemid = $candidate->newitemid;
5673
                        break;
5674
                    }
5675
                }
5676
                $candidates->close();
5677
 
5678
                if ($source) {
5679
                    // We have an alias that refers to another file also included in
5680
                    // the backup. Let us change the reference field so that it refers
5681
                    // to the restored copy of the original file.
5682
                    $reference = file_storage::pack_reference($source);
5683
 
5684
                    // Send the new alias to the filepool.
5685
                    $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5686
                    $this->notify_success($info);
5687
                    continue;
5688
 
5689
                } else {
5690
                    // This is a reference to some moodle file that was not contained in the backup
5691
                    // file. If we are restoring to the same site, keep the reference untouched
5692
                    // and restore the alias as is if the referenced file exists.
5693
                    if ($this->task->is_samesite()) {
5694
                        if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5695
                                $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5696
                            $reference = file_storage::pack_reference($reference);
5697
                            $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5698
                            $this->notify_success($info);
5699
                            continue;
5700
                        } else {
5701
                            $this->notify_failure($info, 'referenced file not found');
5702
                            continue;
5703
                        }
5704
 
5705
                    // If we are at other site, we can't restore this alias.
5706
                    } else {
5707
                        $this->notify_failure($info, 'referenced file not included');
5708
                        continue;
5709
                    }
5710
                }
5711
 
5712
            } else if ($info->oldfile->repositorytype === 'user') {
5713
                if ($this->task->is_samesite()) {
5714
                    // For aliases to user Private files at the same site, we have a chance to check
5715
                    // if the referenced file still exists.
5716
                    try {
5717
                        $reference = file_storage::unpack_reference($info->oldfile->reference);
5718
                    } catch (Exception $e) {
5719
                        $this->notify_failure($info, 'invalid reference field format');
5720
                        continue;
5721
                    }
5722
                    if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5723
                            $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5724
                        $reference = file_storage::pack_reference($reference);
5725
                        $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5726
                        $this->notify_success($info);
5727
                        continue;
5728
                    } else {
5729
                        $this->notify_failure($info, 'referenced file not found');
5730
                        continue;
5731
                    }
5732
 
5733
                // If we are at other site, we can't restore this alias.
5734
                } else {
5735
                    $this->notify_failure($info, 'restoring at another site');
5736
                    continue;
5737
                }
5738
 
5739
            } else {
5740
                // This is a reference to some external file such as dropbox.
5741
                // If we are restoring to the same site, keep the reference untouched and
5742
                // restore the alias as is.
5743
                if ($this->task->is_samesite()) {
5744
                    $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
5745
                    $this->notify_success($info);
5746
                    continue;
5747
 
5748
                // If we are at other site, we can't restore this alias.
5749
                } else {
5750
                    $this->notify_failure($info, 'restoring at another site');
5751
                    continue;
5752
                }
5753
            }
5754
        }
5755
        $progress->end_progress();
5756
        $rs->close();
5757
    }
5758
 
5759
    /**
5760
     * Choose the repository instance that should handle the alias.
5761
     *
5762
     * At the same site, we can rely on repository instance id and we just
5763
     * check it still exists. On other site, try to find matching Server files or
5764
     * Legacy course files repository instance. Return null if no matching
5765
     * repository instance can be found.
5766
     *
5767
     * @param stdClass $info
5768
     * @return repository|null
5769
     */
5770
    private function choose_repository(stdClass $info) {
5771
        global $DB, $CFG;
5772
        require_once($CFG->dirroot.'/repository/lib.php');
5773
 
5774
        if ($this->task->is_samesite()) {
5775
            // We can rely on repository instance id.
5776
 
5777
            if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
5778
                return $this->cachereposbyid[$info->oldfile->repositoryid];
5779
            }
5780
 
5781
            $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
5782
 
5783
            try {
5784
                $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
5785
                return $this->cachereposbyid[$info->oldfile->repositoryid];
5786
            } catch (Exception $e) {
5787
                $this->cachereposbyid[$info->oldfile->repositoryid] = null;
5788
                return null;
5789
            }
5790
 
5791
        } else {
5792
            // We can rely on repository type only.
5793
 
5794
            if (empty($info->oldfile->repositorytype)) {
5795
                return null;
5796
            }
5797
 
5798
            if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
5799
                return $this->cachereposbytype[$info->oldfile->repositorytype];
5800
            }
5801
 
5802
            $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
5803
 
5804
            // Both Server files and Legacy course files repositories have a single
5805
            // instance at the system context to use. Let us try to find it.
5806
            if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5807
                    || $info->oldfile->repositorytype === 'contentbank') {
5808
                $sql = "SELECT ri.id
5809
                          FROM {repository} r
5810
                          JOIN {repository_instances} ri ON ri.typeid = r.id
5811
                         WHERE r.type = ? AND ri.contextid = ?";
5812
                $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
5813
                if (empty($ris)) {
5814
                    return null;
5815
                }
5816
                $repoids = array_keys($ris);
5817
                $repoid = reset($repoids);
5818
                try {
5819
                    $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
5820
                    return $this->cachereposbytype[$info->oldfile->repositorytype];
5821
                } catch (Exception $e) {
5822
                    $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5823
                    return null;
5824
                }
5825
            }
5826
 
5827
            $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5828
            return null;
5829
        }
5830
    }
5831
 
5832
    /**
5833
     * Let the user know that the given alias was successfully restored
5834
     *
5835
     * @param stdClass $info
5836
     */
5837
    private function notify_success(stdClass $info) {
5838
        $filedesc = $this->describe_alias($info);
5839
        $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
5840
    }
5841
 
5842
    /**
5843
     * Let the user know that the given alias can't be restored
5844
     *
5845
     * @param stdClass $info
5846
     * @param string $reason detailed reason to be logged
5847
     */
5848
    private function notify_failure(stdClass $info, $reason = '') {
5849
        $filedesc = $this->describe_alias($info);
5850
        if ($reason) {
5851
            $reason = ' ('.$reason.')';
5852
        }
5853
        $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
5854
        $this->add_result_item('file_aliases_restore_failures', $filedesc);
5855
    }
5856
 
5857
    /**
5858
     * Return a human readable description of the alias file
5859
     *
5860
     * @param stdClass $info
5861
     * @return string
5862
     */
5863
    private function describe_alias(stdClass $info) {
5864
 
5865
        $filedesc = $this->expected_alias_location($info->newfile);
5866
 
5867
        if (!is_null($info->oldfile->source)) {
5868
            $filedesc .= ' ('.$info->oldfile->source.')';
5869
        }
5870
 
5871
        return $filedesc;
5872
    }
5873
 
5874
    /**
5875
     * Return the expected location of a file
5876
     *
5877
     * Please note this may and may not work as a part of URL to pluginfile.php
5878
     * (depends on how the given component/filearea deals with the itemid).
5879
     *
5880
     * @param stdClass $filerecord
5881
     * @return string
5882
     */
5883
    private function expected_alias_location($filerecord) {
5884
 
5885
        $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
5886
        if (!is_null($filerecord->itemid)) {
5887
            $filedesc .= '/'.$filerecord->itemid;
5888
        }
5889
        $filedesc .= $filerecord->filepath.$filerecord->filename;
5890
 
5891
        return $filedesc;
5892
    }
5893
 
5894
    /**
5895
     * Append a value to the given resultset
5896
     *
5897
     * @param string $name name of the result containing a list of values
5898
     * @param mixed $value value to add as another item in that result
5899
     */
5900
    private function add_result_item($name, $value) {
5901
 
5902
        $results = $this->task->get_results();
5903
 
5904
        if (isset($results[$name])) {
5905
            if (!is_array($results[$name])) {
5906
                throw new coding_exception('Unable to append a result item into a non-array structure.');
5907
            }
5908
            $current = $results[$name];
5909
            $current[] = $value;
5910
            $this->task->add_result(array($name => $current));
5911
 
5912
        } else {
5913
            $this->task->add_result(array($name => array($value)));
5914
        }
5915
    }
5916
}
5917
 
5918
 
5919
/**
5920
 * Helper code for use by any plugin that stores question attempt data that it needs to back up.
5921
 */
5922
trait restore_questions_attempt_data_trait {
5923
    /** @var array question_attempt->id to qtype. */
5924
    protected $qtypes = array();
5925
    /** @var array question_attempt->id to questionid. */
5926
    protected $newquestionids = array();
5927
 
5928
    /**
5929
     * Attach below $element (usually attempts) the needed restore_path_elements
5930
     * to restore question_usages and all they contain.
5931
     *
5932
     * If you use the $nameprefix parameter, then you will need to implement some
5933
     * extra methods in your class, like
5934
     *
5935
     * protected function process_{nameprefix}question_attempt($data) {
5936
     *     $this->restore_question_usage_worker($data, '{nameprefix}');
5937
     * }
5938
     * protected function process_{nameprefix}question_attempt($data) {
5939
     *     $this->restore_question_attempt_worker($data, '{nameprefix}');
5940
     * }
5941
     * protected function process_{nameprefix}question_attempt_step($data) {
5942
     *     $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5943
     * }
5944
     *
5945
     * @param restore_path_element $element the parent element that the usages are stored inside.
5946
     * @param array $paths the paths array that is being built.
5947
     * @param string $nameprefix should match the prefix passed to the corresponding
5948
     *      backup_questions_activity_structure_step::add_question_usages call.
5949
     */
5950
    protected function add_question_usages($element, &$paths, $nameprefix = '') {
5951
        // Check $element is restore_path_element
5952
        if (! $element instanceof restore_path_element) {
5953
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
5954
        }
5955
 
5956
        // Check $paths is one array
5957
        if (!is_array($paths)) {
5958
            throw new restore_step_exception('paths_must_be_array', $paths);
5959
        }
5960
        $paths[] = new restore_path_element($nameprefix . 'question_usage',
5961
                $element->get_path() . "/{$nameprefix}question_usage");
5962
        $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5963
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5964
        $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5965
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5966
                true);
5967
        $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5968
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5969
    }
5970
 
5971
    /**
5972
     * Process question_usages
5973
     */
5974
    public function process_question_usage($data) {
5975
        $this->restore_question_usage_worker($data, '');
5976
    }
5977
 
5978
    /**
5979
     * Process question_attempts
5980
     */
5981
    public function process_question_attempt($data) {
5982
        $this->restore_question_attempt_worker($data, '');
5983
    }
5984
 
5985
    /**
5986
     * Process question_attempt_steps
5987
     */
5988
    public function process_question_attempt_step($data) {
5989
        $this->restore_question_attempt_step_worker($data, '');
5990
    }
5991
 
5992
    /**
5993
     * This method does the actual work for process_question_usage or
5994
     * process_{nameprefix}_question_usage.
5995
     * @param array $data the data from the XML file.
5996
     * @param string $nameprefix the element name prefix.
5997
     */
5998
    protected function restore_question_usage_worker($data, $nameprefix) {
5999
        global $DB;
6000
 
6001
        // Clear our caches.
6002
        $this->qtypes = array();
6003
        $this->newquestionids = array();
6004
 
6005
        $data = (object)$data;
6006
        $oldid = $data->id;
6007
 
6008
        $data->contextid  = $this->task->get_contextid();
6009
 
6010
        // Everything ready, insert (no mapping needed)
6011
        $newitemid = $DB->insert_record('question_usages', $data);
6012
 
6013
        $this->inform_new_usage_id($newitemid);
6014
 
6015
        $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
6016
    }
6017
 
6018
    /**
6019
     * When process_question_usage creates the new usage, it calls this method
6020
     * to let the activity link to the new usage. For example, the quiz uses
6021
     * this method to set quiz_attempts.uniqueid to the new usage id.
6022
     * @param integer $newusageid
6023
     */
6024
    abstract protected function inform_new_usage_id($newusageid);
6025
 
6026
    /**
6027
     * This method does the actual work for process_question_attempt or
6028
     * process_{nameprefix}_question_attempt.
6029
     * @param array $data the data from the XML file.
6030
     * @param string $nameprefix the element name prefix.
6031
     */
6032
    protected function restore_question_attempt_worker($data, $nameprefix) {
6033
        global $DB;
6034
 
6035
        $data = (object)$data;
6036
        $oldid = $data->id;
6037
 
6038
        $questioncreated = $this->get_mappingid('question_created', $data->questionid) ? true : false;
6039
        $question = $this->get_mapping('question', $data->questionid);
6040
        if ($questioncreated) {
6041
            $data->questionid = $question->newitemid;
6042
        }
6043
 
6044
        $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
6045
 
6046
        if (!property_exists($data, 'variant')) {
6047
            $data->variant = 1;
6048
        }
6049
 
6050
        if (!property_exists($data, 'maxfraction')) {
6051
            $data->maxfraction = 1;
6052
        }
6053
 
6054
        $newitemid = $DB->insert_record('question_attempts', $data);
6055
 
6056
        $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
6057
        if (isset($question->info->qtype)) {
6058
            $qtype = $question->info->qtype;
6059
        } else {
6060
            $qtype = $DB->get_record('question', ['id' => $data->questionid])->qtype;
6061
        }
6062
        $this->qtypes[$newitemid] = $qtype;
6063
        $this->newquestionids[$newitemid] = $data->questionid;
6064
    }
6065
 
6066
    /**
6067
     * This method does the actual work for process_question_attempt_step or
6068
     * process_{nameprefix}_question_attempt_step.
6069
     * @param array $data the data from the XML file.
6070
     * @param string $nameprefix the element name prefix.
6071
     */
6072
    protected function restore_question_attempt_step_worker($data, $nameprefix) {
6073
        global $DB;
6074
 
6075
        $data = (object)$data;
6076
        $oldid = $data->id;
6077
 
6078
        // Pull out the response data.
6079
        $response = array();
6080
        if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
6081
            foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
6082
                $response[$variable['name']] = $variable['value'];
6083
            }
6084
        }
6085
        unset($data->response);
6086
 
6087
        $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
6088
        $data->userid = $this->get_mappingid('user', $data->userid);
6089
 
6090
        // Everything ready, insert and create mapping (needed by question_sessions)
6091
        $newitemid = $DB->insert_record('question_attempt_steps', $data);
6092
        $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
6093
 
6094
        // Now process the response data.
6095
        $response = $this->questions_recode_response_data(
6096
                $this->qtypes[$data->questionattemptid],
6097
                $this->newquestionids[$data->questionattemptid],
6098
                $data->sequencenumber, $response);
6099
 
6100
        foreach ($response as $name => $value) {
6101
            $row = new stdClass();
6102
            $row->attemptstepid = $newitemid;
6103
            $row->name = $name;
6104
            $row->value = $value;
6105
            $DB->insert_record('question_attempt_step_data', $row, false);
6106
        }
6107
    }
6108
 
6109
    /**
6110
     * Recode the respones data for a particular step of an attempt at at particular question.
6111
     * @param string $qtype the question type.
6112
     * @param int $newquestionid the question id.
6113
     * @param int $sequencenumber the sequence number.
6114
     * @param array $response the response data to recode.
6115
     */
6116
    public function questions_recode_response_data(
6117
            $qtype, $newquestionid, $sequencenumber, array $response) {
6118
        $qtyperestorer = $this->get_qtype_restorer($qtype);
6119
        if ($qtyperestorer) {
6120
            $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
6121
        }
6122
        return $response;
6123
    }
6124
 
6125
    /**
6126
     * Given a list of question->ids, separated by commas, returns the
6127
     * recoded list, with all the restore question mappings applied.
6128
     * Note: Used by quiz->questions and quiz_attempts->layout
6129
     * Note: 0 = page break (unconverted)
6130
     */
6131
    protected function questions_recode_layout($layout) {
6132
        // Extracts question id from sequence
6133
        if ($questionids = explode(',', $layout)) {
6134
            foreach ($questionids as $id => $questionid) {
6135
                if ($questionid) { // If it is zero then this is a pagebreak, don't translate
6136
                    $newquestionid = $this->get_mappingid('question', $questionid);
6137
                    $questionids[$id] = $newquestionid;
6138
                }
6139
            }
6140
        }
6141
        return implode(',', $questionids);
6142
    }
6143
 
6144
    /**
6145
     * Get the restore_qtype_plugin subclass for a specific question type.
6146
     * @param string $qtype e.g. multichoice.
6147
     * @return restore_qtype_plugin instance.
6148
     */
6149
    protected function get_qtype_restorer($qtype) {
6150
        // Build one static cache to store {@link restore_qtype_plugin}
6151
        // while we are needing them, just to save zillions of instantiations
6152
        // or using static stuff that will break our nice API
6153
        static $qtypeplugins = array();
6154
 
6155
        if (!isset($qtypeplugins[$qtype])) {
6156
            $classname = 'restore_qtype_' . $qtype . '_plugin';
6157
            if (class_exists($classname)) {
6158
                $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
6159
            } else {
6160
                $qtypeplugins[$qtype] = null;
6161
            }
6162
        }
6163
        return $qtypeplugins[$qtype];
6164
    }
6165
 
6166
    protected function after_execute() {
6167
        parent::after_execute();
6168
 
6169
        // Restore any files belonging to responses.
6170
        foreach (question_engine::get_all_response_file_areas() as $filearea) {
6171
            $this->add_related_files('question', $filearea, 'question_attempt_step');
6172
        }
6173
    }
6174
}
6175
 
6176
/**
6177
 * Helper trait to restore question reference data.
6178
 */
6179
trait restore_question_reference_data_trait {
6180
 
6181
    /**
6182
     * Attach the question reference data to the restore.
6183
     *
6184
     * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6185
     * @param array $paths the paths array that is being built to describe the structure.
6186
     */
6187
    protected function add_question_references($element, &$paths) {
6188
        // Check $element is restore_path_element.
6189
        if (! $element instanceof restore_path_element) {
6190
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
6191
        }
6192
 
6193
        // Check $paths is one array.
6194
        if (!is_array($paths)) {
6195
            throw new restore_step_exception('paths_must_be_array', $paths);
6196
        }
6197
 
6198
        $paths[] = new restore_path_element('question_reference',
6199
            $element->get_path() . '/question_reference');
6200
    }
6201
 
6202
    /**
6203
     * Process question references which replaces the direct connection to quiz slots to question.
6204
     *
6205
     * @param array $data the data from the XML file.
6206
     */
6207
    public function process_question_reference($data) {
6208
        global $DB;
6209
        $data = (object) $data;
6210
        $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6211
        $data->itemid = $this->get_new_parentid('quiz_question_instance');
6212
        if ($entry = $this->get_mappingid('question_bank_entry', $data->questionbankentryid)) {
6213
            $data->questionbankentryid = $entry;
6214
        }
6215
        $DB->insert_record('question_references', $data);
6216
    }
6217
}
6218
 
6219
/**
6220
 * Helper trait to restore question set reference data.
6221
 */
6222
trait restore_question_set_reference_data_trait {
6223
 
6224
    /**
6225
     * Attach the question reference data to the restore.
6226
     *
6227
     * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6228
     * @param array $paths the paths array that is being built to describe the structure.
6229
     */
6230
    protected function add_question_set_references($element, &$paths) {
6231
        // Check $element is restore_path_element.
6232
        if (! $element instanceof restore_path_element) {
6233
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
6234
        }
6235
 
6236
        // Check $paths is one array.
6237
        if (!is_array($paths)) {
6238
            throw new restore_step_exception('paths_must_be_array', $paths);
6239
        }
6240
 
6241
        $paths[] = new restore_path_element('question_set_reference',
6242
            $element->get_path() . '/question_set_reference');
6243
    }
6244
 
6245
    /**
6246
     * Process question set references data which replaces the random qtype.
6247
     *
6248
     * @param array $data the data from the XML file.
6249
     */
6250
    public function process_question_set_reference($data) {
6251
        global $DB;
6252
        $data = (object) $data;
6253
        $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6254
        $data->itemid = $this->get_new_parentid('quiz_question_instance');
6255
        $filtercondition = json_decode($data->filtercondition, true);
6256
 
6257
        if (!isset($filtercondition['filter'])) {
6258
            // Pre-4.3, convert the old filtercondition format to the new format.
6259
            $filtercondition = \core_question\question_reference_manager::convert_legacy_set_reference_filter_condition(
6260
                    $filtercondition);
6261
        }
6262
 
6263
        // Map category id used for category filter condition and corresponding context id.
6264
        $oldcategoryid = $filtercondition['filter']['category']['values'][0];
6265
        $newcategoryid = $this->get_mappingid('question_category', $oldcategoryid);
6266
        $filtercondition['filter']['category']['values'][0] = $newcategoryid;
6267
 
6268
        if ($context = $this->get_mappingid('context', $data->questionscontextid)) {
6269
            $data->questionscontextid = $context;
6270
        } else {
6271
            $this->log('question_set_reference with old id ' . $data->id .
6272
                ' referenced question context ' . $data->questionscontextid .
6273
                ' which was not included in the backup. Therefore, this has been ' .
6274
                ' restored with the old questionscontextid.', backup::LOG_WARNING);
6275
        }
6276
 
6277
        $filtercondition['cat'] = implode(',', [
6278
            $filtercondition['filter']['category']['values'][0],
6279
            $data->questionscontextid,
6280
        ]);
6281
 
6282
        $data->filtercondition = json_encode($filtercondition);
6283
 
6284
        $DB->insert_record('question_set_references', $data);
6285
    }
6286
}
6287
 
6288
 
6289
/**
6290
 * Abstract structure step to help activities that store question attempt data.
6291
 *
6292
 * @copyright 2011 The Open University
6293
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6294
 */
6295
abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
6296
    use restore_questions_attempt_data_trait;
6297
    use restore_question_reference_data_trait;
6298
    use restore_question_set_reference_data_trait;
6299
 
6300
    /** @var \question_engine_attempt_upgrader manages upgrading all the question attempts. */
6301
    private $attemptupgrader;
6302
 
6303
    /**
6304
     * Attach below $element (usually attempts) the needed restore_path_elements
6305
     * to restore question attempt data from Moodle 2.0.
6306
     *
6307
     * When using this method, the parent element ($element) must be defined with
6308
     * $grouped = true. Then, in that elements process method, you must call
6309
     * {@link process_legacy_attempt_data()} with the groupded data. See, for
6310
     * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
6311
     * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6312
     * @param array $paths the paths array that is being built to describe the
6313
     *      structure.
6314
     */
6315
    protected function add_legacy_question_attempt_data($element, &$paths) {
6316
        global $CFG;
6317
        require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
6318
 
6319
        // Check $element is restore_path_element
6320
        if (!($element instanceof restore_path_element)) {
6321
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
6322
        }
6323
        // Check $paths is one array
6324
        if (!is_array($paths)) {
6325
            throw new restore_step_exception('paths_must_be_array', $paths);
6326
        }
6327
 
6328
        $paths[] = new restore_path_element('question_state',
6329
                $element->get_path() . '/states/state');
6330
        $paths[] = new restore_path_element('question_session',
6331
                $element->get_path() . '/sessions/session');
6332
    }
6333
 
6334
    protected function get_attempt_upgrader() {
6335
        if (empty($this->attemptupgrader)) {
6336
            $this->attemptupgrader = new question_engine_attempt_upgrader();
6337
            $this->attemptupgrader->prepare_to_restore();
6338
        }
6339
        return $this->attemptupgrader;
6340
    }
6341
 
6342
    /**
6343
     * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
6344
     * @param object $data contains all the grouped attempt data to process.
6345
     * @param object $quiz data about the activity the attempts belong to. Required
6346
     * fields are (basically this only works for the quiz module):
6347
     *      oldquestions => list of question ids in this activity - using old ids.
6348
     *      preferredbehaviour => the behaviour to use for questionattempts.
6349
     */
6350
    protected function process_legacy_quiz_attempt_data($data, $quiz) {
6351
        global $DB;
6352
        $upgrader = $this->get_attempt_upgrader();
6353
 
6354
        $data = (object)$data;
6355
 
6356
        $layout = explode(',', $data->layout);
6357
        $newlayout = $layout;
6358
 
6359
        // Convert each old question_session into a question_attempt.
6360
        $qas = array();
6361
        foreach (explode(',', $quiz->oldquestions) as $questionid) {
6362
            if ($questionid == 0) {
6363
                continue;
6364
            }
6365
 
6366
            $newquestionid = $this->get_mappingid('question', $questionid);
6367
            if (!$newquestionid) {
6368
                throw new restore_step_exception('questionattemptreferstomissingquestion',
6369
                        $questionid, $questionid);
6370
            }
6371
 
6372
            $question = $upgrader->load_question($newquestionid, $quiz->id);
6373
 
6374
            foreach ($layout as $key => $qid) {
6375
                if ($qid == $questionid) {
6376
                    $newlayout[$key] = $newquestionid;
6377
                }
6378
            }
6379
 
6380
            list($qsession, $qstates) = $this->find_question_session_and_states(
6381
                    $data, $questionid);
6382
 
6383
            if (empty($qsession) || empty($qstates)) {
6384
                throw new restore_step_exception('questionattemptdatamissing',
6385
                        $questionid, $questionid);
6386
            }
6387
 
6388
            list($qsession, $qstates) = $this->recode_legacy_response_data(
6389
                    $question, $qsession, $qstates);
6390
 
6391
            $data->layout = implode(',', $newlayout);
6392
            $qas[$newquestionid] = $upgrader->convert_question_attempt(
6393
                    $quiz, $data, $question, $qsession, $qstates);
6394
        }
6395
 
6396
        // Now create a new question_usage.
6397
        $usage = new stdClass();
6398
        $usage->component = 'mod_quiz';
6399
        $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
6400
        $usage->preferredbehaviour = $quiz->preferredbehaviour;
6401
        $usage->id = $DB->insert_record('question_usages', $usage);
6402
 
6403
        $this->inform_new_usage_id($usage->id);
6404
 
6405
        $data->uniqueid = $usage->id;
6406
        $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
6407
                $this->questions_recode_layout($quiz->oldquestions));
6408
    }
6409
 
6410
    protected function find_question_session_and_states($data, $questionid) {
6411
        $qsession = null;
6412
        foreach ($data->sessions['session'] as $session) {
6413
            if ($session['questionid'] == $questionid) {
6414
                $qsession = (object) $session;
6415
                break;
6416
            }
6417
        }
6418
 
6419
        $qstates = array();
6420
        foreach ($data->states['state'] as $state) {
6421
            if ($state['question'] == $questionid) {
6422
                // It would be natural to use $state['seq_number'] as the array-key
6423
                // here, but it seems that buggy behaviour in 2.0 and early can
6424
                // mean that that is not unique, so we use id, which is guaranteed
6425
                // to be unique.
6426
                $qstates[$state['id']] = (object) $state;
6427
            }
6428
        }
6429
        ksort($qstates);
6430
        $qstates = array_values($qstates);
6431
 
6432
        return array($qsession, $qstates);
6433
    }
6434
 
6435
    /**
6436
     * Recode any ids in the response data
6437
     * @param object $question the question data
6438
     * @param object $qsession the question sessions.
6439
     * @param array $qstates the question states.
6440
     */
6441
    protected function recode_legacy_response_data($question, $qsession, $qstates) {
6442
        $qsession->questionid = $question->id;
6443
 
6444
        foreach ($qstates as &$state) {
6445
            $state->question = $question->id;
6446
            $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
6447
        }
6448
 
6449
        return array($qsession, $qstates);
6450
    }
6451
 
6452
    /**
6453
     * Recode the legacy answer field.
6454
     * @param object $state the state to recode the answer of.
6455
     * @param string $qtype the question type.
6456
     */
6457
    public function restore_recode_legacy_answer($state, $qtype) {
6458
        $restorer = $this->get_qtype_restorer($qtype);
6459
        if ($restorer) {
6460
            return $restorer->recode_legacy_state_answer($state);
6461
        } else {
6462
            return $state->answer;
6463
        }
6464
    }
6465
}
6466
 
6467
 
6468
/**
6469
 * Restore completion defaults for each module type
6470
 *
6471
 * @package     core_backup
6472
 * @copyright   2017 Marina Glancy
6473
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6474
 */
6475
class restore_completion_defaults_structure_step extends restore_structure_step {
6476
    /**
6477
     * To conditionally decide if this step must be executed.
6478
     */
6479
    protected function execute_condition() {
6480
        // No completion on the front page.
6481
        if ($this->get_courseid() == SITEID) {
6482
            return false;
6483
        }
6484
 
6485
        // No default completion info found, don't execute.
6486
        $fullpath = $this->task->get_taskbasepath();
6487
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
6488
        if (!file_exists($fullpath)) {
6489
            return false;
6490
        }
6491
 
6492
        // Arrived here, execute the step.
6493
        return true;
6494
    }
6495
 
6496
    /**
6497
     * Function that will return the structure to be processed by this restore_step.
6498
     *
6499
     * @return restore_path_element[]
6500
     */
6501
    protected function define_structure() {
6502
        return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
6503
    }
6504
 
6505
    /**
6506
     * Processor for path element 'completion_defaults'
6507
     *
6508
     * @param stdClass|array $data
6509
     */
6510
    protected function process_completion_defaults($data) {
6511
        global $DB;
6512
 
6513
        $data = (array)$data;
6514
        $oldid = $data['id'];
6515
        unset($data['id']);
6516
 
6517
        // Find the module by name since id may be different in another site.
6518
        if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
6519
            return;
6520
        }
6521
        unset($data['modulename']);
6522
 
6523
        // Find the existing record.
6524
        $newid = $DB->get_field('course_completion_defaults', 'id',
6525
            ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
6526
        if (!$newid) {
6527
            $newid = $DB->insert_record('course_completion_defaults',
6528
                ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
6529
        } else {
6530
            $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
6531
        }
6532
 
6533
        // Save id mapping for restoring associated events.
6534
        $this->set_mapping('course_completion_defaults', $oldid, $newid);
6535
    }
6536
}
6537
 
6538
/**
6539
 * Index course after restore.
6540
 *
6541
 * @package core_backup
6542
 * @copyright 2017 The Open University
6543
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6544
 */
6545
class restore_course_search_index extends restore_execution_step {
6546
    /**
6547
     * When this step is executed, we add the course context to the queue for reindexing.
6548
     */
6549
    protected function define_execution() {
6550
        $context = \context_course::instance($this->task->get_courseid());
6551
        \core_search\manager::request_index($context);
6552
    }
6553
}
6554
 
6555
/**
6556
 * Index activity after restore (when not restoring whole course).
6557
 *
6558
 * @package core_backup
6559
 * @copyright 2017 The Open University
6560
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6561
 */
6562
class restore_activity_search_index extends restore_execution_step {
6563
    /**
6564
     * When this step is executed, we add the activity context to the queue for reindexing.
6565
     */
6566
    protected function define_execution() {
6567
        $context = \context::instance_by_id($this->task->get_contextid());
6568
        \core_search\manager::request_index($context);
6569
    }
6570
}
6571
 
6572
/**
6573
 * Index block after restore (when not restoring whole course).
6574
 *
6575
 * @package core_backup
6576
 * @copyright 2017 The Open University
6577
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6578
 */
6579
class restore_block_search_index extends restore_execution_step {
6580
    /**
6581
     * When this step is executed, we add the block context to the queue for reindexing.
6582
     */
6583
    protected function define_execution() {
6584
        // A block in the restore list may be skipped because a duplicate is detected.
6585
        // In this case, there is no new blockid (or context) to get.
6586
        if (!empty($this->task->get_blockid())) {
6587
            $context = \context_block::instance($this->task->get_blockid());
6588
            \core_search\manager::request_index($context);
6589
        }
6590
    }
6591
}
6592
 
6593
/**
6594
 * Restore action events.
6595
 *
6596
 * @package     core_backup
6597
 * @copyright   2017 onwards Ankit Agarwal
6598
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6599
 */
6600
class restore_calendar_action_events extends restore_execution_step {
6601
    /**
6602
     * What to do when this step is executed.
6603
     */
6604
    protected function define_execution() {
6605
        // We just queue the task here rather trying to recreate everything manually.
6606
        // The task will automatically populate all data.
6607
        $task = new \core\task\refresh_mod_calendar_events_task();
6608
        $task->set_custom_data(array('courseid' => $this->get_courseid()));
6609
        \core\task\manager::queue_adhoc_task($task, true);
6610
    }
6611
}