Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | 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
            }
1632
            $section->component = $data->component ?? null;
1633
            $section->itemid = $data->itemid ?? null;
1634
            $newitemid = $DB->insert_record('course_sections', $section);
1635
            $section->id = $newitemid;
1636
 
1637
            core\event\course_section_created::create_from_section($section)->trigger();
1638
 
1639
            $restorefiles = true;
1640
 
1641
        // Section exists, update non-empty information
1642
        } else {
1643
            $section->id = $secrec->id;
1644
            if ((string)$secrec->name === '') {
1645
                $section->name = $data->name;
1646
            }
1647
            if (empty($secrec->summary)) {
1648
                $section->summary = $data->summary;
1649
                $section->summaryformat = $data->summaryformat;
1650
                $restorefiles = true;
1651
            }
1652
 
1653
            // Don't update availability (I didn't see a useful way to define
1654
            // whether existing or new one should take precedence).
1655
 
1656
            $DB->update_record('course_sections', $section);
1657
            $newitemid = $secrec->id;
1658
 
1659
            // Trigger an event for course section update.
1660
            $event = \core\event\course_section_updated::create(
1661
                array(
1662
                    'objectid' => $section->id,
1663
                    'courseid' => $section->course,
1664
                    'context' => context_course::instance($section->course),
1665
                    'other' => array('sectionnum' => $section->section)
1666
                )
1667
            );
1668
            $event->trigger();
1669
        }
1670
 
1671
        // Annotate the section mapping, with restorefiles option if needed
1672
        $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1673
 
1674
        // set the new course_section id in the task
1675
        $this->task->set_sectionid($newitemid);
1676
 
1677
        // If there is the legacy showavailability data, store this for later use.
1678
        // (This data is not present when restoring 'new' backups.)
1679
        if (isset($data->showavailability)) {
1680
            // Cache the showavailability flag using the backup_ids data field.
1681
            restore_dbops::set_backup_ids_record($this->get_restoreid(),
1682
                    'section_showavailability', $newitemid, 0, null,
1683
                    (object)array('showavailability' => $data->showavailability));
1684
        }
1685
 
1686
        // Commented out. We never modify course->numsections as far as that is used
1687
        // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1688
        // Note: We keep the code here, to know about and because of the possibility of making this
1689
        // optional based on some setting/attribute in the future
1690
        // If needed, adjust course->numsections
1691
        //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1692
        //    if ($numsections < $section->section) {
1693
        //        $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1694
        //    }
1695
        //}
1696
    }
1697
 
1698
    /**
1699
     * Process the legacy availability table record. This table does not exist
1700
     * in Moodle 2.7+ but we still support restore.
1701
     *
1702
     * @param stdClass $data Record data
1703
     */
1704
    public function process_availability($data) {
1705
        $data = (object)$data;
1706
        // Simply going to store the whole availability record now, we'll process
1707
        // all them later in the final task (once all activities have been restored)
1708
        // Let's call the low level one to be able to store the whole object.
1709
        $data->coursesectionid = $this->task->get_sectionid();
1710
        restore_dbops::set_backup_ids_record($this->get_restoreid(),
1711
                'section_availability', $data->id, 0, null, $data);
1712
    }
1713
 
1714
    /**
1715
     * Process the legacy availability fields table record. This table does not
1716
     * exist in Moodle 2.7+ but we still support restore.
1717
     *
1718
     * @param stdClass $data Record data
1719
     */
1720
    public function process_availability_field($data) {
1721
        global $DB, $CFG;
1722
        require_once($CFG->dirroot.'/user/profile/lib.php');
1723
 
1724
        $data = (object)$data;
1725
        // Mark it is as passed by default
1726
        $passed = true;
1727
        $customfieldid = null;
1728
 
1729
        // If a customfield has been used in order to pass we must be able to match an existing
1730
        // customfield by name (data->customfield) and type (data->customfieldtype)
1731
        if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1732
            // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1733
            // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1734
            $passed = false;
1735
        } else if (!is_null($data->customfield)) {
1736
            $field = profile_get_custom_field_data_by_shortname($data->customfield);
1737
            $passed = $field && $field->datatype == $data->customfieldtype;
1738
        }
1739
 
1740
        if ($passed) {
1741
            // Create the object to insert into the database
1742
            $availfield = new stdClass();
1743
            $availfield->coursesectionid = $this->task->get_sectionid();
1744
            $availfield->userfield = $data->userfield;
1745
            $availfield->customfieldid = $customfieldid;
1746
            $availfield->operator = $data->operator;
1747
            $availfield->value = $data->value;
1748
 
1749
            // Get showavailability option.
1750
            $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1751
                    'section_showavailability', $availfield->coursesectionid);
1752
            if (!$showrec) {
1753
                // Should not happen.
1754
                throw new coding_exception('No matching showavailability record');
1755
            }
1756
            $show = $showrec->info->showavailability;
1757
 
1758
            // The $availfield object is now in the format used in the old
1759
            // system. Interpret this and convert to new system.
1760
            $currentvalue = $DB->get_field('course_sections', 'availability',
1761
                    array('id' => $availfield->coursesectionid), MUST_EXIST);
1762
            $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1763
                    $currentvalue, $availfield, $show);
1764
 
1765
            $section = new stdClass();
1766
            $section->id = $availfield->coursesectionid;
1767
            $section->availability = $newvalue;
1768
            $section->timemodified = time();
1769
            $DB->update_record('course_sections', $section);
1770
        }
1771
    }
1772
 
1773
    public function process_course_format_options($data) {
1774
        global $DB;
1775
        $courseid = $this->get_courseid();
1776
        if (!array_key_exists($courseid, self::$courseformats)) {
1777
            // It is safe to have a static cache of course formats because format can not be changed after this point.
1778
            self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1779
        }
1780
        $data = (array)$data;
1781
        if (self::$courseformats[$courseid] === $data['format']) {
1782
            // Import section format options only if both courses (the one that was backed up
1783
            // and the one we are restoring into) have same formats.
1784
            $params = array(
1785
                'courseid' => $this->get_courseid(),
1786
                'sectionid' => $this->task->get_sectionid(),
1787
                'format' => $data['format'],
1788
                'name' => $data['name']
1789
            );
1790
            if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1791
                // Do not overwrite existing information.
1792
                $newid = $record->id;
1793
            } else {
1794
                $params['value'] = $data['value'];
1795
                $newid = $DB->insert_record('course_format_options', $params);
1796
            }
1797
            $this->set_mapping('course_format_options', $data['id'], $newid);
1798
        }
1799
    }
1800
 
1801
    protected function after_execute() {
1802
        // Add section related files, with 'course_section' itemid to match
1803
        $this->add_related_files('course', 'section', 'course_section');
1804
    }
1805
}
1806
 
1807
/**
1808
 * Structure step that will read the course.xml file, loading it and performing
1809
 * various actions depending of the site/restore settings. Note that target
1810
 * course always exist before arriving here so this step will be updating
1811
 * the course record (never inserting)
1812
 */
1813
class restore_course_structure_step extends restore_structure_step {
1814
    /**
1815
     * @var bool this gets set to true by {@link process_course()} if we are
1816
     * restoring an old coures that used the legacy 'module security' feature.
1817
     * If so, we have to do more work in {@link after_execute()}.
1818
     */
1819
    protected $legacyrestrictmodules = false;
1820
 
1821
    /**
1822
     * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1823
     * array with array keys the module names ('forum', 'quiz', etc.). These are
1824
     * the modules that are allowed according to the data in the backup file.
1825
     * In {@link after_execute()} we then have to prevent adding of all the other
1826
     * types of activity.
1827
     */
1828
    protected $legacyallowedmodules = array();
1829
 
1830
    protected function define_structure() {
1831
 
1832
        $course = new restore_path_element('course', '/course');
1833
        $category = new restore_path_element('category', '/course/category');
1834
        $tag = new restore_path_element('tag', '/course/tags/tag');
1835
        $customfield = new restore_path_element('customfield', '/course/customfields/customfield');
1836
        $courseformatoptions = new restore_path_element('course_format_option', '/course/courseformatoptions/courseformatoption');
1837
        $allowedmodule = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1838
 
1839
        // Apply for 'format' plugins optional paths at course level
1840
        $this->add_plugin_structure('format', $course);
1841
 
1842
        // Apply for 'theme' plugins optional paths at course level
1843
        $this->add_plugin_structure('theme', $course);
1844
 
1845
        // Apply for 'report' plugins optional paths at course level
1846
        $this->add_plugin_structure('report', $course);
1847
 
1848
        // Apply for 'course report' plugins optional paths at course level
1849
        $this->add_plugin_structure('coursereport', $course);
1850
 
1851
        // Apply for plagiarism plugins optional paths at course level
1852
        $this->add_plugin_structure('plagiarism', $course);
1853
 
1854
        // Apply for local plugins optional paths at course level
1855
        $this->add_plugin_structure('local', $course);
1856
 
1857
        // Apply for admin tool plugins optional paths at course level.
1858
        $this->add_plugin_structure('tool', $course);
1859
 
1860
        return array($course, $category, $tag, $customfield, $allowedmodule, $courseformatoptions);
1861
    }
1862
 
1863
    /**
1864
     * Processing functions go here
1865
     *
1866
     * @global moodledatabase $DB
1867
     * @param stdClass $data
1868
     */
1869
    public function process_course($data) {
1870
        global $CFG, $DB;
1871
        $context = context::instance_by_id($this->task->get_contextid());
1872
        $userid = $this->task->get_userid();
1873
        $target = $this->get_task()->get_target();
1874
        $isnewcourse = $target == backup::TARGET_NEW_COURSE;
1875
 
1876
        // When restoring to a new course we can set all the things except for the ID number.
1877
        $canchangeidnumber = $isnewcourse || has_capability('moodle/course:changeidnumber', $context, $userid);
1878
        $canchangesummary = $isnewcourse || has_capability('moodle/course:changesummary', $context, $userid);
1879
        $canforcelanguage = has_capability('moodle/course:setforcedlanguage', $context, $userid);
1880
 
1881
        $data = (object)$data;
1882
        $data->id = $this->get_courseid();
1883
 
1884
        // Calculate final course names, to avoid dupes.
1885
        $fullname  = $this->get_setting_value('course_fullname');
1886
        $shortname = $this->get_setting_value('course_shortname');
1887
        list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names($this->get_courseid(),
1888
            $fullname === false ? $data->fullname : $fullname,
1889
            $shortname === false ? $data->shortname : $shortname);
1890
        // Do not modify the course names at all when merging and user selected to keep the names (or prohibited by cap).
1891
        if (!$isnewcourse && $fullname === false) {
1892
            unset($data->fullname);
1893
        }
1894
        if (!$isnewcourse && $shortname === false) {
1895
            unset($data->shortname);
1896
        }
1897
 
1898
        // Unset summary if user can't change it.
1899
        if (!$canchangesummary) {
1900
            unset($data->summary);
1901
            unset($data->summaryformat);
1902
        }
1903
 
1904
        // Unset lang if user can't change it.
1905
        if (!$canforcelanguage) {
1906
            unset($data->lang);
1907
        }
1908
 
1909
        // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1910
        // another course on this site.
1911
        if (!empty($data->idnumber) && $canchangeidnumber && $this->task->is_samesite()
1912
                && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1913
            // Do not reset idnumber.
1914
 
1915
        } else if (!$isnewcourse) {
1916
            // Prevent override when restoring as merge.
1917
            unset($data->idnumber);
1918
 
1919
        } else {
1920
            $data->idnumber = '';
1921
        }
1922
 
1923
        // If we restore a course from this site, let's capture the original course id.
1924
        if ($isnewcourse && $this->get_task()->is_samesite()) {
1925
            $data->originalcourseid = $this->get_task()->get_old_courseid();
1926
        }
1927
 
1928
        // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1929
        // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1930
        if (empty($data->hiddensections)) {
1931
            $data->hiddensections = 0;
1932
        }
1933
 
1934
        // Set legacyrestrictmodules to true if the course was resticting modules. If so
1935
        // then we will need to process restricted modules after execution.
1936
        $this->legacyrestrictmodules = !empty($data->restrictmodules);
1937
 
1938
        $data->startdate= $this->apply_date_offset($data->startdate);
1939
        if (isset($data->enddate)) {
1940
            $data->enddate = $this->apply_date_offset($data->enddate);
1941
        }
1942
 
1943
        if ($data->defaultgroupingid) {
1944
            $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1945
        }
1946
 
1947
        $courseconfig = get_config('moodlecourse');
1948
 
1949
        if (empty($CFG->enablecompletion)) {
1950
            // Completion is disabled globally.
1951
            $data->enablecompletion = 0;
1952
            $data->completionstartonenrol = 0;
1953
            $data->completionnotify = 0;
1954
            $data->showcompletionconditions = null;
1955
        } else {
1956
            $showcompletionconditionsdefault = ($courseconfig->showcompletionconditions ?? null);
1957
            $data->showcompletionconditions = $data->showcompletionconditions ?? $showcompletionconditionsdefault;
1958
        }
1959
 
1960
        $showactivitydatesdefault = ($courseconfig->showactivitydates ?? null);
1961
        $data->showactivitydates = $data->showactivitydates ?? $showactivitydatesdefault;
1962
 
1963
        $pdffontdefault = ($courseconfig->pdfexportfont ?? null);
1964
        $data->pdfexportfont = $data->pdfexportfont ?? $pdffontdefault;
1965
 
1966
        $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1967
        if (isset($data->lang) && !array_key_exists($data->lang, $languages)) {
1968
            $data->lang = '';
1969
        }
1970
 
1971
        $themes = get_list_of_themes(); // Get themes for quick search later
1972
        if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1973
            $data->theme = '';
1974
        }
1975
 
1976
        // Check if this is an old SCORM course format.
1977
        if ($data->format == 'scorm') {
1978
            $data->format = 'singleactivity';
1979
            $data->activitytype = 'scorm';
1980
        }
1981
 
1982
        // Course record ready, update it
1983
        $DB->update_record('course', $data);
1984
 
1985
        // Apply any course format options that may be saved against the course
1986
        // entity in earlier-version backups.
1987
        course_get_format($data)->update_course_format_options($data);
1988
 
1989
        // Role name aliases
1990
        restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1991
    }
1992
 
1993
    public function process_category($data) {
1994
        // Nothing to do with the category. UI sets it before restore starts
1995
    }
1996
 
1997
    public function process_tag($data) {
1998
        global $CFG, $DB;
1999
 
2000
        $data = (object)$data;
2001
 
2002
        core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
2003
                context_course::instance($this->get_courseid()), $data->rawname);
2004
    }
2005
 
2006
    /**
2007
     * Process custom fields
2008
     *
2009
     * @param array $data
2010
     */
2011
    public function process_customfield($data) {
2012
        $handler = core_course\customfield\course_handler::create();
2013
        $newid = $handler->restore_instance_data_from_backup($this->task, $data);
2014
 
2015
        if ($newid) {
2016
            $handler->restore_define_structure($this, $newid, $data['id']);
2017
        }
2018
    }
2019
 
2020
    /**
2021
     * Processes a course format option.
2022
     *
2023
     * @param array $data The record being restored.
2024
     * @throws base_step_exception
2025
     * @throws dml_exception
2026
     */
2027
    public function process_course_format_option(array $data): void {
2028
        global $DB;
2029
 
2030
        if ($data['sectionid']) {
2031
            // Ignore section-level format options saved course-level in earlier-version backups.
2032
            return;
2033
        }
2034
 
2035
        $courseid = $this->get_courseid();
2036
        $record = $DB->get_record('course_format_options', [ 'courseid' => $courseid, 'name' => $data['name'],
2037
                'format' => $data['format'], 'sectionid' => 0 ], 'id');
2038
        if ($record !== false) {
2039
            $DB->update_record('course_format_options', (object) [ 'id' => $record->id, 'value' => $data['value'] ]);
2040
        } else {
2041
            $data['courseid'] = $courseid;
2042
            $DB->insert_record('course_format_options', (object) $data);
2043
        }
2044
    }
2045
 
2046
    public function process_allowed_module($data) {
2047
        $data = (object)$data;
2048
 
2049
        // Backwards compatiblity support for the data that used to be in the
2050
        // course_allowed_modules table.
2051
        if ($this->legacyrestrictmodules) {
2052
            $this->legacyallowedmodules[$data->modulename] = 1;
2053
        }
2054
    }
2055
 
2056
    protected function after_execute() {
2057
        global $DB;
2058
 
2059
        // Add course related files, without itemid to match
2060
        $this->add_related_files('course', 'summary', null);
2061
        $this->add_related_files('course', 'overviewfiles', null);
2062
 
2063
        // Deal with legacy allowed modules.
2064
        if ($this->legacyrestrictmodules) {
2065
            $context = context_course::instance($this->get_courseid());
2066
 
2067
            list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
2068
            list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
2069
            foreach ($managerroleids as $roleid) {
2070
                unset($roleids[$roleid]);
2071
            }
2072
 
2073
            foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
2074
                if (isset($this->legacyallowedmodules[$modname])) {
2075
                    // Module is allowed, no worries.
2076
                    continue;
2077
                }
2078
 
2079
                $capability = 'mod/' . $modname . ':addinstance';
2080
 
2081
                if (!get_capability_info($capability)) {
2082
                    $this->log("Capability '{$capability}' was not found!", backup::LOG_WARNING);
2083
                    continue;
2084
                }
2085
 
2086
                foreach ($roleids as $roleid) {
2087
                    assign_capability($capability, CAP_PREVENT, $roleid, $context);
2088
                }
2089
            }
2090
        }
2091
    }
2092
}
2093
 
2094
/**
2095
 * Execution step that will migrate legacy files if present.
2096
 */
2097
class restore_course_legacy_files_step extends restore_execution_step {
2098
    public function define_execution() {
2099
        global $DB;
2100
 
2101
        // Do a check for legacy files and skip if there are none.
2102
        $sql = 'SELECT count(*)
2103
                  FROM {backup_files_temp}
2104
                 WHERE backupid = ?
2105
                   AND contextid = ?
2106
                   AND component = ?
2107
                   AND filearea  = ?';
2108
        $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
2109
 
2110
        if ($DB->count_records_sql($sql, $params)) {
2111
            $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
2112
            restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
2113
                'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
2114
        }
2115
    }
2116
}
2117
 
2118
/*
2119
 * Structure step that will read the roles.xml file (at course/activity/block levels)
2120
 * containing all the role_assignments and overrides for that context. If corresponding to
2121
 * one mapped role, they will be applied to target context. Will observe the role_assignments
2122
 * setting to decide if ras are restored.
2123
 *
2124
 * Note: this needs to be executed after all users are enrolled.
2125
 */
2126
class restore_ras_and_caps_structure_step extends restore_structure_step {
2127
    protected $plugins = null;
2128
 
2129
    protected function define_structure() {
2130
 
2131
        $paths = array();
2132
 
2133
        // Observe the role_assignments setting
2134
        if ($this->get_setting_value('role_assignments')) {
2135
            $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
2136
        }
2137
        if ($this->get_setting_value('permissions')) {
2138
            $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
2139
        }
2140
 
2141
        return $paths;
2142
    }
2143
 
2144
    /**
2145
     * Assign roles
2146
     *
2147
     * This has to be called after enrolments processing.
2148
     *
2149
     * @param mixed $data
2150
     * @return void
2151
     */
2152
    public function process_assignment($data) {
2153
        global $DB;
2154
 
2155
        $data = (object)$data;
2156
 
2157
        // Check roleid, userid are one of the mapped ones
2158
        if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
2159
            return;
2160
        }
2161
        if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
2162
            return;
2163
        }
2164
        if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
2165
            // Only assign roles to not deleted users
2166
            return;
2167
        }
2168
        if (!$contextid = $this->task->get_contextid()) {
2169
            return;
2170
        }
2171
 
2172
        if (empty($data->component)) {
2173
            // assign standard manual roles
2174
            // TODO: role_assign() needs one userid param to be able to specify our restore userid
2175
            role_assign($newroleid, $newuserid, $contextid);
2176
 
2177
        } else if ((strpos($data->component, 'enrol_') === 0)) {
2178
            // Deal with enrolment roles - ignore the component and just find out the instance via new id,
2179
            // it is possible that enrolment was restored using different plugin type.
2180
            if (!isset($this->plugins)) {
2181
                $this->plugins = enrol_get_plugins(true);
2182
            }
2183
            if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
2184
                if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2185
                    if (isset($this->plugins[$instance->enrol])) {
2186
                        $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
2187
                    }
2188
                }
2189
            }
2190
 
2191
        } else {
2192
            $data->roleid    = $newroleid;
2193
            $data->userid    = $newuserid;
2194
            $data->contextid = $contextid;
2195
            $dir = core_component::get_component_directory($data->component);
2196
            if ($dir and is_dir($dir)) {
2197
                if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
2198
                    return;
2199
                }
2200
            }
2201
            // Bad luck, plugin could not restore the data, let's add normal membership.
2202
            role_assign($data->roleid, $data->userid, $data->contextid);
2203
            $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
2204
            $this->log($message, backup::LOG_WARNING);
2205
        }
2206
    }
2207
 
2208
    public function process_override($data) {
2209
        $data = (object)$data;
2210
        // Check roleid is one of the mapped ones
2211
        $newrole = $this->get_mapping('role', $data->roleid);
2212
        $newroleid = $newrole->newitemid ?? false;
2213
        $userid = $this->task->get_userid();
2214
 
2215
        // If newroleid and context are valid assign it via API (it handles dupes and so on)
2216
        if ($newroleid && $this->task->get_contextid()) {
2217
            if (!$capability = get_capability_info($data->capability)) {
2218
                $this->log("Capability '{$data->capability}' was not found!", backup::LOG_WARNING);
2219
            } else {
2220
                $context = context::instance_by_id($this->task->get_contextid());
2221
                $overrideableroles = get_overridable_roles($context, ROLENAME_SHORT);
2222
                $safecapability = is_safe_capability($capability);
2223
 
2224
                // Check if the new role is an overrideable role AND if the user performing the restore has the
2225
                // capability to assign the capability.
2226
                if (in_array($newrole->info['shortname'], $overrideableroles) &&
2227
                    (has_capability('moodle/role:override', $context, $userid) ||
2228
                            ($safecapability && has_capability('moodle/role:safeoverride', $context, $userid)))
2229
                ) {
2230
                    assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
2231
                } else {
2232
                    $this->log("Insufficient capability to assign capability '{$data->capability}' to role!", backup::LOG_WARNING);
2233
                }
2234
            }
2235
        }
2236
    }
2237
}
2238
 
2239
/**
2240
 * If no instances yet add default enrol methods the same way as when creating new course in UI.
2241
 */
2242
class restore_default_enrolments_step extends restore_execution_step {
2243
 
2244
    public function define_execution() {
2245
        global $DB;
2246
 
2247
        // No enrolments in front page.
2248
        if ($this->get_courseid() == SITEID) {
2249
            return;
2250
        }
2251
 
2252
        $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
2253
        // Return any existing course enrolment instances.
2254
        $enrolinstances = enrol_get_instances($course->id, false);
2255
 
2256
        if ($enrolinstances) {
2257
            // Something already added instances.
2258
            // Get the existing enrolment methods in the course.
2259
            $enrolmethods = array_map(function($enrolinstance) {
2260
                return $enrolinstance->enrol;
2261
            }, $enrolinstances);
2262
 
2263
            $plugins = enrol_get_plugins(true);
2264
            foreach ($plugins as $pluginname => $plugin) {
2265
                // Make sure all default enrolment methods exist in the course.
2266
                if (!in_array($pluginname, $enrolmethods)) {
2267
                    $plugin->course_updated(true, $course, null);
2268
                }
2269
                $plugin->restore_sync_course($course);
2270
            }
2271
 
2272
        } else {
2273
            // Looks like a newly created course.
2274
            enrol_course_updated(true, $course, null);
2275
        }
2276
    }
2277
}
2278
 
2279
/**
2280
 * This structure steps restores the enrol plugins and their underlying
2281
 * enrolments, performing all the mappings and/or movements required
2282
 */
2283
class restore_enrolments_structure_step extends restore_structure_step {
2284
    protected $enrolsynced = false;
2285
    protected $plugins = null;
2286
    protected $originalstatus = array();
2287
 
2288
    /**
2289
     * Conditionally decide if this step should be executed.
2290
     *
2291
     * This function checks the following parameter:
2292
     *
2293
     *   1. the course/enrolments.xml file exists
2294
     *
2295
     * @return bool true is safe to execute, false otherwise
2296
     */
2297
    protected function execute_condition() {
2298
 
2299
        if ($this->get_courseid() == SITEID) {
2300
            return false;
2301
        }
2302
 
2303
        // Check it is included in the backup
2304
        $fullpath = $this->task->get_taskbasepath();
2305
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2306
        if (!file_exists($fullpath)) {
2307
            // Not found, can't restore enrolments info
2308
            return false;
2309
        }
2310
 
2311
        return true;
2312
    }
2313
 
2314
    protected function define_structure() {
2315
 
2316
        $userinfo = $this->get_setting_value('users');
2317
 
2318
        $paths = [];
2319
        $paths[] = $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2320
        if ($userinfo) {
2321
            $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2322
        }
2323
        // Attach local plugin stucture to enrol element.
2324
        $this->add_plugin_structure('enrol', $enrol);
2325
 
2326
        return $paths;
2327
    }
2328
 
2329
    /**
2330
     * Create enrolment instances.
2331
     *
2332
     * This has to be called after creation of roles
2333
     * and before adding of role assignments.
2334
     *
2335
     * @param mixed $data
2336
     * @return void
2337
     */
2338
    public function process_enrol($data) {
2339
        global $DB;
2340
 
2341
        $data = (object)$data;
2342
        $oldid = $data->id; // We'll need this later.
2343
        unset($data->id);
2344
 
2345
        $this->originalstatus[$oldid] = $data->status;
2346
 
2347
        if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2348
            $this->set_mapping('enrol', $oldid, 0);
2349
            return;
2350
        }
2351
 
2352
        if (!isset($this->plugins)) {
2353
            $this->plugins = enrol_get_plugins(true);
2354
        }
2355
 
2356
        if (!$this->enrolsynced) {
2357
            // Make sure that all plugin may create instances and enrolments automatically
2358
            // before the first instance restore - this is suitable especially for plugins
2359
            // that synchronise data automatically using course->idnumber or by course categories.
2360
            foreach ($this->plugins as $plugin) {
2361
                $plugin->restore_sync_course($courserec);
2362
            }
2363
            $this->enrolsynced = true;
2364
        }
2365
 
2366
        // Map standard fields - plugin has to process custom fields manually.
2367
        $data->roleid   = $this->get_mappingid('role', $data->roleid);
2368
        $data->courseid = $courserec->id;
2369
 
2370
        if (!$this->get_setting_value('users') && $this->get_setting_value('enrolments') == backup::ENROL_WITHUSERS) {
2371
            $converttomanual = true;
2372
        } else {
2373
            $converttomanual = ($this->get_setting_value('enrolments') == backup::ENROL_NEVER);
2374
        }
2375
 
2376
        if ($converttomanual) {
2377
            // Restore enrolments as manual enrolments.
2378
            unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2379
            if (!enrol_is_enabled('manual')) {
2380
                $this->set_mapping('enrol', $oldid, 0);
2381
                return;
2382
            }
2383
            if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2384
                $instance = reset($instances);
2385
                $this->set_mapping('enrol', $oldid, $instance->id);
2386
            } else {
2387
                if ($data->enrol === 'manual') {
2388
                    $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2389
                } else {
2390
                    $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2391
                }
2392
                $this->set_mapping('enrol', $oldid, $instanceid);
2393
            }
2394
 
2395
        } else {
2396
            if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2397
                $this->set_mapping('enrol', $oldid, 0);
2398
                $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, consider restoring without enrolment methods";
2399
                $this->log($message, backup::LOG_WARNING);
2400
                return;
2401
            }
2402
            if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2403
                // Let's keep the sortorder in old backups.
2404
            } else {
2405
                // Prevent problems with colliding sortorders in old backups,
2406
                // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2407
                unset($data->sortorder);
2408
            }
2409
            // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2410
            $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2411
        }
2412
    }
2413
 
2414
    /**
2415
     * Create user enrolments.
2416
     *
2417
     * This has to be called after creation of enrolment instances
2418
     * and before adding of role assignments.
2419
     *
2420
     * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2421
     *
2422
     * @param mixed $data
2423
     * @return void
2424
     */
2425
    public function process_enrolment($data) {
2426
        global $DB;
2427
 
2428
        if (!isset($this->plugins)) {
2429
            $this->plugins = enrol_get_plugins(true);
2430
        }
2431
 
2432
        $data = (object)$data;
2433
 
2434
        // Process only if parent instance have been mapped.
2435
        if ($enrolid = $this->get_new_parentid('enrol')) {
2436
            $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2437
            $oldenrolid = $this->get_old_parentid('enrol');
2438
            if (isset($this->originalstatus[$oldenrolid])) {
2439
                $oldinstancestatus = $this->originalstatus[$oldenrolid];
2440
            }
2441
            if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2442
                // And only if user is a mapped one.
2443
                if ($userid = $this->get_mappingid('user', $data->userid)) {
2444
                    if (isset($this->plugins[$instance->enrol])) {
2445
                        $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2446
                    }
2447
                }
2448
            }
2449
        }
2450
    }
2451
}
2452
 
2453
 
2454
/**
2455
 * Make sure the user restoring the course can actually access it.
2456
 */
2457
class restore_fix_restorer_access_step extends restore_execution_step {
2458
    protected function define_execution() {
2459
        global $CFG, $DB;
2460
 
2461
        if (!$userid = $this->task->get_userid()) {
2462
            return;
2463
        }
2464
 
2465
        if (empty($CFG->restorernewroleid)) {
2466
            // Bad luck, no fallback role for restorers specified
2467
            return;
2468
        }
2469
 
2470
        $courseid = $this->get_courseid();
2471
        $context = context_course::instance($courseid);
2472
 
2473
        if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2474
            // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2475
            return;
2476
        }
2477
 
2478
        // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2479
        role_assign($CFG->restorernewroleid, $userid, $context);
2480
 
2481
        if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2482
            // Extra role is enough, yay!
2483
            return;
2484
        }
2485
 
2486
        // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2487
        // hopefully admin selected suitable $CFG->restorernewroleid ...
2488
        if (!enrol_is_enabled('manual')) {
2489
            return;
2490
        }
2491
        if (!$enrol = enrol_get_plugin('manual')) {
2492
            return;
2493
        }
2494
        if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2495
            $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2496
            $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2497
            $enrol->add_instance($course, $fields);
2498
        }
2499
 
2500
        enrol_try_internal_enrol($courseid, $userid);
2501
    }
2502
}
2503
 
2504
 
2505
/**
2506
 * This structure steps restores the filters and their configs
2507
 */
2508
class restore_filters_structure_step extends restore_structure_step {
2509
 
2510
    protected function define_structure() {
2511
 
2512
        $paths = array();
2513
 
2514
        $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2515
        $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2516
 
2517
        return $paths;
2518
    }
2519
 
2520
    public function process_active($data) {
2521
 
2522
        $data = (object)$data;
2523
 
2524
        if (strpos($data->filter, 'filter/') === 0) {
2525
            $data->filter = substr($data->filter, 7);
2526
 
2527
        } else if (strpos($data->filter, '/') !== false) {
2528
            // Unsupported old filter.
2529
            return;
2530
        }
2531
 
2532
        if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2533
            return;
2534
        }
2535
        filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2536
    }
2537
 
2538
    public function process_config($data) {
2539
 
2540
        $data = (object)$data;
2541
 
2542
        if (strpos($data->filter, 'filter/') === 0) {
2543
            $data->filter = substr($data->filter, 7);
2544
 
2545
        } else if (strpos($data->filter, '/') !== false) {
2546
            // Unsupported old filter.
2547
            return;
2548
        }
2549
 
2550
        if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2551
            return;
2552
        }
2553
        filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2554
    }
2555
}
2556
 
2557
 
2558
/**
2559
 * This structure steps restores the comments
2560
 * Note: Cannot use the comments API because defaults to USER->id.
2561
 * That should change allowing to pass $userid
2562
 */
2563
class restore_comments_structure_step extends restore_structure_step {
2564
 
2565
    protected function define_structure() {
2566
 
2567
        $paths = array();
2568
 
2569
        $paths[] = new restore_path_element('comment', '/comments/comment');
2570
 
2571
        return $paths;
2572
    }
2573
 
2574
    public function process_comment($data) {
2575
        global $DB;
2576
 
2577
        $data = (object)$data;
2578
 
2579
        // First of all, if the comment has some itemid, ask to the task what to map
2580
        $mapping = false;
2581
        if ($data->itemid) {
2582
            $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2583
            $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2584
        }
2585
        // Only restore the comment if has no mapping OR we have found the matching mapping
2586
        if (!$mapping || $data->itemid) {
2587
            // Only if user mapping and context
2588
            $data->userid = $this->get_mappingid('user', $data->userid);
2589
            if ($data->userid && $this->task->get_contextid()) {
2590
                $data->contextid = $this->task->get_contextid();
2591
                // Only if there is another comment with same context/user/timecreated
2592
                $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2593
                if (!$DB->record_exists('comments', $params)) {
2594
                    $DB->insert_record('comments', $data);
2595
                }
2596
            }
2597
        }
2598
    }
2599
}
2600
 
2601
/**
2602
 * This structure steps restores the badges and their configs
2603
 */
2604
class restore_badges_structure_step extends restore_structure_step {
2605
 
2606
    /**
2607
     * Conditionally decide if this step should be executed.
2608
     *
2609
     * This function checks the following parameters:
2610
     *
2611
     *   1. Badges and course badges are enabled on the site.
2612
     *   2. The course/badges.xml file exists.
2613
     *   3. All modules are restorable.
2614
     *   4. All modules are marked for restore.
2615
     *
2616
     * @return bool True is safe to execute, false otherwise
2617
     */
2618
    protected function execute_condition() {
2619
        global $CFG;
2620
 
2621
        // First check is badges and course level badges are enabled on this site.
2622
        if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2623
            // Disabled, don't restore course badges.
2624
            return false;
2625
        }
2626
 
2627
        // Check if badges.xml is included in the backup.
2628
        $fullpath = $this->task->get_taskbasepath();
2629
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2630
        if (!file_exists($fullpath)) {
2631
            // Not found, can't restore course badges.
2632
            return false;
2633
        }
2634
 
2635
        // Check we are able to restore all backed up modules.
2636
        if ($this->task->is_missing_modules()) {
2637
            return false;
2638
        }
2639
 
2640
        // Finally check all modules within the backup are being restored.
2641
        if ($this->task->is_excluding_activities()) {
2642
            return false;
2643
        }
2644
 
2645
        return true;
2646
    }
2647
 
2648
    protected function define_structure() {
2649
        $paths = array();
2650
        $paths[] = new restore_path_element('badge', '/badges/badge');
2651
        $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2652
        $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2653
        $paths[] = new restore_path_element('endorsement', '/badges/badge/endorsement');
2654
        $paths[] = new restore_path_element('alignment', '/badges/badge/alignments/alignment');
2655
        $paths[] = new restore_path_element('relatedbadge', '/badges/badge/relatedbadges/relatedbadge');
2656
        $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2657
        $paths[] = new restore_path_element('tag', '/badges/badge/tags/tag');
2658
 
2659
        return $paths;
2660
    }
2661
 
2662
    public function process_badge($data) {
2663
        global $DB, $CFG;
2664
 
2665
        require_once($CFG->libdir . '/badgeslib.php');
2666
 
2667
        $data = (object)$data;
2668
        $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2669
        if (empty($data->usercreated)) {
2670
            $data->usercreated = $this->task->get_userid();
2671
        }
2672
        $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2673
        if (empty($data->usermodified)) {
2674
            $data->usermodified = $this->task->get_userid();
2675
        }
2676
 
2677
        // We'll restore the badge image.
2678
        $restorefiles = true;
2679
 
2680
        $courseid = $this->get_courseid();
2681
 
2682
        $params = array(
2683
                'name'           => $data->name,
2684
                'description'    => $data->description,
2685
                'timecreated'    => $data->timecreated,
2686
                'timemodified'   => $data->timemodified,
2687
                'usercreated'    => $data->usercreated,
2688
                'usermodified'   => $data->usermodified,
2689
                'issuername'     => $data->issuername,
2690
                'issuerurl'      => $data->issuerurl,
2691
                'issuercontact'  => $data->issuercontact,
2692
                'expiredate'     => $this->apply_date_offset($data->expiredate),
2693
                'expireperiod'   => $data->expireperiod,
2694
                'type'           => BADGE_TYPE_COURSE,
2695
                'courseid'       => $courseid,
2696
                'message'        => $data->message,
2697
                'messagesubject' => $data->messagesubject,
2698
                'attachment'     => $data->attachment,
2699
                'notification'   => $data->notification,
2700
                'status'         => BADGE_STATUS_INACTIVE,
2701
                'nextcron'       => $data->nextcron,
2702
                'version'        => $data->version,
2703
                'language'       => $data->language,
2704
                'imageauthorname' => $data->imageauthorname,
2705
                'imageauthoremail' => $data->imageauthoremail,
2706
                'imageauthorurl' => $data->imageauthorurl,
2707
                'imagecaption'   => $data->imagecaption
2708
        );
2709
 
2710
        $newid = $DB->insert_record('badge', $params);
2711
        $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2712
    }
2713
 
2714
    /**
2715
     * Create an endorsement for a badge.
2716
     *
2717
     * @param mixed $data
2718
     * @return void
2719
     */
2720
    public function process_endorsement($data) {
2721
        global $DB;
2722
 
2723
        $data = (object)$data;
2724
 
2725
        $params = [
2726
            'badgeid' => $this->get_new_parentid('badge'),
2727
            'issuername' => $data->issuername,
2728
            'issuerurl' => $data->issuerurl,
2729
            'issueremail' => $data->issueremail,
2730
            'claimid' => $data->claimid,
2731
            'claimcomment' => $data->claimcomment,
2732
            'dateissued' => $this->apply_date_offset($data->dateissued)
2733
        ];
2734
        $newid = $DB->insert_record('badge_endorsement', $params);
2735
        $this->set_mapping('endorsement', $data->id, $newid);
2736
    }
2737
 
2738
    /**
2739
     * Link to related badges for a badge. This relies on post processing in after_execute().
2740
     *
2741
     * @param mixed $data
2742
     * @return void
2743
     */
2744
    public function process_relatedbadge($data) {
2745
        global $DB;
2746
 
2747
        $data = (object)$data;
2748
        $relatedbadgeid = $data->relatedbadgeid;
2749
 
2750
        if ($relatedbadgeid) {
2751
            // Only backup and restore related badges if they are contained in the backup file.
2752
            $params = array(
2753
                    'badgeid'           => $this->get_new_parentid('badge'),
2754
                    'relatedbadgeid'    => $relatedbadgeid
2755
            );
2756
            $newid = $DB->insert_record('badge_related', $params);
2757
        }
2758
    }
2759
 
2760
    /**
2761
     * Link to an alignment for a badge.
2762
     *
2763
     * @param mixed $data
2764
     * @return void
2765
     */
2766
    public function process_alignment($data) {
2767
        global $DB;
2768
 
2769
        $data = (object)$data;
2770
        $params = array(
2771
                'badgeid'           => $this->get_new_parentid('badge'),
2772
                'targetname'        => $data->targetname,
2773
                'targeturl'         => $data->targeturl,
2774
                'targetdescription' => $data->targetdescription,
2775
                'targetframework'   => $data->targetframework,
2776
                'targetcode'        => $data->targetcode
2777
        );
2778
        $newid = $DB->insert_record('badge_alignment', $params);
2779
        $this->set_mapping('alignment', $data->id, $newid);
2780
    }
2781
 
2782
    public function process_criterion($data) {
2783
        global $DB;
2784
 
2785
        $data = (object)$data;
2786
 
2787
        $params = array(
2788
                'badgeid'           => $this->get_new_parentid('badge'),
2789
                'criteriatype'      => $data->criteriatype,
2790
                'method'            => $data->method,
2791
                'description'       => isset($data->description) ? $data->description : '',
2792
                'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0,
2793
        );
2794
 
2795
        $newid = $DB->insert_record('badge_criteria', $params);
2796
        $this->set_mapping('criterion', $data->id, $newid);
2797
    }
2798
 
2799
    public function process_parameter($data) {
2800
        global $DB, $CFG;
2801
 
2802
        require_once($CFG->libdir . '/badgeslib.php');
2803
 
2804
        $data = (object)$data;
2805
        $criteriaid = $this->get_new_parentid('criterion');
2806
 
2807
        // Parameter array that will go to database.
2808
        $params = array();
2809
        $params['critid'] = $criteriaid;
2810
 
2811
        $oldparam = explode('_', $data->name);
2812
 
2813
        if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2814
            $module = $this->get_mappingid('course_module', $oldparam[1]);
2815
            $params['name'] = $oldparam[0] . '_' . $module;
2816
            $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2817
        } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2818
            $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2819
            $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2820
        } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2821
            $role = $this->get_mappingid('role', $data->value);
2822
            if (!empty($role)) {
2823
                $params['name'] = 'role_' . $role;
2824
                $params['value'] = $role;
2825
            } else {
2826
                return;
2827
            }
2828
        } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COMPETENCY) {
2829
            $competencyid = $this->get_mappingid('competency', $data->value);
2830
            if (!empty($competencyid)) {
2831
                $params['name'] = 'competency_' . $competencyid;
2832
                $params['value'] = $competencyid;
2833
            } else {
2834
                return;
2835
            }
2836
        }
2837
 
2838
        if (!$DB->record_exists('badge_criteria_param', $params)) {
2839
            $DB->insert_record('badge_criteria_param', $params);
2840
        }
2841
    }
2842
 
2843
    public function process_manual_award($data) {
2844
        global $DB;
2845
 
2846
        $data = (object)$data;
2847
        $role = $this->get_mappingid('role', $data->issuerrole);
2848
 
2849
        if (!empty($role)) {
2850
            $award = array(
2851
                'badgeid'     => $this->get_new_parentid('badge'),
2852
                'recipientid' => $this->get_mappingid('user', $data->recipientid),
2853
                'issuerid'    => $this->get_mappingid('user', $data->issuerid),
2854
                'issuerrole'  => $role,
2855
                'datemet'     => $this->apply_date_offset($data->datemet)
2856
            );
2857
 
2858
            // Skip the manual award if recipient or issuer can not be mapped to.
2859
            if (empty($award['recipientid']) || empty($award['issuerid'])) {
2860
                return;
2861
            }
2862
 
2863
            $DB->insert_record('badge_manual_award', $award);
2864
        }
2865
    }
2866
 
2867
    /**
2868
     * Process tag.
2869
     *
2870
     * @param array $data The data.
2871
     * @throws base_step_exception
2872
     */
2873
    public function process_tag(array $data): void {
2874
        $data = (object)$data;
2875
        $badgeid = $this->get_new_parentid('badge');
2876
 
2877
        if (!empty($data->rawname)) {
2878
            core_tag_tag::add_item_tag('core_badges', 'badge', $badgeid,
2879
                context_course::instance($this->get_courseid()), $data->rawname);
2880
        }
2881
    }
2882
 
2883
    protected function after_execute() {
2884
        global $DB;
2885
        // Add related files.
2886
        $this->add_related_files('badges', 'badgeimage', 'badge');
2887
 
2888
        $badgeid = $this->get_new_parentid('badge');
2889
        // Remap any related badges.
2890
        // We do this in the DB directly because this is backup/restore it is not valid to call into
2891
        // the component API.
2892
        $params = array('badgeid' => $badgeid);
2893
        $query = "SELECT DISTINCT br.id, br.badgeid, br.relatedbadgeid
2894
                    FROM {badge_related} br
2895
                   WHERE (br.badgeid = :badgeid)";
2896
        $relatedbadges = $DB->get_records_sql($query, $params);
2897
        $newrelatedids = [];
2898
        foreach ($relatedbadges as $relatedbadge) {
2899
            $relatedid = $this->get_mappingid('badge', $relatedbadge->relatedbadgeid);
2900
            $params['relatedbadgeid'] = $relatedbadge->relatedbadgeid;
2901
            $DB->delete_records_select('badge_related', '(badgeid = :badgeid AND relatedbadgeid = :relatedbadgeid)', $params);
2902
            if ($relatedid) {
2903
                $newrelatedids[] = $relatedid;
2904
            }
2905
        }
2906
        if (!empty($newrelatedids)) {
2907
            $relatedbadges = [];
2908
            foreach ($newrelatedids as $relatedid) {
2909
                $relatedbadge = new stdClass();
2910
                $relatedbadge->badgeid = $badgeid;
2911
                $relatedbadge->relatedbadgeid = $relatedid;
2912
                $relatedbadges[] = $relatedbadge;
2913
            }
2914
            $DB->insert_records('badge_related', $relatedbadges);
2915
        }
2916
    }
2917
}
2918
 
2919
/**
2920
 * This structure steps restores the calendar events
2921
 */
2922
class restore_calendarevents_structure_step extends restore_structure_step {
2923
 
2924
    protected function define_structure() {
2925
 
2926
        $paths = array();
2927
 
2928
        $paths[] = new restore_path_element('calendarevents', '/events/event');
2929
 
2930
        return $paths;
2931
    }
2932
 
2933
    public function process_calendarevents($data) {
2934
        global $DB, $SITE, $USER;
2935
 
2936
        $data = (object)$data;
2937
        $oldid = $data->id;
2938
        $restorefiles = true; // We'll restore the files
2939
 
2940
        // If this is a new action event, it will automatically be populated by the adhoc task.
2941
        // Nothing to do here.
2942
        if (isset($data->type) && $data->type == CALENDAR_EVENT_TYPE_ACTION) {
2943
            return;
2944
        }
2945
 
2946
        // User overrides for activities are identified by having a courseid of zero with
2947
        // both a modulename and instance value set.
2948
        $isuseroverride = !$data->courseid && $data->modulename && $data->instance;
2949
 
2950
        // If we don't want to include user data and this record is a user override event
2951
        // for an activity then we should not create it. (Only activity events can be user override events - which must have this
2952
        // setting).
2953
        if ($isuseroverride && $this->task->setting_exists('userinfo') && !$this->task->get_setting_value('userinfo')) {
2954
            return;
2955
        }
2956
 
2957
        // Find the userid and the groupid associated with the event.
2958
        $data->userid = $this->get_mappingid('user', $data->userid);
2959
        if ($data->userid === false) {
2960
            // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2961
            // Use the current user ID for these events.
2962
            $data->userid = $USER->id;
2963
        }
2964
        if (!empty($data->groupid)) {
2965
            $data->groupid = $this->get_mappingid('group', $data->groupid);
2966
            if ($data->groupid === false) {
2967
                return;
2968
            }
2969
        }
2970
        // Handle events with empty eventtype //MDL-32827
2971
        if(empty($data->eventtype)) {
2972
            if ($data->courseid == $SITE->id) {                                // Site event
2973
                $data->eventtype = "site";
2974
            } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2975
                // Course assingment event
2976
                $data->eventtype = "due";
2977
            } else if ($data->courseid != 0 && $data->groupid == 0) {      // Course event
2978
                $data->eventtype = "course";
2979
            } else if ($data->groupid) {                                      // Group event
2980
                $data->eventtype = "group";
2981
            } else if ($data->userid) {                                       // User event
2982
                $data->eventtype = "user";
2983
            } else {
2984
                return;
2985
            }
2986
        }
2987
 
2988
        $params = array(
2989
                'name'           => $data->name,
2990
                'description'    => $data->description,
2991
                'format'         => $data->format,
2992
                // User overrides in activities use a course id of zero. All other event types
2993
                // must use the mapped course id.
2994
                'courseid'       => $data->courseid ? $this->get_courseid() : 0,
2995
                'groupid'        => $data->groupid,
2996
                'userid'         => $data->userid,
2997
                'repeatid'       => $this->get_mappingid('event', $data->repeatid),
2998
                'modulename'     => $data->modulename,
2999
                'type'           => isset($data->type) ? $data->type : 0,
3000
                'eventtype'      => $data->eventtype,
3001
                'timestart'      => $this->apply_date_offset($data->timestart),
3002
                'timeduration'   => $data->timeduration,
3003
                'timesort'       => isset($data->timesort) ? $this->apply_date_offset($data->timesort) : null,
3004
                'visible'        => $data->visible,
3005
                'uuid'           => $data->uuid,
3006
                'sequence'       => $data->sequence,
3007
                'timemodified'   => $data->timemodified,
3008
                'priority'       => isset($data->priority) ? $data->priority : null,
3009
                'location'       => isset($data->location) ? $data->location : null);
3010
        if ($this->name == 'activity_calendar') {
3011
            $params['instance'] = $this->task->get_activityid();
3012
        } else {
3013
            $params['instance'] = 0;
3014
        }
3015
        $sql = "SELECT id
3016
                  FROM {event}
3017
                 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
3018
                   AND courseid = ?
3019
                   AND modulename = ?
3020
                   AND instance = ?
3021
                   AND timestart = ?
3022
                   AND timeduration = ?
3023
                   AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
3024
        $arg = array ($params['name'], $params['courseid'], $params['modulename'], $params['instance'], $params['timestart'], $params['timeduration'], $params['description']);
3025
        $result = $DB->record_exists_sql($sql, $arg);
3026
        if (empty($result)) {
3027
            $newitemid = $DB->insert_record('event', $params);
3028
            $this->set_mapping('event', $oldid, $newitemid);
3029
            $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
3030
        }
3031
        // With repeating events, each event has the repeatid pointed at the first occurrence.
3032
        // Since the repeatid will be empty when the first occurrence is restored,
3033
        // Get the repeatid from the second occurrence of the repeating event and use that to update the first occurrence.
3034
        // Then keep a list of repeatids so we only perform this update once.
3035
        static $repeatids = array();
3036
        if (!empty($params['repeatid']) && !in_array($params['repeatid'], $repeatids)) {
3037
            // This entry is repeated so the repeatid field must be set.
3038
            $DB->set_field('event', 'repeatid', $params['repeatid'], array('id' => $params['repeatid']));
3039
            $repeatids[] = $params['repeatid'];
3040
        }
3041
 
3042
    }
3043
    protected function after_execute() {
3044
        // Add related files
3045
        $this->add_related_files('calendar', 'event_description', 'event_description');
3046
    }
3047
}
3048
 
3049
class restore_course_completion_structure_step extends restore_structure_step {
3050
 
3051
    /**
3052
     * Conditionally decide if this step should be executed.
3053
     *
3054
     * This function checks parameters that are not immediate settings to ensure
3055
     * that the enviroment is suitable for the restore of course completion info.
3056
     *
3057
     * This function checks the following four parameters:
3058
     *
3059
     *   1. Course completion is enabled on the site
3060
     *   2. The backup includes course completion information
3061
     *   3. All modules are restorable
3062
     *   4. All modules are marked for restore.
3063
     *   5. No completion criteria already exist for the course.
3064
     *
3065
     * @return bool True is safe to execute, false otherwise
3066
     */
3067
    protected function execute_condition() {
3068
        global $CFG, $DB;
3069
 
3070
        // First check course completion is enabled on this site
3071
        if (empty($CFG->enablecompletion)) {
3072
            // Disabled, don't restore course completion
3073
            return false;
3074
        }
3075
 
3076
        // No course completion on the front page.
3077
        if ($this->get_courseid() == SITEID) {
3078
            return false;
3079
        }
3080
 
3081
        // Check it is included in the backup
3082
        $fullpath = $this->task->get_taskbasepath();
3083
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3084
        if (!file_exists($fullpath)) {
3085
            // Not found, can't restore course completion
3086
            return false;
3087
        }
3088
 
3089
        // Check we are able to restore all backed up modules
3090
        if ($this->task->is_missing_modules()) {
3091
            return false;
3092
        }
3093
 
3094
        // Check all modules within the backup are being restored.
3095
        if ($this->task->is_excluding_activities()) {
3096
            return false;
3097
        }
3098
 
3099
        // Check that no completion criteria is already set for the course.
3100
        if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
3101
            return false;
3102
        }
3103
 
3104
        return true;
3105
    }
3106
 
3107
    /**
3108
     * Define the course completion structure
3109
     *
3110
     * @return array Array of restore_path_element
3111
     */
3112
    protected function define_structure() {
3113
 
3114
        // To know if we are including user completion info
3115
        $userinfo = $this->get_setting_value('userscompletion');
3116
 
3117
        $paths = array();
3118
        $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
3119
        $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
3120
 
3121
        if ($userinfo) {
3122
            $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
3123
            $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
3124
        }
3125
 
3126
        return $paths;
3127
 
3128
    }
3129
 
3130
    /**
3131
     * Process course completion criteria
3132
     *
3133
     * @global moodle_database $DB
3134
     * @param stdClass $data
3135
     */
3136
    public function process_course_completion_criteria($data) {
3137
        global $DB;
3138
 
3139
        $data = (object)$data;
3140
        $data->course = $this->get_courseid();
3141
 
3142
        // Apply the date offset to the time end field
3143
        $data->timeend = $this->apply_date_offset($data->timeend);
3144
 
3145
        // Map the role from the criteria
3146
        if (isset($data->role) && $data->role != '') {
3147
            // Newer backups should include roleshortname, which makes this much easier.
3148
            if (!empty($data->roleshortname)) {
3149
                $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
3150
                if (!$roleinstanceid) {
3151
                    $this->log(
3152
                        'Could not match the role shortname in course_completion_criteria, so skipping',
3153
                        backup::LOG_DEBUG
3154
                    );
3155
                    return;
3156
                }
3157
                $data->role = $roleinstanceid;
3158
            } else {
3159
                $data->role = $this->get_mappingid('role', $data->role);
3160
            }
3161
 
3162
            // Check we have an id, otherwise it causes all sorts of bugs.
3163
            if (!$data->role) {
3164
                $this->log(
3165
                    'Could not match role in course_completion_criteria, so skipping',
3166
                    backup::LOG_DEBUG
3167
                );
3168
                return;
3169
            }
3170
        }
3171
 
3172
        // If the completion criteria is for a module we need to map the module instance
3173
        // to the new module id.
3174
        if (!empty($data->moduleinstance) && !empty($data->module)) {
3175
            $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
3176
            if (empty($data->moduleinstance)) {
3177
                $this->log(
3178
                    'Could not match the module instance in course_completion_criteria, so skipping',
3179
                    backup::LOG_DEBUG
3180
                );
3181
                return;
3182
            }
3183
        } else {
3184
            $data->module = null;
3185
            $data->moduleinstance = null;
3186
        }
3187
 
3188
        // We backup the course shortname rather than the ID so that we can match back to the course
3189
        if (!empty($data->courseinstanceshortname)) {
3190
            $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
3191
            if (!$courseinstanceid) {
3192
                $this->log(
3193
                    'Could not match the course instance in course_completion_criteria, so skipping',
3194
                    backup::LOG_DEBUG
3195
                );
3196
                return;
3197
            }
3198
        } else {
3199
            $courseinstanceid = null;
3200
        }
3201
        $data->courseinstance = $courseinstanceid;
3202
 
3203
        $params = array(
3204
            'course'         => $data->course,
3205
            'criteriatype'   => $data->criteriatype,
3206
            'enrolperiod'    => $data->enrolperiod,
3207
            'courseinstance' => $data->courseinstance,
3208
            'module'         => $data->module,
3209
            'moduleinstance' => $data->moduleinstance,
3210
            'timeend'        => $data->timeend,
3211
            'gradepass'      => $data->gradepass,
3212
            'role'           => $data->role
3213
        );
3214
        $newid = $DB->insert_record('course_completion_criteria', $params);
3215
        $this->set_mapping('course_completion_criteria', $data->id, $newid);
3216
    }
3217
 
3218
    /**
3219
     * Processes course compltion criteria complete records
3220
     *
3221
     * @global moodle_database $DB
3222
     * @param stdClass $data
3223
     */
3224
    public function process_course_completion_crit_compl($data) {
3225
        global $DB;
3226
 
3227
        $data = (object)$data;
3228
 
3229
        // This may be empty if criteria could not be restored
3230
        $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
3231
 
3232
        $data->course = $this->get_courseid();
3233
        $data->userid = $this->get_mappingid('user', $data->userid);
3234
 
3235
        if (!empty($data->criteriaid) && !empty($data->userid)) {
3236
            $params = array(
3237
                'userid' => $data->userid,
3238
                'course' => $data->course,
3239
                'criteriaid' => $data->criteriaid,
3240
                'timecompleted' => $data->timecompleted
3241
            );
3242
            if (isset($data->gradefinal)) {
3243
                $params['gradefinal'] = $data->gradefinal;
3244
            }
3245
            if (isset($data->unenroled)) {
3246
                $params['unenroled'] = $data->unenroled;
3247
            }
3248
            $DB->insert_record('course_completion_crit_compl', $params);
3249
        }
3250
    }
3251
 
3252
    /**
3253
     * Process course completions
3254
     *
3255
     * @global moodle_database $DB
3256
     * @param stdClass $data
3257
     */
3258
    public function process_course_completions($data) {
3259
        global $DB;
3260
 
3261
        $data = (object)$data;
3262
 
3263
        $data->course = $this->get_courseid();
3264
        $data->userid = $this->get_mappingid('user', $data->userid);
3265
 
3266
        if (!empty($data->userid)) {
3267
            $params = array(
3268
                'userid' => $data->userid,
3269
                'course' => $data->course,
3270
                'timeenrolled' => $data->timeenrolled,
3271
                'timestarted' => $data->timestarted,
3272
                'timecompleted' => $data->timecompleted,
3273
                'reaggregate' => $data->reaggregate
3274
            );
3275
 
3276
            $existing = $DB->get_record('course_completions', array(
3277
                'userid' => $data->userid,
3278
                'course' => $data->course
3279
            ));
3280
 
3281
            // MDL-46651 - If cron writes out a new record before we get to it
3282
            // then we should replace it with the Truth data from the backup.
3283
            // This may be obsolete after MDL-48518 is resolved
3284
            if ($existing) {
3285
                $params['id'] = $existing->id;
3286
                $DB->update_record('course_completions', $params);
3287
            } else {
3288
                $DB->insert_record('course_completions', $params);
3289
            }
3290
        }
3291
    }
3292
 
3293
    /**
3294
     * Process course completion aggregate methods
3295
     *
3296
     * @global moodle_database $DB
3297
     * @param stdClass $data
3298
     */
3299
    public function process_course_completion_aggr_methd($data) {
3300
        global $DB;
3301
 
3302
        $data = (object)$data;
3303
 
3304
        $data->course = $this->get_courseid();
3305
 
3306
        // Only create the course_completion_aggr_methd records if
3307
        // the target course has not them defined. MDL-28180
3308
        if (!$DB->record_exists('course_completion_aggr_methd', array(
3309
                    'course' => $data->course,
3310
                    'criteriatype' => $data->criteriatype))) {
3311
            $params = array(
3312
                'course' => $data->course,
3313
                'criteriatype' => $data->criteriatype,
3314
                'method' => $data->method,
3315
                'value' => $data->value,
3316
            );
3317
            $DB->insert_record('course_completion_aggr_methd', $params);
3318
        }
3319
    }
3320
}
3321
 
3322
 
3323
/**
3324
 * This structure step restores course logs (cmid = 0), delegating
3325
 * the hard work to the corresponding {@link restore_logs_processor} passing the
3326
 * collection of {@link restore_log_rule} rules to be observed as they are defined
3327
 * by the task. Note this is only executed based in the 'logs' setting.
3328
 *
3329
 * NOTE: This is executed by final task, to have all the activities already restored
3330
 *
3331
 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
3332
 * records are. There are others like 'calendar' and 'upload' that will be handled
3333
 * later.
3334
 *
3335
 * NOTE: All the missing actions (not able to be restored) are sent to logs for
3336
 * debugging purposes
3337
 */
3338
class restore_course_logs_structure_step extends restore_structure_step {
3339
 
3340
    /**
3341
     * Conditionally decide if this step should be executed.
3342
     *
3343
     * This function checks the following parameter:
3344
     *
3345
     *   1. the course/logs.xml file exists
3346
     *
3347
     * @return bool true is safe to execute, false otherwise
3348
     */
3349
    protected function execute_condition() {
3350
 
3351
        // Check it is included in the backup
3352
        $fullpath = $this->task->get_taskbasepath();
3353
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3354
        if (!file_exists($fullpath)) {
3355
            // Not found, can't restore course logs
3356
            return false;
3357
        }
3358
 
3359
        return true;
3360
    }
3361
 
3362
    protected function define_structure() {
3363
 
3364
        $paths = array();
3365
 
3366
        // Simple, one plain level of information contains them
3367
        $paths[] = new restore_path_element('log', '/logs/log');
3368
 
3369
        return $paths;
3370
    }
3371
 
3372
    protected function process_log($data) {
3373
        global $DB;
3374
 
3375
        $data = (object)($data);
3376
 
3377
        // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3378
 
3379
        $data->userid = $this->get_mappingid('user', $data->userid);
3380
        $data->course = $this->get_courseid();
3381
        $data->cmid = 0;
3382
 
3383
        // For any reason user wasn't remapped ok, stop processing this
3384
        if (empty($data->userid)) {
3385
            return;
3386
        }
3387
 
3388
        // Everything ready, let's delegate to the restore_logs_processor
3389
 
3390
        // Set some fixed values that will save tons of DB requests
3391
        $values = array(
3392
            'course' => $this->get_courseid());
3393
        // Get instance and process log record
3394
        $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3395
 
3396
        // If we have data, insert it, else something went wrong in the restore_logs_processor
3397
        if ($data) {
3398
            if (empty($data->url)) {
3399
                $data->url = '';
3400
            }
3401
            if (empty($data->info)) {
3402
                $data->info = '';
3403
            }
3404
            // Store the data in the legacy log table if we are still using it.
3405
            $manager = get_log_manager();
3406
            if (method_exists($manager, 'legacy_add_to_log')) {
3407
                $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3408
                    $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3409
            }
3410
        }
3411
    }
3412
}
3413
 
3414
/**
3415
 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
3416
 * sharing its same structure but modifying the way records are handled
3417
 */
3418
class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
3419
 
3420
    protected function process_log($data) {
3421
        global $DB;
3422
 
3423
        $data = (object)($data);
3424
 
3425
        // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3426
 
3427
        $data->userid = $this->get_mappingid('user', $data->userid);
3428
        $data->course = $this->get_courseid();
3429
        $data->cmid = $this->task->get_moduleid();
3430
 
3431
        // For any reason user wasn't remapped ok, stop processing this
3432
        if (empty($data->userid)) {
3433
            return;
3434
        }
3435
 
3436
        // Everything ready, let's delegate to the restore_logs_processor
3437
 
3438
        // Set some fixed values that will save tons of DB requests
3439
        $values = array(
3440
            'course' => $this->get_courseid(),
3441
            'course_module' => $this->task->get_moduleid(),
3442
            $this->task->get_modulename() => $this->task->get_activityid());
3443
        // Get instance and process log record
3444
        $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3445
 
3446
        // If we have data, insert it, else something went wrong in the restore_logs_processor
3447
        if ($data) {
3448
            if (empty($data->url)) {
3449
                $data->url = '';
3450
            }
3451
            if (empty($data->info)) {
3452
                $data->info = '';
3453
            }
3454
            // Store the data in the legacy log table if we are still using it.
3455
            $manager = get_log_manager();
3456
            if (method_exists($manager, 'legacy_add_to_log')) {
3457
                $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3458
                    $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3459
            }
3460
        }
3461
    }
3462
}
3463
 
3464
/**
3465
 * Structure step in charge of restoring the logstores.xml file for the course logs.
3466
 *
3467
 * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3468
 * it, for logs belonging to the course level.
3469
 */
3470
class restore_course_logstores_structure_step extends restore_structure_step {
3471
 
3472
    /**
3473
     * Conditionally decide if this step should be executed.
3474
     *
3475
     * This function checks the following parameter:
3476
     *
3477
     *   1. the logstores.xml file exists
3478
     *
3479
     * @return bool true is safe to execute, false otherwise
3480
     */
3481
    protected function execute_condition() {
3482
 
3483
        // Check it is included in the backup.
3484
        $fullpath = $this->task->get_taskbasepath();
3485
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3486
        if (!file_exists($fullpath)) {
3487
            // Not found, can't restore logstores.xml information.
3488
            return false;
3489
        }
3490
 
3491
        return true;
3492
    }
3493
 
3494
    /**
3495
     * Return the elements to be processed on restore of logstores.
3496
     *
3497
     * @return restore_path_element[] array of elements to be processed on restore.
3498
     */
3499
    protected function define_structure() {
3500
 
3501
        $paths = array();
3502
 
3503
        $logstore = new restore_path_element('logstore', '/logstores/logstore');
3504
        $paths[] = $logstore;
3505
 
3506
        // Add logstore subplugin support to the 'logstore' element.
3507
        $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3508
 
3509
        return array($logstore);
3510
    }
3511
 
3512
    /**
3513
     * Process the 'logstore' element,
3514
     *
3515
     * Note: This is empty by definition in backup, because stores do not share any
3516
     * data between them, so there is nothing to process here.
3517
     *
3518
     * @param array $data element data
3519
     */
3520
    protected function process_logstore($data) {
3521
        return;
3522
    }
3523
}
3524
 
3525
/**
3526
 * Structure step in charge of restoring the loglastaccess.xml file for the course logs.
3527
 *
3528
 * This restore step will rebuild the table for user_lastaccess table.
3529
 */
3530
class restore_course_loglastaccess_structure_step extends restore_structure_step {
3531
 
3532
    /**
3533
     * Conditionally decide if this step should be executed.
3534
     *
3535
     * This function checks the following parameter:
3536
     *
3537
     *   1. the loglastaccess.xml file exists
3538
     *
3539
     * @return bool true is safe to execute, false otherwise
3540
     */
3541
    protected function execute_condition() {
3542
        // Check it is included in the backup.
3543
        $fullpath = $this->task->get_taskbasepath();
3544
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3545
        if (!file_exists($fullpath)) {
3546
            // Not found, can't restore loglastaccess.xml information.
3547
            return false;
3548
        }
3549
 
3550
        return true;
3551
    }
3552
 
3553
    /**
3554
     * Return the elements to be processed on restore of loglastaccess.
3555
     *
3556
     * @return restore_path_element[] array of elements to be processed on restore.
3557
     */
3558
    protected function define_structure() {
3559
 
3560
        $paths = array();
3561
        // To know if we are including userinfo.
3562
        $userinfo = $this->get_setting_value('users');
3563
 
3564
        if ($userinfo) {
3565
            $paths[] = new restore_path_element('lastaccess', '/lastaccesses/lastaccess');
3566
        }
3567
        // Return the paths wrapped.
3568
        return $paths;
3569
    }
3570
 
3571
    /**
3572
     * Process the 'lastaccess' elements.
3573
     *
3574
     * @param array $data element data
3575
     */
3576
    protected function process_lastaccess($data) {
3577
        global $DB;
3578
 
3579
        $data = (object)$data;
3580
 
3581
        $data->courseid = $this->get_courseid();
3582
        if (!$data->userid = $this->get_mappingid('user', $data->userid)) {
3583
            return; // Nothing to do, not able to find the user to set the lastaccess time.
3584
        }
3585
 
3586
        // Check if record does exist.
3587
        $exists = $DB->get_record('user_lastaccess', array('courseid' => $data->courseid, 'userid' => $data->userid));
3588
        if ($exists) {
3589
            // If the time of last access of the restore is newer, then replace and update.
3590
            if ($exists->timeaccess < $data->timeaccess) {
3591
                $exists->timeaccess = $data->timeaccess;
3592
                $DB->update_record('user_lastaccess', $exists);
3593
            }
3594
        } else {
3595
            $DB->insert_record('user_lastaccess', $data);
3596
        }
3597
    }
3598
}
3599
 
3600
/**
3601
 * Structure step in charge of restoring the logstores.xml file for the activity logs.
3602
 *
3603
 * Note: Activity structure is completely equivalent to the course one, so just extend it.
3604
 */
3605
class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3606
}
3607
 
3608
/**
3609
 * Restore course competencies structure step.
3610
 */
3611
class restore_course_competencies_structure_step extends restore_structure_step {
3612
 
3613
    /**
3614
     * Returns the structure.
3615
     *
3616
     * @return array
3617
     */
3618
    protected function define_structure() {
3619
        $userinfo = $this->get_setting_value('users');
3620
        $paths = array(
3621
            new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3622
            new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3623
        );
3624
        if ($userinfo) {
3625
            $paths[] = new restore_path_element('user_competency_course',
3626
                '/course_competencies/user_competencies/user_competency');
3627
        }
3628
        return $paths;
3629
    }
3630
 
3631
    /**
3632
     * Process a course competency settings.
3633
     *
3634
     * @param array $data The data.
3635
     */
3636
    public function process_course_competency_settings($data) {
3637
        global $DB;
3638
        $data = (object) $data;
3639
 
3640
        // We do not restore the course settings during merge.
3641
        $target = $this->get_task()->get_target();
3642
        if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) {
3643
            return;
3644
        }
3645
 
3646
        $courseid = $this->task->get_courseid();
3647
        $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3648
            array('courseid' => $courseid));
3649
 
3650
        // Strangely the course settings already exist, let's just leave them as is then.
3651
        if ($exists) {
3652
            $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING);
3653
            return;
3654
        }
3655
 
3656
        $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3657
        $settings = new \core_competency\course_competency_settings(0, $data);
3658
        $settings->create();
3659
    }
3660
 
3661
    /**
3662
     * Process a course competency.
3663
     *
3664
     * @param array $data The data.
3665
     */
3666
    public function process_course_competency($data) {
3667
        $data = (object) $data;
3668
 
3669
        // Mapping the competency by ID numbers.
3670
        $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3671
        if (!$framework) {
3672
            return;
3673
        }
3674
        $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3675
            'competencyframeworkid' => $framework->get('id')));
3676
        if (!$competency) {
3677
            return;
3678
        }
3679
        $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get('id'));
3680
 
3681
        $params = array(
3682
            'competencyid' => $competency->get('id'),
3683
            'courseid' => $this->task->get_courseid()
3684
        );
3685
        $query = 'competencyid = :competencyid AND courseid = :courseid';
3686
        $existing = \core_competency\course_competency::record_exists_select($query, $params);
3687
 
3688
        if (!$existing) {
3689
            // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3690
            $record = (object) $params;
3691
            $record->ruleoutcome = $data->ruleoutcome;
3692
            $coursecompetency = new \core_competency\course_competency(0, $record);
3693
            $coursecompetency->create();
3694
        }
3695
    }
3696
 
3697
    /**
3698
     * Process the user competency course.
3699
     *
3700
     * @param array $data The data.
3701
     */
3702
    public function process_user_competency_course($data) {
3703
        global $USER, $DB;
3704
        $data = (object) $data;
3705
 
3706
        $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid);
3707
        if (!$data->competencyid) {
3708
            // This is strange, the competency does not belong to the course.
3709
            return;
3710
        } else if ($data->grade === null) {
3711
            // We do not need to do anything when there is no grade.
3712
            return;
3713
        }
3714
 
3715
        $data->userid = $this->get_mappingid('user', $data->userid);
3716
        $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
3717
 
3718
        // The method add_evidence also sets the course rating.
3719
        \core_competency\api::add_evidence($data->userid,
3720
                                           $data->competencyid,
3721
                                           $this->task->get_contextid(),
3722
                                           \core_competency\evidence::ACTION_OVERRIDE,
3723
                                           'evidence_courserestored',
3724
                                           'core_competency',
3725
                                           $shortname,
3726
                                           false,
3727
                                           null,
3728
                                           $data->grade,
3729
                                           $USER->id);
3730
    }
3731
 
3732
    /**
3733
     * Execute conditions.
3734
     *
3735
     * @return bool
3736
     */
3737
    protected function execute_condition() {
3738
 
3739
        // Do not execute if competencies are not included.
3740
        if (!$this->get_setting_value('competencies')) {
3741
            return false;
3742
        }
3743
 
3744
        // Do not execute if the competencies XML file is not found.
3745
        $fullpath = $this->task->get_taskbasepath();
3746
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3747
        if (!file_exists($fullpath)) {
3748
            return false;
3749
        }
3750
 
3751
        return true;
3752
    }
3753
}
3754
 
3755
/**
3756
 * Restore activity competencies structure step.
3757
 */
3758
class restore_activity_competencies_structure_step extends restore_structure_step {
3759
 
3760
    /**
3761
     * Defines the structure.
3762
     *
3763
     * @return array
3764
     */
3765
    protected function define_structure() {
3766
        $paths = array(
3767
            new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3768
        );
3769
        return $paths;
3770
    }
3771
 
3772
    /**
3773
     * Process a course module competency.
3774
     *
3775
     * @param array $data The data.
3776
     */
3777
    public function process_course_module_competency($data) {
3778
        $data = (object) $data;
3779
 
3780
        // Mapping the competency by ID numbers.
3781
        $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3782
        if (!$framework) {
3783
            return;
3784
        }
3785
        $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3786
            'competencyframeworkid' => $framework->get('id')));
3787
        if (!$competency) {
3788
            return;
3789
        }
3790
 
3791
        $params = array(
3792
            'competencyid' => $competency->get('id'),
3793
            'cmid' => $this->task->get_moduleid()
3794
        );
3795
        $query = 'competencyid = :competencyid AND cmid = :cmid';
3796
        $existing = \core_competency\course_module_competency::record_exists_select($query, $params);
3797
 
3798
        if (!$existing) {
3799
            // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3800
            $record = (object) $params;
3801
            $record->ruleoutcome = $data->ruleoutcome;
3802
            $record->overridegrade = $data->overridegrade ?? 0;
3803
            $coursemodulecompetency = new \core_competency\course_module_competency(0, $record);
3804
            $coursemodulecompetency->create();
3805
        }
3806
    }
3807
 
3808
    /**
3809
     * Execute conditions.
3810
     *
3811
     * @return bool
3812
     */
3813
    protected function execute_condition() {
3814
 
3815
        // Do not execute if competencies are not included.
3816
        if (!$this->get_setting_value('competencies')) {
3817
            return false;
3818
        }
3819
 
3820
        // Do not execute if the competencies XML file is not found.
3821
        $fullpath = $this->task->get_taskbasepath();
3822
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3823
        if (!file_exists($fullpath)) {
3824
            return false;
3825
        }
3826
 
3827
        return true;
3828
    }
3829
}
3830
 
3831
/**
3832
 * Defines the restore step for advanced grading methods attached to the activity module
3833
 */
3834
class restore_activity_grading_structure_step extends restore_structure_step {
3835
 
3836
    /**
3837
     * This step is executed only if the grading file is present
3838
     */
3839
     protected function execute_condition() {
3840
 
3841
        if ($this->get_courseid() == SITEID) {
3842
            return false;
3843
        }
3844
 
3845
        $fullpath = $this->task->get_taskbasepath();
3846
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3847
        if (!file_exists($fullpath)) {
3848
            return false;
3849
        }
3850
 
3851
        return true;
3852
    }
3853
 
3854
 
3855
    /**
3856
     * Declares paths in the grading.xml file we are interested in
3857
     */
3858
    protected function define_structure() {
3859
 
3860
        $paths = array();
3861
        $userinfo = $this->get_setting_value('userinfo');
3862
 
3863
        $area = new restore_path_element('grading_area', '/areas/area');
3864
        $paths[] = $area;
3865
        // attach local plugin stucture to $area element
3866
        $this->add_plugin_structure('local', $area);
3867
 
3868
        $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
3869
        $paths[] = $definition;
3870
        $this->add_plugin_structure('gradingform', $definition);
3871
        // attach local plugin stucture to $definition element
3872
        $this->add_plugin_structure('local', $definition);
3873
 
3874
 
3875
        if ($userinfo) {
3876
            $instance = new restore_path_element('grading_instance',
3877
                '/areas/area/definitions/definition/instances/instance');
3878
            $paths[] = $instance;
3879
            $this->add_plugin_structure('gradingform', $instance);
3880
            // attach local plugin stucture to $intance element
3881
            $this->add_plugin_structure('local', $instance);
3882
        }
3883
 
3884
        return $paths;
3885
    }
3886
 
3887
    /**
3888
     * Processes one grading area element
3889
     *
3890
     * @param array $data element data
3891
     */
3892
    protected function process_grading_area($data) {
3893
        global $DB;
3894
 
3895
        $task = $this->get_task();
3896
        $data = (object)$data;
3897
        $oldid = $data->id;
3898
        $data->component = 'mod_'.$task->get_modulename();
3899
        $data->contextid = $task->get_contextid();
3900
 
3901
        $newid = $DB->insert_record('grading_areas', $data);
3902
        $this->set_mapping('grading_area', $oldid, $newid);
3903
    }
3904
 
3905
    /**
3906
     * Processes one grading definition element
3907
     *
3908
     * @param array $data element data
3909
     */
3910
    protected function process_grading_definition($data) {
3911
        global $DB;
3912
 
3913
        $task = $this->get_task();
3914
        $data = (object)$data;
3915
        $oldid = $data->id;
3916
        $data->areaid = $this->get_new_parentid('grading_area');
3917
        $data->copiedfromid = null;
3918
        $data->timecreated = time();
3919
        $data->usercreated = $task->get_userid();
3920
        $data->timemodified = $data->timecreated;
3921
        $data->usermodified = $data->usercreated;
3922
 
3923
        $newid = $DB->insert_record('grading_definitions', $data);
3924
        $this->set_mapping('grading_definition', $oldid, $newid, true);
3925
    }
3926
 
3927
    /**
3928
     * Processes one grading form instance element
3929
     *
3930
     * @param array $data element data
3931
     */
3932
    protected function process_grading_instance($data) {
3933
        global $DB;
3934
 
3935
        $data = (object)$data;
3936
 
3937
        // new form definition id
3938
        $newformid = $this->get_new_parentid('grading_definition');
3939
 
3940
        // get the name of the area we are restoring to
3941
        $sql = "SELECT ga.areaname
3942
                  FROM {grading_definitions} gd
3943
                  JOIN {grading_areas} ga ON gd.areaid = ga.id
3944
                 WHERE gd.id = ?";
3945
        $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
3946
 
3947
        // get the mapped itemid - the activity module is expected to define the mappings
3948
        // for each gradable area
3949
        $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
3950
 
3951
        $oldid = $data->id;
3952
        $data->definitionid = $newformid;
3953
        $data->raterid = $this->get_mappingid('user', $data->raterid);
3954
        $data->itemid = $newitemid;
3955
 
3956
        $newid = $DB->insert_record('grading_instances', $data);
3957
        $this->set_mapping('grading_instance', $oldid, $newid);
3958
    }
3959
 
3960
    /**
3961
     * Final operations when the database records are inserted
3962
     */
3963
    protected function after_execute() {
3964
        // Add files embedded into the definition description
3965
        $this->add_related_files('grading', 'description', 'grading_definition');
3966
    }
3967
}
3968
 
3969
 
3970
/**
3971
 * This structure step restores the grade items associated with one activity
3972
 * All the grade items are made child of the "course" grade item but the original
3973
 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3974
 * the complete gradebook (categories and calculations), that information is
3975
 * available there
3976
 */
3977
class restore_activity_grades_structure_step extends restore_structure_step {
3978
 
3979
    /**
3980
     * No grades in front page.
3981
     * @return bool
3982
     */
3983
    protected function execute_condition() {
3984
        return ($this->get_courseid() != SITEID);
3985
    }
3986
 
3987
    protected function define_structure() {
3988
 
3989
        $paths = array();
3990
        $userinfo = $this->get_setting_value('userinfo');
3991
 
3992
        $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3993
        $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3994
        if ($userinfo) {
3995
            $paths[] = new restore_path_element('grade_grade',
3996
                           '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
3997
        }
3998
        return $paths;
3999
    }
4000
 
4001
    protected function process_grade_item($data) {
4002
        global $DB;
4003
 
4004
        $data = (object)($data);
4005
        $oldid       = $data->id;        // We'll need these later
4006
        $oldparentid = $data->categoryid;
4007
        $courseid = $this->get_courseid();
4008
 
4009
        $idnumber = null;
4010
        if (!empty($data->idnumber)) {
4011
            // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
4012
            // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
4013
            // so the best is to keep the ones already in the gradebook
4014
            // Potential problem: duplicates if same items are restored more than once. :-(
4015
            // This needs to be fixed in some way (outcomes & activities with multiple items)
4016
            // $data->idnumber     = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
4017
            // In any case, verify always for uniqueness
4018
            $sql = "SELECT cm.id
4019
                      FROM {course_modules} cm
4020
                     WHERE cm.course = :courseid AND
4021
                           cm.idnumber = :idnumber AND
4022
                           cm.id <> :cmid";
4023
            $params = array(
4024
                'courseid' => $courseid,
4025
                'idnumber' => $data->idnumber,
4026
                'cmid' => $this->task->get_moduleid()
4027
            );
4028
            if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
4029
                $idnumber = $data->idnumber;
4030
            }
4031
        }
4032
 
4033
        if (!empty($data->categoryid)) {
4034
            // If the grade category id of the grade item being restored belongs to this course
4035
            // then it is a fair assumption that this is the correct grade category for the activity
4036
            // and we should leave it in place, if not then unset it.
4037
            // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
4038
            $conditions = array('id' => $data->categoryid, 'courseid' => $courseid);
4039
            if (!$this->task->is_samesite() || !$DB->record_exists('grade_categories', $conditions)) {
4040
                unset($data->categoryid);
4041
            }
4042
        }
4043
 
4044
        unset($data->id);
4045
        $data->courseid     = $this->get_courseid();
4046
        $data->iteminstance = $this->task->get_activityid();
4047
        $data->idnumber     = $idnumber;
4048
        $data->scaleid      = $this->get_mappingid('scale', $data->scaleid);
4049
        $data->outcomeid    = $this->get_mappingid('outcome', $data->outcomeid);
4050
 
4051
        $gradeitem = new grade_item($data, false);
4052
        $gradeitem->insert('restore');
4053
 
4054
        //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
4055
        $gradeitem->sortorder = $data->sortorder;
4056
        $gradeitem->update('restore');
4057
 
4058
        // Set mapping, saving the original category id into parentitemid
4059
        // gradebook restore (final task) will need it to reorganise items
4060
        $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
4061
    }
4062
 
4063
    protected function process_grade_grade($data) {
4064
        global $CFG;
4065
 
4066
        require_once($CFG->libdir . '/grade/constants.php');
4067
 
4068
        $data = (object)($data);
4069
        $olduserid = $data->userid;
4070
        $oldid = $data->id;
4071
        unset($data->id);
4072
 
4073
        $data->itemid = $this->get_new_parentid('grade_item');
4074
 
4075
        $data->userid = $this->get_mappingid('user', $data->userid, null);
4076
        if (!empty($data->userid)) {
4077
            $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4078
            $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4079
 
4080
            $grade = new grade_grade($data, false);
4081
            $grade->insert('restore');
4082
 
4083
            $this->set_mapping('grade_grades', $oldid, $grade->id, true);
4084
 
4085
            $this->add_related_files(
4086
                GRADE_FILE_COMPONENT,
4087
                GRADE_FEEDBACK_FILEAREA,
4088
                'grade_grades',
4089
                null,
4090
                $oldid
4091
            );
4092
        } else {
4093
            debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
4094
        }
4095
    }
4096
 
4097
    /**
4098
     * process activity grade_letters. Note that, while these are possible,
4099
     * because grade_letters are contextid based, in practice, only course
4100
     * context letters can be defined. So we keep here this method knowing
4101
     * it won't be executed ever. gradebook restore will restore course letters.
4102
     */
4103
    protected function process_grade_letter($data) {
4104
        global $DB;
4105
 
4106
        $data['contextid'] = $this->task->get_contextid();
4107
        $gradeletter = (object)$data;
4108
 
4109
        // Check if it exists before adding it
4110
        unset($data['id']);
4111
        if (!$DB->record_exists('grade_letters', $data)) {
4112
            $newitemid = $DB->insert_record('grade_letters', $gradeletter);
4113
        }
4114
        // no need to save any grade_letter mapping
4115
    }
4116
 
4117
    public function after_restore() {
4118
        // Fix grade item's sortorder after restore, as it might have duplicates.
4119
        $courseid = $this->get_task()->get_courseid();
4120
        grade_item::fix_duplicate_sortorder($courseid);
4121
    }
4122
}
4123
 
4124
/**
4125
 * Step in charge of restoring the grade history of an activity.
4126
 *
4127
 * This step is added to the task regardless of the setting 'grade_histories'.
4128
 * The reason is to allow for a more flexible step in case the logic needs to be
4129
 * split accross different settings to control the history of items and/or grades.
4130
 */
4131
class restore_activity_grade_history_structure_step extends restore_structure_step {
4132
 
4133
    /**
4134
     * This step is executed only if the grade history file is present.
4135
     */
4136
     protected function execute_condition() {
4137
 
4138
        if ($this->get_courseid() == SITEID) {
4139
            return false;
4140
        }
4141
 
4142
        $fullpath = $this->task->get_taskbasepath();
4143
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4144
        if (!file_exists($fullpath)) {
4145
            return false;
4146
        }
4147
        return true;
4148
    }
4149
 
4150
    protected function define_structure() {
4151
        $paths = array();
4152
 
4153
        // Settings to use.
4154
        $userinfo = $this->get_setting_value('userinfo');
4155
        $history = $this->get_setting_value('grade_histories');
4156
 
4157
        if ($userinfo && $history) {
4158
            $paths[] = new restore_path_element('grade_grade',
4159
               '/grade_history/grade_grades/grade_grade');
4160
        }
4161
 
4162
        return $paths;
4163
    }
4164
 
4165
    protected function process_grade_grade($data) {
4166
        global $CFG, $DB;
4167
 
4168
        require_once($CFG->libdir . '/grade/constants.php');
4169
 
4170
        $data = (object) $data;
4171
        $oldhistoryid = $data->id;
4172
        $olduserid = $data->userid;
4173
        unset($data->id);
4174
 
4175
        $data->userid = $this->get_mappingid('user', $data->userid, null);
4176
        if (!empty($data->userid)) {
4177
            // Do not apply the date offsets as this is history.
4178
            $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
4179
            $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
4180
            $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4181
            $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4182
 
4183
            $newhistoryid = $DB->insert_record('grade_grades_history', $data);
4184
 
4185
            $this->set_mapping('grade_grades_history', $oldhistoryid, $newhistoryid, true);
4186
 
4187
            $this->add_related_files(
4188
                GRADE_FILE_COMPONENT,
4189
                GRADE_HISTORY_FEEDBACK_FILEAREA,
4190
                'grade_grades_history',
4191
                null,
4192
                $oldhistoryid
4193
            );
4194
        } else {
4195
            $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
4196
            $this->log($message, backup::LOG_DEBUG);
4197
        }
4198
    }
4199
}
4200
 
4201
/**
4202
 * This structure steps restores the content bank content
4203
 */
4204
class restore_contentbankcontent_structure_step extends restore_structure_step {
4205
 
4206
    /**
4207
     * Define structure for content bank step
4208
     */
4209
    protected function define_structure() {
4210
 
4211
        $paths = [];
4212
        $paths[] = new restore_path_element('contentbankcontent', '/contents/content');
4213
 
4214
        return $paths;
4215
    }
4216
 
4217
    /**
4218
     * Define data processed for content bank
4219
     *
4220
     * @param mixed  $data
4221
     */
4222
    public function process_contentbankcontent($data) {
4223
        global $DB;
4224
 
4225
        $data = (object)$data;
4226
        $oldid = $data->id;
4227
 
4228
        $params = [
4229
            'name'           => $data->name,
4230
            'contextid'      => $this->task->get_contextid(),
4231
            'contenttype'    => $data->contenttype,
4232
            'instanceid'     => $data->instanceid,
4233
            'timecreated'    => $data->timecreated,
4234
        ];
4235
        $exists = $DB->record_exists('contentbank_content', $params);
4236
        if (!$exists) {
4237
            $params['configdata'] = $data->configdata;
4238
            $params['timemodified'] = time();
4239
 
4240
            // Trying to map users. Users cannot always be mapped, e.g. when copying.
4241
            $params['usercreated'] = $this->get_mappingid('user', $data->usercreated);
4242
            if (!$params['usercreated']) {
4243
                // Leave the content creator unchanged when we are restoring the same site.
4244
                // Otherwise use current user id.
4245
                if ($this->task->is_samesite()) {
4246
                    $params['usercreated'] = $data->usercreated;
4247
                } else {
4248
                    $params['usercreated'] = $this->task->get_userid();
4249
                }
4250
            }
4251
            $params['usermodified'] = $this->get_mappingid('user', $data->usermodified);
4252
            if (!$params['usermodified']) {
4253
                // Leave the content modifier unchanged when we are restoring the same site.
4254
                // Otherwise use current user id.
4255
                if ($this->task->is_samesite()) {
4256
                    $params['usermodified'] = $data->usermodified;
4257
                } else {
4258
                    $params['usermodified'] = $this->task->get_userid();
4259
                }
4260
            }
4261
 
4262
            $newitemid = $DB->insert_record('contentbank_content', $params);
4263
            $this->set_mapping('contentbank_content', $oldid, $newitemid, true);
4264
        }
4265
    }
4266
 
4267
    /**
4268
     * Define data processed after execute for content bank
4269
     */
4270
    protected function after_execute() {
4271
        // Add related files.
4272
        $this->add_related_files('contentbank', 'public', 'contentbank_content');
4273
    }
4274
}
4275
 
4276
/**
4277
 * This structure steps restores the xAPI states.
4278
 */
4279
class restore_xapistate_structure_step extends restore_structure_step {
4280
 
4281
    /**
4282
     * Define structure for xAPI state step
4283
     */
4284
    protected function define_structure() {
4285
        return [new restore_path_element('xapistate', '/states/state')];
4286
    }
4287
 
4288
    /**
4289
     * Define data processed for xAPI state.
4290
     *
4291
     * @param array|stdClass $data
4292
     */
4293
    public function process_xapistate($data) {
4294
        global $DB;
4295
 
4296
        $data = (object)$data;
4297
        $oldid = $data->id;
4298
        $exists = false;
4299
 
4300
        $params = [
4301
            'component' => $data->component,
4302
            'itemid' => $this->task->get_contextid(),
4303
            // Set stateid to 'restored', to let plugins identify the origin of this state is a backup.
4304
            'stateid' => 'restored',
4305
            'statedata' => $data->statedata,
4306
            'registration' => $data->registration,
4307
            'timecreated' => $data->timecreated,
4308
            'timemodified' => time(),
4309
        ];
4310
 
4311
        // Trying to map users. Users cannot always be mapped, for instance, when copying.
4312
        $params['userid'] = $this->get_mappingid('user', $data->userid);
4313
        if (!$params['userid']) {
4314
            // Leave the userid unchanged when we are restoring the same site.
4315
            if ($this->task->is_samesite()) {
4316
                $params['userid'] = $data->userid;
4317
            }
4318
            $filter = $params;
4319
            unset($filter['statedata']);
4320
            $exists = $DB->record_exists('xapi_states', $filter);
4321
        }
4322
 
4323
        if (!$exists && $params['userid']) {
4324
            // Only insert the record if the user exists or can be mapped.
4325
            $newitemid = $DB->insert_record('xapi_states', $params);
4326
            $this->set_mapping('xapi_states', $oldid, $newitemid, true);
4327
        }
4328
    }
4329
}
4330
 
4331
/**
4332
 * This structure steps restores one instance + positions of one block
4333
 * Note: Positions corresponding to one existing context are restored
4334
 * here, but all the ones having unknown contexts are sent to backup_ids
4335
 * for a later chance to be restored at the end (final task)
4336
 */
4337
class restore_block_instance_structure_step extends restore_structure_step {
4338
 
4339
    protected function define_structure() {
4340
 
4341
        $paths = array();
4342
 
4343
        $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
4344
        $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
4345
 
4346
        return $paths;
4347
    }
4348
 
4349
    public function process_block($data) {
4350
        global $DB, $CFG;
4351
 
4352
        $data = (object)$data; // Handy
4353
        $oldcontextid = $data->contextid;
4354
        $oldid        = $data->id;
4355
        $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
4356
 
4357
        // Look for the parent contextid
4358
        if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
4359
            // Parent contextid does not exist, ignore this block.
4360
            return false;
4361
        }
4362
 
4363
        // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
4364
        // If there is already one block of that type in the parent context
4365
        // and the block is not multiple, stop processing
4366
        // Use blockslib loader / method executor
4367
        if (!$bi = block_instance($data->blockname)) {
4368
            return false;
4369
        }
4370
 
4371
        if (!$bi->instance_allow_multiple()) {
4372
            // The block cannot be added twice, so we will check if the same block is already being
4373
            // displayed on the same page. For this, rather than mocking a page and using the block_manager
4374
            // we use a similar query to the one in block_manager::load_blocks(), this will give us
4375
            // a very good idea of the blocks already displayed in the context.
4376
            $params =  array(
4377
                'blockname' => $data->blockname
4378
            );
4379
 
4380
            // Context matching test.
4381
            $context = context::instance_by_id($data->parentcontextid);
4382
            $contextsql = 'bi.parentcontextid = :contextid';
4383
            $params['contextid'] = $context->id;
4384
 
4385
            $parentcontextids = $context->get_parent_context_ids();
4386
            if ($parentcontextids) {
4387
                list($parentcontextsql, $parentcontextparams) =
4388
                        $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
4389
                $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
4390
                $params = array_merge($params, $parentcontextparams);
4391
            }
4392
 
4393
            // Page type pattern test.
4394
            $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
4395
            list($pagetypepatternsql, $pagetypepatternparams) =
4396
                $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
4397
            $params = array_merge($params, $pagetypepatternparams);
4398
 
4399
            // Sub page pattern test.
4400
            $subpagepatternsql = 'bi.subpagepattern IS NULL';
4401
            if ($data->subpagepattern !== null) {
4402
                $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
4403
                $params['subpagepattern'] = $data->subpagepattern;
4404
            }
4405
 
4406
            $existingblock = $DB->get_records_sql("SELECT bi.id
4407
                                                FROM {block_instances} bi
4408
                                                JOIN {block} b ON b.name = bi.blockname
4409
                                               WHERE bi.blockname = :blockname
4410
                                                 AND $contextsql
4411
                                                 AND bi.pagetypepattern $pagetypepatternsql
4412
                                                 AND $subpagepatternsql", $params);
4413
            if (!empty($existingblock)) {
4414
                // Save the context mapping in case something else is linking to this block's context.
4415
                $newcontext = context_block::instance(reset($existingblock)->id);
4416
                $this->set_mapping('context', $oldcontextid, $newcontext->id);
4417
                // There is at least one very similar block visible on the page where we
4418
                // are trying to restore the block. In these circumstances the block API
4419
                // would not allow the user to add another instance of the block, so we
4420
                // apply the same rule here.
4421
                return false;
4422
            }
4423
        }
4424
 
4425
        // If there is already one block of that type in the parent context
4426
        // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
4427
        // stop processing
4428
        $params = array(
4429
            'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
4430
            'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
4431
            'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
4432
        if ($birecs = $DB->get_records('block_instances', $params)) {
4433
            foreach($birecs as $birec) {
4434
                if ($birec->configdata == $data->configdata) {
4435
                    // Save the context mapping in case something else is linking to this block's context.
4436
                    $newcontext = context_block::instance($birec->id);
4437
                    $this->set_mapping('context', $oldcontextid, $newcontext->id);
4438
                    return false;
4439
                }
4440
            }
4441
        }
4442
 
4443
        // Set task old contextid, blockid and blockname once we know them
4444
        $this->task->set_old_contextid($oldcontextid);
4445
        $this->task->set_old_blockid($oldid);
4446
        $this->task->set_blockname($data->blockname);
4447
 
4448
        // Let's look for anything within configdata neededing processing
4449
        // (nulls and uses of legacy file.php)
4450
        if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
4451
            $configdata = array_filter(
4452
                (array) unserialize_object(base64_decode($data->configdata)),
4453
                static function($value): bool {
4454
                    return !($value instanceof __PHP_Incomplete_Class);
4455
                }
4456
            );
4457
 
4458
            foreach ($configdata as $attribute => $value) {
4459
                if (in_array($attribute, $attrstotransform)) {
4460
                    $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
4461
                }
4462
            }
4463
            $data->configdata = base64_encode(serialize((object)$configdata));
4464
        }
4465
 
4466
        // Set timecreated, timemodified if not included (older backup).
4467
        if (empty($data->timecreated)) {
4468
            $data->timecreated = time();
4469
        }
4470
        if (empty($data->timemodified)) {
4471
            $data->timemodified = $data->timecreated;
4472
        }
4473
 
4474
        // Create the block instance
4475
        $newitemid = $DB->insert_record('block_instances', $data);
4476
        // Save the mapping (with restorefiles support)
4477
        $this->set_mapping('block_instance', $oldid, $newitemid, true);
4478
        // Create the block context
4479
        $newcontextid = context_block::instance($newitemid)->id;
4480
        // Save the block contexts mapping and sent it to task
4481
        $this->set_mapping('context', $oldcontextid, $newcontextid);
4482
        $this->task->set_contextid($newcontextid);
4483
        $this->task->set_blockid($newitemid);
4484
 
4485
        // Restore block fileareas if declared
4486
        $component = 'block_' . $this->task->get_blockname();
4487
        foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
4488
            $this->add_related_files($component, $filearea, null);
4489
        }
4490
 
4491
        // Process block positions, creating them or accumulating for final step
4492
        foreach($positions as $position) {
4493
            $position = (object)$position;
4494
            $position->blockinstanceid = $newitemid; // The instance is always the restored one
4495
            // If position is for one already mapped (known) contextid
4496
            // process it now, creating the position
4497
            if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
4498
                $position->contextid = $newpositionctxid;
4499
                // Create the block position
4500
                $DB->insert_record('block_positions', $position);
4501
 
4502
            // The position belongs to an unknown context, send it to backup_ids
4503
            // to process them as part of the final steps of restore. We send the
4504
            // whole $position object there, hence use the low level method.
4505
            } else {
4506
                restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
4507
            }
4508
        }
4509
    }
4510
}
4511
 
4512
/**
4513
 * Structure step to restore common course_module information
4514
 *
4515
 * This step will process the module.xml file for one activity, in order to restore
4516
 * the corresponding information to the course_modules table, skipping various bits
4517
 * of information based on CFG settings (groupings, completion...) in order to fullfill
4518
 * all the reqs to be able to create the context to be used by all the rest of steps
4519
 * in the activity restore task
4520
 */
4521
class restore_module_structure_step extends restore_structure_step {
4522
 
4523
    protected function define_structure() {
4524
        global $CFG;
4525
 
4526
        $paths = array();
4527
 
4528
        $module = new restore_path_element('module', '/module');
4529
        $paths[] = $module;
4530
        if ($CFG->enableavailability) {
4531
            $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
4532
            $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
4533
        }
4534
 
4535
        $paths[] = new restore_path_element('tag', '/module/tags/tag');
4536
 
4537
        // Apply for 'format' plugins optional paths at module level
4538
        $this->add_plugin_structure('format', $module);
4539
 
4540
        // Apply for 'report' plugins optional paths at module level.
4541
        $this->add_plugin_structure('report', $module);
4542
 
4543
        // Apply for 'plagiarism' plugins optional paths at module level
4544
        $this->add_plugin_structure('plagiarism', $module);
4545
 
4546
        // Apply for 'local' plugins optional paths at module level
4547
        $this->add_plugin_structure('local', $module);
4548
 
4549
        // Apply for 'admin tool' plugins optional paths at module level.
4550
        $this->add_plugin_structure('tool', $module);
4551
 
4552
        return $paths;
4553
    }
4554
 
4555
    protected function process_module($data) {
4556
        global $CFG, $DB;
4557
 
4558
        $data = (object)$data;
4559
        $oldid = $data->id;
4560
        $this->task->set_old_moduleversion($data->version);
4561
 
4562
        $data->course = $this->task->get_courseid();
4563
        $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
4564
        // Map section (first try by course_section mapping match. Useful in course and section restores)
4565
        $data->section = $this->get_mappingid('course_section', $data->sectionid);
4566
        if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
4567
            $params = array(
4568
                'course' => $this->get_courseid(),
4569
                'section' => $data->sectionnumber);
4570
            $data->section = $DB->get_field('course_sections', 'id', $params);
4571
        }
4572
        if (!$data->section) { // sectionnumber failed, try to get first section in course
4573
            $params = array(
4574
                'course' => $this->get_courseid());
4575
            $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
4576
        }
4577
        if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
4578
            $sectionrec = array(
4579
                'course' => $this->get_courseid(),
4580
                'section' => 0,
4581
                'timemodified' => time());
4582
            $DB->insert_record('course_sections', $sectionrec); // section 0
4583
            $sectionrec = array(
4584
                'course' => $this->get_courseid(),
4585
                'section' => 1,
4586
                'timemodified' => time());
4587
            $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
4588
        }
4589
        $data->groupingid= $this->get_mappingid('grouping', $data->groupingid);      // grouping
4590
        if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) {        // idnumber uniqueness
4591
            $data->idnumber = '';
4592
        }
4593
        if (empty($CFG->enablecompletion)) { // completion
4594
            $data->completion = 0;
4595
            $data->completiongradeitemnumber = null;
4596
            $data->completionview = 0;
4597
            $data->completionexpected = 0;
4598
        } else {
4599
            $data->completionexpected = $this->apply_date_offset($data->completionexpected);
4600
        }
4601
        if (empty($CFG->enableavailability)) {
4602
            $data->availability = null;
4603
        }
4604
        // Backups that did not include showdescription, set it to default 0
4605
        // (this is not totally necessary as it has a db default, but just to
4606
        // be explicit).
4607
        if (!isset($data->showdescription)) {
4608
            $data->showdescription = 0;
4609
        }
4610
        $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
4611
 
4612
        if (empty($data->availability)) {
4613
            // If there are legacy availablility data fields (and no new format data),
4614
            // convert the old fields.
4615
            $data->availability = \core_availability\info::convert_legacy_fields(
4616
                    $data, false);
4617
        } else if (!empty($data->groupmembersonly)) {
4618
            // There is current availability data, but it still has groupmembersonly
4619
            // as well (2.7 backups), convert just that part.
4620
            require_once($CFG->dirroot . '/lib/db/upgradelib.php');
4621
            $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
4622
        }
4623
 
4624
        if (!has_capability('moodle/course:setforcedlanguage', context_course::instance($data->course))) {
4625
            unset($data->lang);
4626
        }
4627
 
4628
        // course_module record ready, insert it
4629
        $newitemid = $DB->insert_record('course_modules', $data);
4630
        // save mapping
4631
        $this->set_mapping('course_module', $oldid, $newitemid);
4632
        // set the new course_module id in the task
4633
        $this->task->set_moduleid($newitemid);
4634
        // we can now create the context safely
4635
        $ctxid = context_module::instance($newitemid)->id;
4636
        // set the new context id in the task
4637
        $this->task->set_contextid($ctxid);
4638
        // update sequence field in course_section
4639
        if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
4640
            $sequence .= ',' . $newitemid;
4641
        } else {
4642
            $sequence = $newitemid;
4643
        }
4644
 
4645
        $updatesection = new \stdClass();
4646
        $updatesection->id = $data->section;
4647
        $updatesection->sequence = $sequence;
4648
        $updatesection->timemodified = time();
4649
        $DB->update_record('course_sections', $updatesection);
4650
 
4651
        // If there is the legacy showavailability data, store this for later use.
4652
        // (This data is not present when restoring 'new' backups.)
4653
        if (isset($data->showavailability)) {
4654
            // Cache the showavailability flag using the backup_ids data field.
4655
            restore_dbops::set_backup_ids_record($this->get_restoreid(),
4656
                    'module_showavailability', $newitemid, 0, null,
4657
                    (object)array('showavailability' => $data->showavailability));
4658
        }
4659
    }
4660
 
4661
    /**
4662
     * Fetch all the existing because tag_set() deletes them
4663
     * so everything must be reinserted on each call.
4664
     *
4665
     * @param stdClass $data Record data
4666
     */
4667
    protected function process_tag($data) {
4668
        global $CFG;
4669
 
4670
        $data = (object)$data;
4671
 
4672
        if (core_tag_tag::is_enabled('core', 'course_modules')) {
4673
            $modcontext = context::instance_by_id($this->task->get_contextid());
4674
            $instanceid = $this->task->get_moduleid();
4675
 
4676
            core_tag_tag::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname);
4677
        }
4678
    }
4679
 
4680
    /**
4681
     * Process the legacy availability table record. This table does not exist
4682
     * in Moodle 2.7+ but we still support restore.
4683
     *
4684
     * @param stdClass $data Record data
4685
     */
4686
    protected function process_availability($data) {
4687
        $data = (object)$data;
4688
        // Simply going to store the whole availability record now, we'll process
4689
        // all them later in the final task (once all activities have been restored)
4690
        // Let's call the low level one to be able to store the whole object
4691
        $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
4692
        restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
4693
    }
4694
 
4695
    /**
4696
     * Process the legacy availability fields table record. This table does not
4697
     * exist in Moodle 2.7+ but we still support restore.
4698
     *
4699
     * @param stdClass $data Record data
4700
     */
4701
    protected function process_availability_field($data) {
4702
        global $DB, $CFG;
4703
        require_once($CFG->dirroot.'/user/profile/lib.php');
4704
 
4705
        $data = (object)$data;
4706
        // Mark it is as passed by default
4707
        $passed = true;
4708
        $customfieldid = null;
4709
 
4710
        // If a customfield has been used in order to pass we must be able to match an existing
4711
        // customfield by name (data->customfield) and type (data->customfieldtype)
4712
        if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
4713
            // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
4714
            // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
4715
            $passed = false;
4716
        } else if (!empty($data->customfield)) {
4717
            $field = profile_get_custom_field_data_by_shortname($data->customfield);
4718
            $passed = $field && $field->datatype == $data->customfieldtype;
4719
        }
4720
 
4721
        if ($passed) {
4722
            // Create the object to insert into the database
4723
            $availfield = new stdClass();
4724
            $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
4725
            $availfield->userfield = $data->userfield;
4726
            $availfield->customfieldid = $customfieldid;
4727
            $availfield->operator = $data->operator;
4728
            $availfield->value = $data->value;
4729
 
4730
            // Get showavailability option.
4731
            $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4732
                    'module_showavailability', $availfield->coursemoduleid);
4733
            if (!$showrec) {
4734
                // Should not happen.
4735
                throw new coding_exception('No matching showavailability record');
4736
            }
4737
            $show = $showrec->info->showavailability;
4738
 
4739
            // The $availfieldobject is now in the format used in the old
4740
            // system. Interpret this and convert to new system.
4741
            $currentvalue = $DB->get_field('course_modules', 'availability',
4742
                    array('id' => $availfield->coursemoduleid), MUST_EXIST);
4743
            $newvalue = \core_availability\info::add_legacy_availability_field_condition(
4744
                    $currentvalue, $availfield, $show);
4745
            $DB->set_field('course_modules', 'availability', $newvalue,
4746
                    array('id' => $availfield->coursemoduleid));
4747
        }
4748
    }
4749
    /**
4750
     * This method will be executed after the rest of the restore has been processed.
4751
     *
4752
     * Update old tag instance itemid(s).
4753
     */
4754
    protected function after_restore() {
4755
        global $DB;
4756
 
4757
        $contextid = $this->task->get_contextid();
4758
        $instanceid = $this->task->get_activityid();
4759
        $olditemid = $this->task->get_old_activityid();
4760
 
4761
        $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
4762
    }
4763
}
4764
 
4765
/**
4766
 * Structure step that will process the user activity completion
4767
 * information if all these conditions are met:
4768
 *  - Target site has completion enabled ($CFG->enablecompletion)
4769
 *  - Activity includes completion info (file_exists)
4770
 */
4771
class restore_userscompletion_structure_step extends restore_structure_step {
4772
    /**
4773
     * To conditionally decide if this step must be executed
4774
     * Note the "settings" conditions are evaluated in the
4775
     * corresponding task. Here we check for other conditions
4776
     * not being restore settings (files, site settings...)
4777
     */
4778
     protected function execute_condition() {
4779
         global $CFG;
4780
 
4781
         // Completion disabled in this site, don't execute
4782
         if (empty($CFG->enablecompletion)) {
4783
             return false;
4784
         }
4785
 
4786
        // No completion on the front page.
4787
        if ($this->get_courseid() == SITEID) {
4788
            return false;
4789
        }
4790
 
4791
         // No user completion info found, don't execute
4792
        $fullpath = $this->task->get_taskbasepath();
4793
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4794
         if (!file_exists($fullpath)) {
4795
             return false;
4796
         }
4797
 
4798
         // Arrived here, execute the step
4799
         return true;
4800
     }
4801
 
4802
     protected function define_structure() {
4803
 
4804
        $paths = array();
4805
 
4806
        // Restore completion.
4807
        $paths[] = new restore_path_element('completion', '/completions/completion');
4808
 
4809
        // Restore completion view.
4810
        $paths[] = new restore_path_element('completionview', '/completions/completionviews/completionview');
4811
 
4812
        return $paths;
4813
    }
4814
 
4815
    protected function process_completion($data) {
4816
        global $DB;
4817
 
4818
        $data = (object)$data;
4819
 
4820
        $data->coursemoduleid = $this->task->get_moduleid();
4821
        $data->userid = $this->get_mappingid('user', $data->userid);
4822
 
4823
        // Find the existing record
4824
        $existing = $DB->get_record('course_modules_completion', array(
4825
                'coursemoduleid' => $data->coursemoduleid,
4826
                'userid' => $data->userid), 'id, timemodified');
4827
        // Check we didn't already insert one for this cmid and userid
4828
        // (there aren't supposed to be duplicates in that field, but
4829
        // it was possible until MDL-28021 was fixed).
4830
        if ($existing) {
4831
            // Update it to these new values, but only if the time is newer
4832
            if ($existing->timemodified < $data->timemodified) {
4833
                $data->id = $existing->id;
4834
                $DB->update_record('course_modules_completion', $data);
4835
            }
4836
        } else {
4837
            // Normal entry where it doesn't exist already
4838
            $DB->insert_record('course_modules_completion', $data);
4839
        }
4840
 
4841
        // Add viewed to course_modules_viewed.
4842
        if (isset($data->viewed) && $data->viewed) {
4843
            $dataview = clone($data);
4844
            unset($dataview->id);
4845
            unset($dataview->viewed);
4846
            $dataview->timecreated = $data->timemodified;
4847
            $DB->insert_record('course_modules_viewed', $dataview);
4848
        }
4849
    }
4850
 
4851
    /**
4852
     * Process the completioinview data.
4853
     * @param array $data The data from the XML file.
4854
     */
4855
    protected function process_completionview(array $data) {
4856
        global $DB;
4857
 
4858
        $data = (object)$data;
4859
        $data->coursemoduleid = $this->task->get_moduleid();
4860
        $data->userid = $this->get_mappingid('user', $data->userid);
4861
 
4862
        $DB->insert_record('course_modules_viewed', $data);
4863
    }
4864
}
4865
 
4866
/**
4867
 * Abstract structure step, parent of all the activity structure steps. Used to support
4868
 * the main <activity ...> tag and process it.
4869
 */
4870
abstract class restore_activity_structure_step extends restore_structure_step {
4871
 
4872
    /**
4873
     * Adds support for the 'activity' path that is common to all the activities
4874
     * and will be processed globally here
4875
     */
4876
    protected function prepare_activity_structure($paths) {
4877
 
4878
        $paths[] = new restore_path_element('activity', '/activity');
4879
 
4880
        return $paths;
4881
    }
4882
 
4883
    /**
4884
     * Process the activity path, informing the task about various ids, needed later
4885
     */
4886
    protected function process_activity($data) {
4887
        $data = (object)$data;
4888
        $this->task->set_old_contextid($data->contextid); // Save old contextid in task
4889
        $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
4890
        $this->task->set_old_activityid($data->id); // Save old activityid in task
4891
    }
4892
 
4893
    /**
4894
     * This must be invoked immediately after creating the "module" activity record (forum, choice...)
4895
     * and will adjust the new activity id (the instance) in various places
4896
     */
4897
    protected function apply_activity_instance($newitemid) {
4898
        global $DB;
4899
 
4900
        $this->task->set_activityid($newitemid); // Save activity id in task
4901
        // Apply the id to course_sections->instanceid
4902
        $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
4903
        // Do the mapping for modulename, preparing it for files by oldcontext
4904
        $modulename = $this->task->get_modulename();
4905
        $oldid = $this->task->get_old_activityid();
4906
        $this->set_mapping($modulename, $oldid, $newitemid, true);
4907
    }
4908
}
4909
 
4910
/**
4911
 * Structure step in charge of creating/mapping all the qcats and qs
4912
 * by parsing the questions.xml file and checking it against the
4913
 * results calculated by {@link restore_process_categories_and_questions}
4914
 * and stored in backup_ids_temp.
4915
 */
4916
class restore_create_categories_and_questions extends restore_structure_step {
4917
 
4918
    /** @var array $cachedcategory store a question category */
4919
    protected $cachedcategory = null;
4920
 
4921
    protected function define_structure() {
4922
 
4923
        // Check if the backup is a pre 4.0 one.
4924
        $restoretask = $this->get_task();
4925
        $before40 = $restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<');
4926
        // Start creating the path, category should be the first one.
4927
        $paths = [];
4928
        $paths [] = new restore_path_element('question_category', '/question_categories/question_category');
4929
        // For the backups done before 4.0.
4930
        if ($before40) {
4931
            // This path is to recreate the bank entry and version for the legacy question objets.
4932
            $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
4933
 
4934
            // Apply for 'qtype' plugins optional paths at question level.
4935
            $this->add_plugin_structure('qtype', $question);
4936
 
4937
            // Apply for 'local' plugins optional paths at question level.
4938
            $this->add_plugin_structure('local', $question);
4939
 
4940
            $paths [] = $question;
4941
            $paths [] = new restore_path_element('question_hint',
4942
                '/question_categories/question_category/questions/question/question_hints/question_hint');
4943
            $paths [] = new restore_path_element('tag', '/question_categories/question_category/questions/question/tags/tag');
4944
        } else {
4945
            // For all the new backups.
4946
            $paths [] = new restore_path_element('question_bank_entry',
4947
                '/question_categories/question_category/question_bank_entries/question_bank_entry');
4948
            $paths [] = new restore_path_element('question_versions', '/question_categories/question_category/'.
4949
                'question_bank_entries/question_bank_entry/question_version/question_versions');
4950
            $question = new restore_path_element('question', '/question_categories/question_category/'.
4951
                'question_bank_entries/question_bank_entry/question_version/question_versions/questions/question');
4952
 
4953
            // Apply for 'qtype' plugins optional paths at question level.
4954
            $this->add_plugin_structure('qtype', $question);
4955
 
4956
            // Apply for 'qbank' plugins optional paths at question level.
4957
            $this->add_plugin_structure('qbank', $question);
4958
 
4959
            // Apply for 'local' plugins optional paths at question level.
4960
            $this->add_plugin_structure('local', $question);
4961
 
4962
            $paths [] = $question;
4963
            $paths [] = new restore_path_element('question_hint', '/question_categories/question_category/question_bank_entries/'.
4964
                'question_bank_entry/question_version/question_versions/questions/question/question_hints/question_hint');
4965
            $paths [] = new restore_path_element('tag', '/question_categories/question_category/question_bank_entries/'.
4966
                'question_bank_entry/question_version/question_versions/questions/question/tags/tag');
4967
        }
4968
 
4969
        return $paths;
4970
    }
4971
 
4972
    /**
4973
     * Process question category restore.
4974
     *
4975
     * @param array $data the data from the XML file.
4976
     */
4977
    protected function process_question_category($data) {
4978
        global $DB;
4979
 
4980
        $data = (object)$data;
4981
        $oldid = $data->id;
4982
 
4983
        // Check we have one mapping for this category.
4984
        if (!$mapping = $this->get_mapping('question_category', $oldid)) {
4985
            return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
4986
        }
4987
 
4988
        // Check we have to create the category (newitemid = 0).
4989
        if ($mapping->newitemid) {
4990
            // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4991
            // children elements of the 'question_category' one.
4992
            $this->set_mapping('question_category', $oldid, $mapping->newitemid);
4993
            return; // newitemid != 0, this category is going to be mapped. Nothing to do
4994
        }
4995
 
4996
        // Arrived here, newitemid = 0, we need to create the category
4997
        // we'll do it at parentitemid context, but for CONTEXT_MODULE
4998
        // categories, that will be created at CONTEXT_COURSE and moved
4999
        // to module context later when the activity is created.
5000
        if ($mapping->info->contextlevel == CONTEXT_MODULE) {
5001
            $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
5002
        }
5003
        $data->contextid = $mapping->parentitemid;
5004
 
5005
        // Before 3.5, question categories could be created at top level.
5006
        // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
5007
        $restoretask = $this->get_task();
5008
        $before35 = $restoretask->backup_release_compare('3.5', '<') || $restoretask->backup_version_compare(20180205, '<');
5009
        if (empty($mapping->info->parent) && $before35) {
5010
            $top = question_get_top_category($data->contextid, true);
5011
            $data->parent = $top->id;
5012
        }
5013
 
5014
        if (empty($data->parent)) {
5015
            if (!$top = question_get_top_category($data->contextid)) {
5016
                $top = question_get_top_category($data->contextid, true);
5017
                $this->set_mapping('question_category_created', $oldid, $top->id, false, null, $data->contextid);
5018
            }
5019
            $this->set_mapping('question_category', $oldid, $top->id);
5020
        } else {
5021
 
5022
            // Before 3.1, the 'stamp' field could be erroneously duplicated.
5023
            // From 3.1 onwards, there's a unique index of (contextid, stamp).
5024
            // If we encounter a duplicate in an old restore file, just generate a new stamp.
5025
            // This is the same as what happens during an upgrade to 3.1+ anyway.
5026
            if ($DB->record_exists('question_categories', ['stamp' => $data->stamp, 'contextid' => $data->contextid])) {
5027
                $data->stamp = make_unique_id_code();
5028
            }
5029
 
5030
            // The idnumber if it exists also needs to be unique within a context or reset it to null.
5031
            if (!empty($data->idnumber) && $DB->record_exists('question_categories',
5032
                    ['idnumber' => $data->idnumber, 'contextid' => $data->contextid])) {
5033
                unset($data->idnumber);
5034
            }
5035
 
5036
            // Let's create the question_category and save mapping.
5037
            $newitemid = $DB->insert_record('question_categories', $data);
5038
            $this->set_mapping('question_category', $oldid, $newitemid);
5039
            // Also annotate them as question_category_created, we need
5040
            // that later when remapping parents.
5041
            $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
5042
        }
5043
    }
5044
 
5045
    /**
5046
     * Process pre 4.0 question data where in creates the record for version and entry table.
5047
     *
5048
     * @param array $data the data from the XML file.
5049
     */
5050
    protected function process_question_legacy_data($data) {
5051
        global $DB;
5052
 
5053
        $oldid = $data->id;
5054
        // Process question bank entry.
5055
        $entrydata = new stdClass();
5056
        $entrydata->questioncategoryid = $data->category;
5057
        $userid = $this->get_mappingid('user', $data->createdby);
5058
        if ($userid) {
5059
            $entrydata->ownerid = $userid;
5060
        } else {
5061
            if (!$this->task->is_samesite()) {
5062
                $entrydata->ownerid = $this->task->get_userid();
5063
            }
5064
        }
5065
        // The idnumber if it exists also needs to be unique within a category or reset it to null.
5066
        if (isset($data->idnumber) && !$DB->record_exists('question_bank_entries',
5067
                ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->category])) {
5068
            $entrydata->idnumber = $data->idnumber;
5069
        }
5070
 
5071
        $newentryid = $DB->insert_record('question_bank_entries', $entrydata);
5072
        // Process question versions.
5073
        $versiondata = new stdClass();
5074
        $versiondata->questionbankentryid = $newentryid;
5075
        $versiondata->version = 1;
5076
        // Question id is updated after inserting the question.
5077
        $versiondata->questionid = 0;
5078
        $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
5079
        if ((int)$data->hidden === 1) {
5080
            $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_HIDDEN;
5081
        }
5082
        $versiondata->status = $versionstatus;
5083
        $newversionid = $DB->insert_record('question_versions', $versiondata);
5084
        $this->set_mapping('question_version_created', $oldid, $newversionid);
5085
    }
5086
 
5087
    /**
5088
     * Process question bank entry data.
5089
     *
5090
     * @param array $data the data from the XML file.
5091
     */
5092
    protected function process_question_bank_entry($data) {
5093
        global $DB;
5094
 
5095
        $data = (object)$data;
5096
        $oldid = $data->id;
5097
 
5098
        $questioncreated = $this->get_mappingid('question_category_created', $data->questioncategoryid) ? true : false;
5099
        $recordexist = $DB->record_exists('question_bank_entries', ['id' => $data->id,
5100
            'questioncategoryid' => $data->questioncategoryid]);
5101
        // Check we have category created.
5102
        if (!$questioncreated && $recordexist) {
5103
            return self::SKIP_ALL_CHILDREN;
5104
        }
5105
 
5106
        $data->questioncategoryid = $this->get_new_parentid('question_category');
5107
        $userid = $this->get_mappingid('user', $data->ownerid);
5108
        if ($userid) {
5109
            $data->ownerid = $userid;
5110
        } else {
5111
            if (!$this->task->is_samesite()) {
5112
                $data->ownerid = $this->task->get_userid();
5113
            }
5114
        }
5115
 
5116
        // The idnumber if it exists also needs to be unique within a category or reset it to null.
5117
        if (!empty($data->idnumber) && $DB->record_exists('question_bank_entries',
5118
                ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->questioncategoryid])) {
5119
            unset($data->idnumber);
5120
        }
5121
 
5122
        $newitemid = $DB->insert_record('question_bank_entries', $data);
5123
        $this->set_mapping('question_bank_entry', $oldid, $newitemid);
5124
    }
5125
 
5126
    /**
5127
     * Process question versions.
5128
     *
5129
     * @param array $data the data from the XML file.
5130
     */
5131
    protected function process_question_versions($data) {
5132
        global $DB;
5133
 
5134
        $data = (object)$data;
5135
        $oldid = $data->id;
5136
 
5137
        $data->questionbankentryid = $this->get_new_parentid('question_bank_entry');
5138
        // Question id is updated after inserting the question.
5139
        $data->questionid = 0;
5140
        $newitemid = $DB->insert_record('question_versions', $data);
5141
        $this->set_mapping('question_versions', $oldid, $newitemid);
5142
    }
5143
 
5144
    /**
5145
     * Process the actual question.
5146
     *
5147
     * @param array $data the data from the XML file.
5148
     */
5149
    protected function process_question($data) {
5150
        global $DB;
5151
 
5152
        $data = (object)$data;
5153
        $oldid = $data->id;
5154
 
5155
        // Check if the backup is a pre 4.0 one.
5156
        $restoretask = $this->get_task();
5157
        if ($restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<')) {
5158
            // Check we have one mapping for this question.
5159
            if (!$questionmapping = $this->get_mapping('question', $oldid)) {
5160
                return; // No mapping = this question doesn't need to be created/mapped.
5161
            }
5162
 
5163
            // Get the mapped category (cannot use get_new_parentid() because not
5164
            // all the categories have been created, so it is not always available
5165
            // Instead we get the mapping for the question->parentitemid because
5166
            // we have loaded qcatids there for all parsed questions.
5167
            $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
5168
            $this->process_question_legacy_data($data);
5169
        }
5170
 
5171
        // In the past, there were some very sloppy values of penalty. Fix them.
5172
        if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
5173
            $data->penalty = 0.3333333;
5174
        }
5175
        if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
5176
            $data->penalty = 0.6666667;
5177
        }
5178
        if ($data->penalty >= 1) {
5179
            $data->penalty = 1;
5180
        }
5181
 
5182
        $userid = $this->get_mappingid('user', $data->createdby);
5183
        if ($userid) {
5184
            // The question creator is included in the backup, so we can use their mapping id.
5185
            $data->createdby = $userid;
5186
        } else {
5187
            // Leave the question creator unchanged when we are restoring the same site.
5188
            // Otherwise use current user id.
5189
            if (!$this->task->is_samesite()) {
5190
                $data->createdby = $this->task->get_userid();
5191
            }
5192
        }
5193
 
5194
        $userid = $this->get_mappingid('user', $data->modifiedby);
5195
        if ($userid) {
5196
            // The question modifier is included in the backup, so we can use their mapping id.
5197
            $data->modifiedby = $userid;
5198
        } else {
5199
            // Leave the question modifier unchanged when we are restoring the same site.
5200
            // Otherwise use current user id.
5201
            if (!$this->task->is_samesite()) {
5202
                $data->modifiedby = $this->task->get_userid();
5203
            }
5204
        }
5205
 
5206
        $newitemid = $DB->insert_record('question', $data);
5207
        $this->set_mapping('question', $oldid, $newitemid);
5208
        // Also annotate them as question_created, we need
5209
        // that later when remapping parents (keeping the old categoryid as parentid).
5210
        $parentcatid = $this->get_old_parentid('question_category');
5211
        $this->set_mapping('question_created', $oldid, $newitemid, false, null, $parentcatid);
5212
        // Now update the question_versions table with the new question id. we dont need to do that for random qtypes.
5213
        $legacyquestiondata = $this->get_mappingid('question_version_created', $oldid) ? true : false;
5214
        if ($legacyquestiondata) {
5215
            $parentitemid = $this->get_mappingid('question_version_created', $oldid);
5216
        } else {
5217
            $parentitemid = $this->get_new_parentid('question_versions');
5218
        }
5219
        $version = new stdClass();
5220
        $version->id = $parentitemid;
5221
        $version->questionid = $newitemid;
5222
        $DB->update_record('question_versions', $version);
5223
 
5224
        // Note, we don't restore any question files yet
5225
        // as far as the CONTEXT_MODULE categories still
5226
        // haven't their contexts to be restored to
5227
        // The {@link restore_create_question_files}, executed in the final step
5228
        // step will be in charge of restoring all the question files.
5229
    }
5230
 
5231
    protected function process_question_hint($data) {
5232
        global $DB;
5233
 
5234
        $data = (object)$data;
5235
        $oldid = $data->id;
5236
 
5237
        // Detect if the question is created or mapped
5238
        $oldquestionid   = $this->get_old_parentid('question');
5239
        $newquestionid   = $this->get_new_parentid('question');
5240
        $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
5241
 
5242
        // If the question has been created by restore, we need to create its question_answers too
5243
        if ($questioncreated) {
5244
            // Adjust some columns
5245
            $data->questionid = $newquestionid;
5246
            // Insert record
5247
            $newitemid = $DB->insert_record('question_hints', $data);
5248
 
5249
        // The question existed, we need to map the existing question_hints
5250
        } else {
5251
            // Look in question_hints by hint text matching
5252
            $sql = 'SELECT id
5253
                      FROM {question_hints}
5254
                     WHERE questionid = ?
5255
                       AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
5256
            $params = array($newquestionid, $data->hint);
5257
            $newitemid = $DB->get_field_sql($sql, $params);
5258
 
5259
            // Not able to find the hint, let's try cleaning the hint text
5260
            // of all the question's hints in DB as slower fallback. MDL-33863.
5261
            if (!$newitemid) {
5262
                $potentialhints = $DB->get_records('question_hints',
5263
                        array('questionid' => $newquestionid), '', 'id, hint');
5264
                foreach ($potentialhints as $potentialhint) {
5265
                    // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
5266
                    $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
5267
                    $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
5268
                    if ($cleanhint === $data->hint) {
5269
                        $newitemid = $data->id;
5270
                    }
5271
                }
5272
            }
5273
 
5274
            // If we haven't found the newitemid, something has gone really wrong, question in DB
5275
            // is missing hints, exception
5276
            if (!$newitemid) {
5277
                $info = new stdClass();
5278
                $info->filequestionid = $oldquestionid;
5279
                $info->dbquestionid   = $newquestionid;
5280
                $info->hint           = $data->hint;
5281
                throw new restore_step_exception('error_question_hint_missing_in_db', $info);
5282
            }
5283
        }
5284
        // Create mapping (I'm not sure if this is really needed?)
5285
        $this->set_mapping('question_hint', $oldid, $newitemid);
5286
    }
5287
 
5288
    protected function process_tag($data) {
5289
        global $DB;
5290
 
5291
        $data = (object)$data;
5292
        $newquestion = $this->get_new_parentid('question');
5293
        $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
5294
        if (!$questioncreated) {
5295
            // This question already exists in the question bank. Nothing for us to do.
5296
            return;
5297
        }
5298
 
5299
        if (core_tag_tag::is_enabled('core_question', 'question')) {
5300
            $tagname = $data->rawname;
5301
            if (!empty($data->contextid) && $newcontextid = $this->get_mappingid('context', $data->contextid)) {
5302
                    $tagcontextid = $newcontextid;
5303
            } else {
5304
                // Get the category, so we can then later get the context.
5305
                $categoryid = $this->get_new_parentid('question_category');
5306
                if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
5307
                    $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
5308
                }
5309
                $tagcontextid = $this->cachedcategory->contextid;
5310
            }
5311
            // Add the tag to the question.
5312
            core_tag_tag::add_item_tag('core_question', 'question', $newquestion,
5313
                    context::instance_by_id($tagcontextid),
5314
                    $tagname);
5315
        }
5316
    }
5317
 
5318
    protected function after_execute() {
5319
        global $DB;
5320
 
5321
        // First of all, recode all the created question_categories->parent fields
5322
        $qcats = $DB->get_records('backup_ids_temp', array(
5323
                     'backupid' => $this->get_restoreid(),
5324
                     'itemname' => 'question_category_created'));
5325
        foreach ($qcats as $qcat) {
5326
            $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
5327
            // Get new parent (mapped or created, so we look in quesiton_category mappings)
5328
            if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5329
                                 'backupid' => $this->get_restoreid(),
5330
                                 'itemname' => 'question_category',
5331
                                 'itemid'   => $dbcat->parent))) {
5332
                // contextids must match always, as far as we always include complete qbanks, just check it
5333
                $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
5334
                if ($dbcat->contextid == $newparentctxid) {
5335
                    $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
5336
                } else {
5337
                    $newparent = 0; // No ctx match for both cats, no parent relationship
5338
                }
5339
            }
5340
            // Here with $newparent empty, problem with contexts or remapping, set it to top cat
5341
            if (!$newparent && $dbcat->parent) {
5342
                $topcat = question_get_top_category($dbcat->contextid, true);
5343
                if ($dbcat->parent != $topcat->id) {
5344
                    $DB->set_field('question_categories', 'parent', $topcat->id, array('id' => $dbcat->id));
5345
                }
5346
            }
5347
        }
5348
 
5349
        // Now, recode all the created question->parent fields
5350
        $qs = $DB->get_records('backup_ids_temp', array(
5351
                  'backupid' => $this->get_restoreid(),
5352
                  'itemname' => 'question_created'));
5353
        foreach ($qs as $q) {
5354
            $dbq = $DB->get_record('question', array('id' => $q->newitemid));
5355
            // Get new parent (mapped or created, so we look in question mappings)
5356
            if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5357
                                 'backupid' => $this->get_restoreid(),
5358
                                 'itemname' => 'question',
5359
                                 'itemid'   => $dbq->parent))) {
5360
                $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
5361
            }
5362
        }
5363
 
5364
        // Note, we don't restore any question files yet
5365
        // as far as the CONTEXT_MODULE categories still
5366
        // haven't their contexts to be restored to
5367
        // The {@link restore_create_question_files}, executed in the final step
5368
        // step will be in charge of restoring all the question files
5369
    }
5370
}
5371
 
5372
/**
5373
 * Execution step that will move all the CONTEXT_MODULE question categories
5374
 * created at early stages of restore in course context (because modules weren't
5375
 * created yet) to their target module (matching by old-new-contextid mapping)
5376
 */
5377
class restore_move_module_questions_categories extends restore_execution_step {
5378
 
5379
    protected function define_execution() {
5380
        global $DB;
5381
 
5382
        $after35 = $this->task->backup_release_compare('3.5', '>=') && $this->task->backup_version_compare(20180205, '>');
5383
 
5384
        $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
5385
        foreach ($contexts as $contextid => $contextlevel) {
5386
            // Only if context mapping exists (i.e. the module has been restored)
5387
            if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
5388
                // Update all the qcats having their parentitemid set to the original contextid
5389
                $modulecats = $DB->get_records_sql("SELECT itemid, newitemid, info
5390
                                                      FROM {backup_ids_temp}
5391
                                                     WHERE backupid = ?
5392
                                                       AND itemname = 'question_category'
5393
                                                       AND parentitemid = ?", array($this->get_restoreid(), $contextid));
5394
                $top = question_get_top_category($newcontext->newitemid, true);
5395
                $oldtopid = 0;
5396
                $categoryids = [];
5397
                foreach ($modulecats as $modulecat) {
5398
                    // Before 3.5, question categories could be created at top level.
5399
                    // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
5400
                    $info = backup_controller_dbops::decode_backup_temp_info($modulecat->info);
5401
                    if ($after35 && empty($info->parent)) {
5402
                        $oldtopid = $modulecat->newitemid;
5403
                        $modulecat->newitemid = $top->id;
5404
                    } else {
5405
                        $cat = new stdClass();
5406
                        $cat->id = $modulecat->newitemid;
5407
                        $cat->contextid = $newcontext->newitemid;
5408
                        if (empty($info->parent)) {
5409
                            $cat->parent = $top->id;
5410
                        }
5411
                        $DB->update_record('question_categories', $cat);
5412
                        $categoryids[] = (int)$cat->id;
5413
                    }
5414
 
5415
                    // And set new contextid (and maybe update newitemid) also in question_category mapping (will be
5416
                    // used by {@link restore_create_question_files} later.
5417
                    restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid,
5418
                            $modulecat->newitemid, $newcontext->newitemid);
5419
                }
5420
 
5421
                // Update the context id of any tags applied to any questions in these categories.
5422
                if ($categoryids) {
5423
                    [$categorysql, $categoryidparams] = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
5424
                    $sqlupdate = "UPDATE {tag_instance}
5425
                                     SET contextid = :newcontext
5426
                                   WHERE component = :component
5427
                                         AND itemtype = :itemtype
5428
                                         AND itemid IN (SELECT DISTINCT bi.newitemid as questionid
5429
                                                          FROM {backup_ids_temp} bi
5430
                                                          JOIN {question} q ON q.id = bi.newitemid
5431
                                                          JOIN {question_versions} qv ON qv.questionid = q.id
5432
                                                          JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
5433
                                                         WHERE bi.backupid = :backupid AND bi.itemname = 'question_created'
5434
                                                               AND qbe.questioncategoryid {$categorysql}) ";
5435
                    $params = [
5436
                        'newcontext' => $newcontext->newitemid,
5437
                        'component' => 'core_question',
5438
                        'itemtype' => 'question',
5439
                        'backupid' => $this->get_restoreid(),
5440
                    ];
5441
                    $params += $categoryidparams;
5442
                    $DB->execute($sqlupdate, $params);
5443
 
5444
                    // As explained in {@see restore_quiz_activity_structure_step::process_quiz_question_legacy_instance()}
5445
                    // question_set_references relating to random questions restored from old backups,
5446
                    // which pick from context_module question_categores, will have been restored with the wrong questioncontextid.
5447
                    // So, now, we need to find those, and updated the questioncontextid.
5448
                    // We can only find them by picking apart the filter conditions, and seeign which categories they refer to.
5449
 
5450
                    // We need to check all the question_set_references belonging to this context_module.
5451
                    $references = $DB->get_records('question_set_references', ['usingcontextid' => $newcontext->newitemid]);
5452
                    foreach ($references as $reference) {
5453
                        $filtercondition = json_decode($reference->filtercondition);
5454
                        if (!empty($filtercondition->questioncategoryid) &&
5455
                                in_array($filtercondition->questioncategoryid, $categoryids)) {
5456
                            // This is one of ours, update the questionscontextid.
5457
                            $DB->set_field('question_set_references',
5458
                                'questionscontextid', $newcontext->newitemid,
5459
                                ['id' => $reference->id]);
5460
                        }
5461
                    }
5462
                }
5463
 
5464
                // Now set the parent id for the question categories that were in the top category in the course context
5465
                // and have been moved now.
5466
                if ($oldtopid) {
5467
                    $DB->set_field('question_categories', 'parent', $top->id,
5468
                            array('contextid' => $newcontext->newitemid, 'parent' => $oldtopid));
5469
                }
5470
            }
5471
        }
5472
    }
5473
}
5474
 
5475
/**
5476
 * Execution step that will create all the question/answers/qtype-specific files for the restored
5477
 * questions. It must be executed after {@link restore_move_module_questions_categories}
5478
 * because only then each question is in its final category and only then the
5479
 * contexts can be determined.
5480
 */
5481
class restore_create_question_files extends restore_execution_step {
5482
 
5483
    /** @var array Question-type specific component items cache. */
5484
    private $qtypecomponentscache = array();
5485
 
5486
    /**
5487
     * Preform the restore_create_question_files step.
5488
     */
5489
    protected function define_execution() {
5490
        global $DB;
5491
 
5492
        // Track progress, as this task can take a long time.
5493
        $progress = $this->task->get_progress();
5494
        $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
5495
 
5496
        // Parentitemids of question_createds in backup_ids_temp are the category it is in.
5497
        // MUST use a recordset, as there is no unique key in the first (or any) column.
5498
        $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
5499
                                                   FROM {backup_ids_temp} bi
5500
                                                   JOIN {question} q ON q.id = bi.newitemid
5501
                                                  WHERE bi.backupid = ?
5502
                                                        AND bi.itemname = 'question_created'
5503
                                               ORDER BY categoryid ASC", array($this->get_restoreid()));
5504
 
5505
        $currentcatid = -1;
5506
        foreach ($catqtypes as $categoryid => $row) {
5507
            $qtype = $row->qtype;
5508
 
5509
            // Check if we are in a new category.
5510
            if ($currentcatid !== $categoryid) {
5511
                // Report progress for each category.
5512
                $progress->progress();
5513
 
5514
                if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
5515
                        'question_category', $categoryid)) {
5516
                    // Something went really wrong, cannot find the question_category for the question_created records.
5517
                    debugging('Error fetching target context for question', DEBUG_DEVELOPER);
5518
                    continue;
5519
                }
5520
 
5521
                // Calculate source and target contexts.
5522
                $oldctxid = $qcatmapping->info->contextid;
5523
                $newctxid = $qcatmapping->parentitemid;
5524
 
5525
                $this->send_common_files($oldctxid, $newctxid, $progress);
5526
                $currentcatid = $categoryid;
5527
            }
5528
 
5529
            $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
5530
        }
5531
        $catqtypes->close();
5532
        $progress->end_progress();
5533
    }
5534
 
5535
    /**
5536
     * Send the common question files to a new context.
5537
     *
5538
     * @param int             $oldctxid Old context id.
5539
     * @param int             $newctxid New context id.
5540
     * @param \core\progress\base  $progress Progress object to use.
5541
     */
5542
    private function send_common_files($oldctxid, $newctxid, $progress) {
5543
        // Add common question files (question and question_answer ones).
5544
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
5545
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5546
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
5547
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5548
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
5549
                $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5550
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
5551
                $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5552
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
5553
                $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
5554
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
5555
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5556
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
5557
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5558
        restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
5559
                $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5560
    }
5561
 
5562
    /**
5563
     * Send the question type specific files to a new context.
5564
     *
5565
     * @param text            $qtype The qtype name to send.
5566
     * @param int             $oldctxid Old context id.
5567
     * @param int             $newctxid New context id.
5568
     * @param \core\progress\base  $progress Progress object to use.
5569
     */
5570
    private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
5571
        if (!isset($this->qtypecomponentscache[$qtype])) {
5572
            $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
5573
        }
5574
        $components = $this->qtypecomponentscache[$qtype];
5575
        foreach ($components as $component => $fileareas) {
5576
            foreach ($fileareas as $filearea => $mapping) {
5577
                restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
5578
                        $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
5579
            }
5580
        }
5581
    }
5582
}
5583
 
5584
/**
5585
 * Try to restore aliases and references to external files.
5586
 *
5587
 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
5588
 * We expect that all regular (non-alias) files have already been restored. Make sure
5589
 * there is no restore step executed after this one that would call send_files_to_pool() again.
5590
 *
5591
 * You may notice we have hardcoded support for Server files, Legacy course files
5592
 * and user Private files here at the moment. This could be eventually replaced with a set of
5593
 * callbacks in the future if needed.
5594
 *
5595
 * @copyright 2012 David Mudrak <david@moodle.com>
5596
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5597
 */
5598
class restore_process_file_aliases_queue extends restore_execution_step {
5599
 
5600
    /** @var array internal cache for {@link choose_repository()} */
5601
    private $cachereposbyid = array();
5602
 
5603
    /** @var array internal cache for {@link choose_repository()} */
5604
    private $cachereposbytype = array();
5605
 
5606
    /**
5607
     * What to do when this step is executed.
5608
     */
5609
    protected function define_execution() {
5610
        global $DB;
5611
 
5612
        $fs = get_file_storage();
5613
 
5614
        // Load the queue.
5615
        $aliascount = $DB->count_records('backup_ids_temp',
5616
            ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue']);
5617
        $rs = $DB->get_recordset('backup_ids_temp',
5618
            ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'],
5619
            '', 'info');
5620
 
5621
        $this->log('processing file aliases queue. ' . $aliascount . ' entries.', backup::LOG_DEBUG);
5622
        $progress = $this->task->get_progress();
5623
        $progress->start_progress('Processing file aliases queue', $aliascount);
5624
 
5625
        // Iterate over aliases in the queue.
5626
        foreach ($rs as $record) {
5627
            $progress->increment_progress();
5628
            $info = backup_controller_dbops::decode_backup_temp_info($record->info);
5629
 
5630
            // Try to pick a repository instance that should serve the alias.
5631
            $repository = $this->choose_repository($info);
5632
 
5633
            if (is_null($repository)) {
5634
                $this->notify_failure($info, 'unable to find a matching repository instance');
5635
                continue;
5636
            }
5637
 
5638
            if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5639
                    || $info->oldfile->repositorytype === 'contentbank') {
5640
                // Aliases to Server files and Legacy course files may refer to a file
5641
                // contained in the backup file or to some existing file (if we are on the
5642
                // same site).
5643
                try {
5644
                    $reference = file_storage::unpack_reference($info->oldfile->reference);
5645
                } catch (Exception $e) {
5646
                    $this->notify_failure($info, 'invalid reference field format');
5647
                    continue;
5648
                }
5649
 
5650
                // Let's see if the referred source file was also included in the backup.
5651
                $candidates = $DB->get_recordset('backup_files_temp', array(
5652
                        'backupid' => $this->get_restoreid(),
5653
                        'contextid' => $reference['contextid'],
5654
                        'component' => $reference['component'],
5655
                        'filearea' => $reference['filearea'],
5656
                        'itemid' => $reference['itemid'],
5657
                    ), '', 'info, newcontextid, newitemid');
5658
 
5659
                $source = null;
5660
 
5661
                foreach ($candidates as $candidate) {
5662
                    $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
5663
                    if ($candidateinfo->filename === $reference['filename']
5664
                            and $candidateinfo->filepath === $reference['filepath']
5665
                            and !is_null($candidate->newcontextid)
5666
                            and !is_null($candidate->newitemid) ) {
5667
                        $source = $candidateinfo;
5668
                        $source->contextid = $candidate->newcontextid;
5669
                        $source->itemid = $candidate->newitemid;
5670
                        break;
5671
                    }
5672
                }
5673
                $candidates->close();
5674
 
5675
                if ($source) {
5676
                    // We have an alias that refers to another file also included in
5677
                    // the backup. Let us change the reference field so that it refers
5678
                    // to the restored copy of the original file.
5679
                    $reference = file_storage::pack_reference($source);
5680
 
5681
                    // Send the new alias to the filepool.
5682
                    $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5683
                    $this->notify_success($info);
5684
                    continue;
5685
 
5686
                } else {
5687
                    // This is a reference to some moodle file that was not contained in the backup
5688
                    // file. If we are restoring to the same site, keep the reference untouched
5689
                    // and restore the alias as is if the referenced file exists.
5690
                    if ($this->task->is_samesite()) {
5691
                        if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5692
                                $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5693
                            $reference = file_storage::pack_reference($reference);
5694
                            $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5695
                            $this->notify_success($info);
5696
                            continue;
5697
                        } else {
5698
                            $this->notify_failure($info, 'referenced file not found');
5699
                            continue;
5700
                        }
5701
 
5702
                    // If we are at other site, we can't restore this alias.
5703
                    } else {
5704
                        $this->notify_failure($info, 'referenced file not included');
5705
                        continue;
5706
                    }
5707
                }
5708
 
5709
            } else if ($info->oldfile->repositorytype === 'user') {
5710
                if ($this->task->is_samesite()) {
5711
                    // For aliases to user Private files at the same site, we have a chance to check
5712
                    // if the referenced file still exists.
5713
                    try {
5714
                        $reference = file_storage::unpack_reference($info->oldfile->reference);
5715
                    } catch (Exception $e) {
5716
                        $this->notify_failure($info, 'invalid reference field format');
5717
                        continue;
5718
                    }
5719
                    if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5720
                            $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5721
                        $reference = file_storage::pack_reference($reference);
5722
                        $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5723
                        $this->notify_success($info);
5724
                        continue;
5725
                    } else {
5726
                        $this->notify_failure($info, 'referenced file not found');
5727
                        continue;
5728
                    }
5729
 
5730
                // If we are at other site, we can't restore this alias.
5731
                } else {
5732
                    $this->notify_failure($info, 'restoring at another site');
5733
                    continue;
5734
                }
5735
 
5736
            } else {
5737
                // This is a reference to some external file such as dropbox.
5738
                // If we are restoring to the same site, keep the reference untouched and
5739
                // restore the alias as is.
5740
                if ($this->task->is_samesite()) {
5741
                    $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
5742
                    $this->notify_success($info);
5743
                    continue;
5744
 
5745
                // If we are at other site, we can't restore this alias.
5746
                } else {
5747
                    $this->notify_failure($info, 'restoring at another site');
5748
                    continue;
5749
                }
5750
            }
5751
        }
5752
        $progress->end_progress();
5753
        $rs->close();
5754
    }
5755
 
5756
    /**
5757
     * Choose the repository instance that should handle the alias.
5758
     *
5759
     * At the same site, we can rely on repository instance id and we just
5760
     * check it still exists. On other site, try to find matching Server files or
5761
     * Legacy course files repository instance. Return null if no matching
5762
     * repository instance can be found.
5763
     *
5764
     * @param stdClass $info
5765
     * @return repository|null
5766
     */
5767
    private function choose_repository(stdClass $info) {
5768
        global $DB, $CFG;
5769
        require_once($CFG->dirroot.'/repository/lib.php');
5770
 
5771
        if ($this->task->is_samesite()) {
5772
            // We can rely on repository instance id.
5773
 
5774
            if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
5775
                return $this->cachereposbyid[$info->oldfile->repositoryid];
5776
            }
5777
 
5778
            $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
5779
 
5780
            try {
5781
                $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
5782
                return $this->cachereposbyid[$info->oldfile->repositoryid];
5783
            } catch (Exception $e) {
5784
                $this->cachereposbyid[$info->oldfile->repositoryid] = null;
5785
                return null;
5786
            }
5787
 
5788
        } else {
5789
            // We can rely on repository type only.
5790
 
5791
            if (empty($info->oldfile->repositorytype)) {
5792
                return null;
5793
            }
5794
 
5795
            if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
5796
                return $this->cachereposbytype[$info->oldfile->repositorytype];
5797
            }
5798
 
5799
            $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
5800
 
5801
            // Both Server files and Legacy course files repositories have a single
5802
            // instance at the system context to use. Let us try to find it.
5803
            if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5804
                    || $info->oldfile->repositorytype === 'contentbank') {
5805
                $sql = "SELECT ri.id
5806
                          FROM {repository} r
5807
                          JOIN {repository_instances} ri ON ri.typeid = r.id
5808
                         WHERE r.type = ? AND ri.contextid = ?";
5809
                $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
5810
                if (empty($ris)) {
5811
                    return null;
5812
                }
5813
                $repoids = array_keys($ris);
5814
                $repoid = reset($repoids);
5815
                try {
5816
                    $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
5817
                    return $this->cachereposbytype[$info->oldfile->repositorytype];
5818
                } catch (Exception $e) {
5819
                    $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5820
                    return null;
5821
                }
5822
            }
5823
 
5824
            $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5825
            return null;
5826
        }
5827
    }
5828
 
5829
    /**
5830
     * Let the user know that the given alias was successfully restored
5831
     *
5832
     * @param stdClass $info
5833
     */
5834
    private function notify_success(stdClass $info) {
5835
        $filedesc = $this->describe_alias($info);
5836
        $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
5837
    }
5838
 
5839
    /**
5840
     * Let the user know that the given alias can't be restored
5841
     *
5842
     * @param stdClass $info
5843
     * @param string $reason detailed reason to be logged
5844
     */
5845
    private function notify_failure(stdClass $info, $reason = '') {
5846
        $filedesc = $this->describe_alias($info);
5847
        if ($reason) {
5848
            $reason = ' ('.$reason.')';
5849
        }
5850
        $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
5851
        $this->add_result_item('file_aliases_restore_failures', $filedesc);
5852
    }
5853
 
5854
    /**
5855
     * Return a human readable description of the alias file
5856
     *
5857
     * @param stdClass $info
5858
     * @return string
5859
     */
5860
    private function describe_alias(stdClass $info) {
5861
 
5862
        $filedesc = $this->expected_alias_location($info->newfile);
5863
 
5864
        if (!is_null($info->oldfile->source)) {
5865
            $filedesc .= ' ('.$info->oldfile->source.')';
5866
        }
5867
 
5868
        return $filedesc;
5869
    }
5870
 
5871
    /**
5872
     * Return the expected location of a file
5873
     *
5874
     * Please note this may and may not work as a part of URL to pluginfile.php
5875
     * (depends on how the given component/filearea deals with the itemid).
5876
     *
5877
     * @param stdClass $filerecord
5878
     * @return string
5879
     */
5880
    private function expected_alias_location($filerecord) {
5881
 
5882
        $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
5883
        if (!is_null($filerecord->itemid)) {
5884
            $filedesc .= '/'.$filerecord->itemid;
5885
        }
5886
        $filedesc .= $filerecord->filepath.$filerecord->filename;
5887
 
5888
        return $filedesc;
5889
    }
5890
 
5891
    /**
5892
     * Append a value to the given resultset
5893
     *
5894
     * @param string $name name of the result containing a list of values
5895
     * @param mixed $value value to add as another item in that result
5896
     */
5897
    private function add_result_item($name, $value) {
5898
 
5899
        $results = $this->task->get_results();
5900
 
5901
        if (isset($results[$name])) {
5902
            if (!is_array($results[$name])) {
5903
                throw new coding_exception('Unable to append a result item into a non-array structure.');
5904
            }
5905
            $current = $results[$name];
5906
            $current[] = $value;
5907
            $this->task->add_result(array($name => $current));
5908
 
5909
        } else {
5910
            $this->task->add_result(array($name => array($value)));
5911
        }
5912
    }
5913
}
5914
 
5915
 
5916
/**
5917
 * Helper code for use by any plugin that stores question attempt data that it needs to back up.
5918
 */
5919
trait restore_questions_attempt_data_trait {
5920
    /** @var array question_attempt->id to qtype. */
5921
    protected $qtypes = array();
5922
    /** @var array question_attempt->id to questionid. */
5923
    protected $newquestionids = array();
5924
 
5925
    /**
5926
     * Attach below $element (usually attempts) the needed restore_path_elements
5927
     * to restore question_usages and all they contain.
5928
     *
5929
     * If you use the $nameprefix parameter, then you will need to implement some
5930
     * extra methods in your class, like
5931
     *
5932
     * protected function process_{nameprefix}question_attempt($data) {
5933
     *     $this->restore_question_usage_worker($data, '{nameprefix}');
5934
     * }
5935
     * protected function process_{nameprefix}question_attempt($data) {
5936
     *     $this->restore_question_attempt_worker($data, '{nameprefix}');
5937
     * }
5938
     * protected function process_{nameprefix}question_attempt_step($data) {
5939
     *     $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5940
     * }
5941
     *
5942
     * @param restore_path_element $element the parent element that the usages are stored inside.
5943
     * @param array $paths the paths array that is being built.
5944
     * @param string $nameprefix should match the prefix passed to the corresponding
5945
     *      backup_questions_activity_structure_step::add_question_usages call.
5946
     */
5947
    protected function add_question_usages($element, &$paths, $nameprefix = '') {
5948
        // Check $element is restore_path_element
5949
        if (! $element instanceof restore_path_element) {
5950
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
5951
        }
5952
 
5953
        // Check $paths is one array
5954
        if (!is_array($paths)) {
5955
            throw new restore_step_exception('paths_must_be_array', $paths);
5956
        }
5957
        $paths[] = new restore_path_element($nameprefix . 'question_usage',
5958
                $element->get_path() . "/{$nameprefix}question_usage");
5959
        $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5960
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5961
        $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5962
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5963
                true);
5964
        $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5965
                $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5966
    }
5967
 
5968
    /**
5969
     * Process question_usages
5970
     */
5971
    public function process_question_usage($data) {
5972
        $this->restore_question_usage_worker($data, '');
5973
    }
5974
 
5975
    /**
5976
     * Process question_attempts
5977
     */
5978
    public function process_question_attempt($data) {
5979
        $this->restore_question_attempt_worker($data, '');
5980
    }
5981
 
5982
    /**
5983
     * Process question_attempt_steps
5984
     */
5985
    public function process_question_attempt_step($data) {
5986
        $this->restore_question_attempt_step_worker($data, '');
5987
    }
5988
 
5989
    /**
5990
     * This method does the actual work for process_question_usage or
5991
     * process_{nameprefix}_question_usage.
5992
     * @param array $data the data from the XML file.
5993
     * @param string $nameprefix the element name prefix.
5994
     */
5995
    protected function restore_question_usage_worker($data, $nameprefix) {
5996
        global $DB;
5997
 
5998
        // Clear our caches.
5999
        $this->qtypes = array();
6000
        $this->newquestionids = array();
6001
 
6002
        $data = (object)$data;
6003
        $oldid = $data->id;
6004
 
6005
        $data->contextid  = $this->task->get_contextid();
6006
 
6007
        // Everything ready, insert (no mapping needed)
6008
        $newitemid = $DB->insert_record('question_usages', $data);
6009
 
6010
        $this->inform_new_usage_id($newitemid);
6011
 
6012
        $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
6013
    }
6014
 
6015
    /**
6016
     * When process_question_usage creates the new usage, it calls this method
6017
     * to let the activity link to the new usage. For example, the quiz uses
6018
     * this method to set quiz_attempts.uniqueid to the new usage id.
6019
     * @param integer $newusageid
6020
     */
6021
    abstract protected function inform_new_usage_id($newusageid);
6022
 
6023
    /**
6024
     * This method does the actual work for process_question_attempt or
6025
     * process_{nameprefix}_question_attempt.
6026
     * @param array $data the data from the XML file.
6027
     * @param string $nameprefix the element name prefix.
6028
     */
6029
    protected function restore_question_attempt_worker($data, $nameprefix) {
6030
        global $DB;
6031
 
6032
        $data = (object)$data;
6033
        $oldid = $data->id;
6034
 
6035
        $questioncreated = $this->get_mappingid('question_created', $data->questionid) ? true : false;
6036
        $question = $this->get_mapping('question', $data->questionid);
6037
        if ($questioncreated) {
6038
            $data->questionid = $question->newitemid;
6039
        }
6040
 
6041
        $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
6042
 
6043
        if (!property_exists($data, 'variant')) {
6044
            $data->variant = 1;
6045
        }
6046
 
6047
        if (!property_exists($data, 'maxfraction')) {
6048
            $data->maxfraction = 1;
6049
        }
6050
 
6051
        $newitemid = $DB->insert_record('question_attempts', $data);
6052
 
6053
        $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
6054
        if (isset($question->info->qtype)) {
6055
            $qtype = $question->info->qtype;
6056
        } else {
6057
            $qtype = $DB->get_record('question', ['id' => $data->questionid])->qtype;
6058
        }
6059
        $this->qtypes[$newitemid] = $qtype;
6060
        $this->newquestionids[$newitemid] = $data->questionid;
6061
    }
6062
 
6063
    /**
6064
     * This method does the actual work for process_question_attempt_step or
6065
     * process_{nameprefix}_question_attempt_step.
6066
     * @param array $data the data from the XML file.
6067
     * @param string $nameprefix the element name prefix.
6068
     */
6069
    protected function restore_question_attempt_step_worker($data, $nameprefix) {
6070
        global $DB;
6071
 
6072
        $data = (object)$data;
6073
        $oldid = $data->id;
6074
 
6075
        // Pull out the response data.
6076
        $response = array();
6077
        if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
6078
            foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
6079
                $response[$variable['name']] = $variable['value'];
6080
            }
6081
        }
6082
        unset($data->response);
6083
 
6084
        $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
6085
        $data->userid = $this->get_mappingid('user', $data->userid);
6086
 
6087
        // Everything ready, insert and create mapping (needed by question_sessions)
6088
        $newitemid = $DB->insert_record('question_attempt_steps', $data);
6089
        $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
6090
 
6091
        // Now process the response data.
6092
        $response = $this->questions_recode_response_data(
6093
                $this->qtypes[$data->questionattemptid],
6094
                $this->newquestionids[$data->questionattemptid],
6095
                $data->sequencenumber, $response);
6096
 
6097
        foreach ($response as $name => $value) {
6098
            $row = new stdClass();
6099
            $row->attemptstepid = $newitemid;
6100
            $row->name = $name;
6101
            $row->value = $value;
6102
            $DB->insert_record('question_attempt_step_data', $row, false);
6103
        }
6104
    }
6105
 
6106
    /**
6107
     * Recode the respones data for a particular step of an attempt at at particular question.
6108
     * @param string $qtype the question type.
6109
     * @param int $newquestionid the question id.
6110
     * @param int $sequencenumber the sequence number.
6111
     * @param array $response the response data to recode.
6112
     */
6113
    public function questions_recode_response_data(
6114
            $qtype, $newquestionid, $sequencenumber, array $response) {
6115
        $qtyperestorer = $this->get_qtype_restorer($qtype);
6116
        if ($qtyperestorer) {
6117
            $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
6118
        }
6119
        return $response;
6120
    }
6121
 
6122
    /**
6123
     * Given a list of question->ids, separated by commas, returns the
6124
     * recoded list, with all the restore question mappings applied.
6125
     * Note: Used by quiz->questions and quiz_attempts->layout
6126
     * Note: 0 = page break (unconverted)
6127
     */
6128
    protected function questions_recode_layout($layout) {
6129
        // Extracts question id from sequence
6130
        if ($questionids = explode(',', $layout)) {
6131
            foreach ($questionids as $id => $questionid) {
6132
                if ($questionid) { // If it is zero then this is a pagebreak, don't translate
6133
                    $newquestionid = $this->get_mappingid('question', $questionid);
6134
                    $questionids[$id] = $newquestionid;
6135
                }
6136
            }
6137
        }
6138
        return implode(',', $questionids);
6139
    }
6140
 
6141
    /**
6142
     * Get the restore_qtype_plugin subclass for a specific question type.
6143
     * @param string $qtype e.g. multichoice.
6144
     * @return restore_qtype_plugin instance.
6145
     */
6146
    protected function get_qtype_restorer($qtype) {
6147
        // Build one static cache to store {@link restore_qtype_plugin}
6148
        // while we are needing them, just to save zillions of instantiations
6149
        // or using static stuff that will break our nice API
6150
        static $qtypeplugins = array();
6151
 
6152
        if (!isset($qtypeplugins[$qtype])) {
6153
            $classname = 'restore_qtype_' . $qtype . '_plugin';
6154
            if (class_exists($classname)) {
6155
                $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
6156
            } else {
6157
                $qtypeplugins[$qtype] = null;
6158
            }
6159
        }
6160
        return $qtypeplugins[$qtype];
6161
    }
6162
 
6163
    protected function after_execute() {
6164
        parent::after_execute();
6165
 
6166
        // Restore any files belonging to responses.
6167
        foreach (question_engine::get_all_response_file_areas() as $filearea) {
6168
            $this->add_related_files('question', $filearea, 'question_attempt_step');
6169
        }
6170
    }
6171
}
6172
 
6173
/**
6174
 * Helper trait to restore question reference data.
6175
 */
6176
trait restore_question_reference_data_trait {
6177
 
6178
    /**
6179
     * Attach the question reference data to the restore.
6180
     *
6181
     * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6182
     * @param array $paths the paths array that is being built to describe the structure.
6183
     */
6184
    protected function add_question_references($element, &$paths) {
6185
        // Check $element is restore_path_element.
6186
        if (! $element instanceof restore_path_element) {
6187
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
6188
        }
6189
 
6190
        // Check $paths is one array.
6191
        if (!is_array($paths)) {
6192
            throw new restore_step_exception('paths_must_be_array', $paths);
6193
        }
6194
 
6195
        $paths[] = new restore_path_element('question_reference',
6196
            $element->get_path() . '/question_reference');
6197
    }
6198
 
6199
    /**
6200
     * Process question references which replaces the direct connection to quiz slots to question.
6201
     *
6202
     * @param array $data the data from the XML file.
6203
     */
6204
    public function process_question_reference($data) {
6205
        global $DB;
6206
        $data = (object) $data;
6207
        $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6208
        $data->itemid = $this->get_new_parentid('quiz_question_instance');
6209
        if ($entry = $this->get_mappingid('question_bank_entry', $data->questionbankentryid)) {
6210
            $data->questionbankentryid = $entry;
6211
        }
6212
        $DB->insert_record('question_references', $data);
6213
    }
6214
}
6215
 
6216
/**
6217
 * Helper trait to restore question set reference data.
6218
 */
6219
trait restore_question_set_reference_data_trait {
6220
 
6221
    /**
6222
     * Attach the question reference data to the restore.
6223
     *
6224
     * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6225
     * @param array $paths the paths array that is being built to describe the structure.
6226
     */
6227
    protected function add_question_set_references($element, &$paths) {
6228
        // Check $element is restore_path_element.
6229
        if (! $element instanceof restore_path_element) {
6230
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
6231
        }
6232
 
6233
        // Check $paths is one array.
6234
        if (!is_array($paths)) {
6235
            throw new restore_step_exception('paths_must_be_array', $paths);
6236
        }
6237
 
6238
        $paths[] = new restore_path_element('question_set_reference',
6239
            $element->get_path() . '/question_set_reference');
6240
    }
6241
 
6242
    /**
6243
     * Process question set references data which replaces the random qtype.
6244
     *
6245
     * @param array $data the data from the XML file.
6246
     */
6247
    public function process_question_set_reference($data) {
6248
        global $DB;
6249
        $data = (object) $data;
6250
        $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6251
        $data->itemid = $this->get_new_parentid('quiz_question_instance');
6252
        $filtercondition = json_decode($data->filtercondition, true);
6253
 
6254
        if (!isset($filtercondition['filter'])) {
6255
            // Pre-4.3, convert the old filtercondition format to the new format.
6256
            $filtercondition = \core_question\question_reference_manager::convert_legacy_set_reference_filter_condition(
6257
                    $filtercondition);
6258
        }
6259
 
6260
        // Map category id used for category filter condition and corresponding context id.
6261
        $oldcategoryid = $filtercondition['filter']['category']['values'][0];
6262
        $newcategoryid = $this->get_mappingid('question_category', $oldcategoryid);
6263
        $filtercondition['filter']['category']['values'][0] = $newcategoryid;
6264
 
6265
        if ($context = $this->get_mappingid('context', $data->questionscontextid)) {
6266
            $data->questionscontextid = $context;
6267
        } else {
6268
            $this->log('question_set_reference with old id ' . $data->id .
6269
                ' referenced question context ' . $data->questionscontextid .
6270
                ' which was not included in the backup. Therefore, this has been ' .
6271
                ' restored with the old questionscontextid.', backup::LOG_WARNING);
6272
        }
6273
 
6274
        $filtercondition['cat'] = implode(',', [
6275
            $filtercondition['filter']['category']['values'][0],
6276
            $data->questionscontextid,
6277
        ]);
6278
 
6279
        $data->filtercondition = json_encode($filtercondition);
6280
 
6281
        $DB->insert_record('question_set_references', $data);
6282
    }
6283
}
6284
 
6285
 
6286
/**
6287
 * Abstract structure step to help activities that store question attempt data.
6288
 *
6289
 * @copyright 2011 The Open University
6290
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6291
 */
6292
abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
6293
    use restore_questions_attempt_data_trait;
6294
    use restore_question_reference_data_trait;
6295
    use restore_question_set_reference_data_trait;
6296
 
6297
    /** @var \question_engine_attempt_upgrader manages upgrading all the question attempts. */
6298
    private $attemptupgrader;
6299
 
6300
    /**
6301
     * Attach below $element (usually attempts) the needed restore_path_elements
6302
     * to restore question attempt data from Moodle 2.0.
6303
     *
6304
     * When using this method, the parent element ($element) must be defined with
6305
     * $grouped = true. Then, in that elements process method, you must call
6306
     * {@link process_legacy_attempt_data()} with the groupded data. See, for
6307
     * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
6308
     * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6309
     * @param array $paths the paths array that is being built to describe the
6310
     *      structure.
6311
     */
6312
    protected function add_legacy_question_attempt_data($element, &$paths) {
6313
        global $CFG;
6314
        require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
6315
 
6316
        // Check $element is restore_path_element
6317
        if (!($element instanceof restore_path_element)) {
6318
            throw new restore_step_exception('element_must_be_restore_path_element', $element);
6319
        }
6320
        // Check $paths is one array
6321
        if (!is_array($paths)) {
6322
            throw new restore_step_exception('paths_must_be_array', $paths);
6323
        }
6324
 
6325
        $paths[] = new restore_path_element('question_state',
6326
                $element->get_path() . '/states/state');
6327
        $paths[] = new restore_path_element('question_session',
6328
                $element->get_path() . '/sessions/session');
6329
    }
6330
 
6331
    protected function get_attempt_upgrader() {
6332
        if (empty($this->attemptupgrader)) {
6333
            $this->attemptupgrader = new question_engine_attempt_upgrader();
6334
            $this->attemptupgrader->prepare_to_restore();
6335
        }
6336
        return $this->attemptupgrader;
6337
    }
6338
 
6339
    /**
6340
     * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
6341
     * @param object $data contains all the grouped attempt data to process.
6342
     * @param object $quiz data about the activity the attempts belong to. Required
6343
     * fields are (basically this only works for the quiz module):
6344
     *      oldquestions => list of question ids in this activity - using old ids.
6345
     *      preferredbehaviour => the behaviour to use for questionattempts.
6346
     */
6347
    protected function process_legacy_quiz_attempt_data($data, $quiz) {
6348
        global $DB;
6349
        $upgrader = $this->get_attempt_upgrader();
6350
 
6351
        $data = (object)$data;
6352
 
6353
        $layout = explode(',', $data->layout);
6354
        $newlayout = $layout;
6355
 
6356
        // Convert each old question_session into a question_attempt.
6357
        $qas = array();
6358
        foreach (explode(',', $quiz->oldquestions) as $questionid) {
6359
            if ($questionid == 0) {
6360
                continue;
6361
            }
6362
 
6363
            $newquestionid = $this->get_mappingid('question', $questionid);
6364
            if (!$newquestionid) {
6365
                throw new restore_step_exception('questionattemptreferstomissingquestion',
6366
                        $questionid, $questionid);
6367
            }
6368
 
6369
            $question = $upgrader->load_question($newquestionid, $quiz->id);
6370
 
6371
            foreach ($layout as $key => $qid) {
6372
                if ($qid == $questionid) {
6373
                    $newlayout[$key] = $newquestionid;
6374
                }
6375
            }
6376
 
6377
            list($qsession, $qstates) = $this->find_question_session_and_states(
6378
                    $data, $questionid);
6379
 
6380
            if (empty($qsession) || empty($qstates)) {
6381
                throw new restore_step_exception('questionattemptdatamissing',
6382
                        $questionid, $questionid);
6383
            }
6384
 
6385
            list($qsession, $qstates) = $this->recode_legacy_response_data(
6386
                    $question, $qsession, $qstates);
6387
 
6388
            $data->layout = implode(',', $newlayout);
6389
            $qas[$newquestionid] = $upgrader->convert_question_attempt(
6390
                    $quiz, $data, $question, $qsession, $qstates);
6391
        }
6392
 
6393
        // Now create a new question_usage.
6394
        $usage = new stdClass();
6395
        $usage->component = 'mod_quiz';
6396
        $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
6397
        $usage->preferredbehaviour = $quiz->preferredbehaviour;
6398
        $usage->id = $DB->insert_record('question_usages', $usage);
6399
 
6400
        $this->inform_new_usage_id($usage->id);
6401
 
6402
        $data->uniqueid = $usage->id;
6403
        $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
6404
                $this->questions_recode_layout($quiz->oldquestions));
6405
    }
6406
 
6407
    protected function find_question_session_and_states($data, $questionid) {
6408
        $qsession = null;
6409
        foreach ($data->sessions['session'] as $session) {
6410
            if ($session['questionid'] == $questionid) {
6411
                $qsession = (object) $session;
6412
                break;
6413
            }
6414
        }
6415
 
6416
        $qstates = array();
6417
        foreach ($data->states['state'] as $state) {
6418
            if ($state['question'] == $questionid) {
6419
                // It would be natural to use $state['seq_number'] as the array-key
6420
                // here, but it seems that buggy behaviour in 2.0 and early can
6421
                // mean that that is not unique, so we use id, which is guaranteed
6422
                // to be unique.
6423
                $qstates[$state['id']] = (object) $state;
6424
            }
6425
        }
6426
        ksort($qstates);
6427
        $qstates = array_values($qstates);
6428
 
6429
        return array($qsession, $qstates);
6430
    }
6431
 
6432
    /**
6433
     * Recode any ids in the response data
6434
     * @param object $question the question data
6435
     * @param object $qsession the question sessions.
6436
     * @param array $qstates the question states.
6437
     */
6438
    protected function recode_legacy_response_data($question, $qsession, $qstates) {
6439
        $qsession->questionid = $question->id;
6440
 
6441
        foreach ($qstates as &$state) {
6442
            $state->question = $question->id;
6443
            $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
6444
        }
6445
 
6446
        return array($qsession, $qstates);
6447
    }
6448
 
6449
    /**
6450
     * Recode the legacy answer field.
6451
     * @param object $state the state to recode the answer of.
6452
     * @param string $qtype the question type.
6453
     */
6454
    public function restore_recode_legacy_answer($state, $qtype) {
6455
        $restorer = $this->get_qtype_restorer($qtype);
6456
        if ($restorer) {
6457
            return $restorer->recode_legacy_state_answer($state);
6458
        } else {
6459
            return $state->answer;
6460
        }
6461
    }
6462
}
6463
 
6464
 
6465
/**
6466
 * Restore completion defaults for each module type
6467
 *
6468
 * @package     core_backup
6469
 * @copyright   2017 Marina Glancy
6470
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6471
 */
6472
class restore_completion_defaults_structure_step extends restore_structure_step {
6473
    /**
6474
     * To conditionally decide if this step must be executed.
6475
     */
6476
    protected function execute_condition() {
6477
        // No completion on the front page.
6478
        if ($this->get_courseid() == SITEID) {
6479
            return false;
6480
        }
6481
 
6482
        // No default completion info found, don't execute.
6483
        $fullpath = $this->task->get_taskbasepath();
6484
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
6485
        if (!file_exists($fullpath)) {
6486
            return false;
6487
        }
6488
 
6489
        // Arrived here, execute the step.
6490
        return true;
6491
    }
6492
 
6493
    /**
6494
     * Function that will return the structure to be processed by this restore_step.
6495
     *
6496
     * @return restore_path_element[]
6497
     */
6498
    protected function define_structure() {
6499
        return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
6500
    }
6501
 
6502
    /**
6503
     * Processor for path element 'completion_defaults'
6504
     *
6505
     * @param stdClass|array $data
6506
     */
6507
    protected function process_completion_defaults($data) {
6508
        global $DB;
6509
 
6510
        $data = (array)$data;
6511
        $oldid = $data['id'];
6512
        unset($data['id']);
6513
 
6514
        // Find the module by name since id may be different in another site.
6515
        if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
6516
            return;
6517
        }
6518
        unset($data['modulename']);
6519
 
6520
        // Find the existing record.
6521
        $newid = $DB->get_field('course_completion_defaults', 'id',
6522
            ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
6523
        if (!$newid) {
6524
            $newid = $DB->insert_record('course_completion_defaults',
6525
                ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
6526
        } else {
6527
            $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
6528
        }
6529
 
6530
        // Save id mapping for restoring associated events.
6531
        $this->set_mapping('course_completion_defaults', $oldid, $newid);
6532
    }
6533
}
6534
 
6535
/**
6536
 * Index course after restore.
6537
 *
6538
 * @package core_backup
6539
 * @copyright 2017 The Open University
6540
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6541
 */
6542
class restore_course_search_index extends restore_execution_step {
6543
    /**
6544
     * When this step is executed, we add the course context to the queue for reindexing.
6545
     */
6546
    protected function define_execution() {
6547
        $context = \context_course::instance($this->task->get_courseid());
6548
        \core_search\manager::request_index($context);
6549
    }
6550
}
6551
 
6552
/**
6553
 * Index activity after restore (when not restoring whole course).
6554
 *
6555
 * @package core_backup
6556
 * @copyright 2017 The Open University
6557
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6558
 */
6559
class restore_activity_search_index extends restore_execution_step {
6560
    /**
6561
     * When this step is executed, we add the activity context to the queue for reindexing.
6562
     */
6563
    protected function define_execution() {
6564
        $context = \context::instance_by_id($this->task->get_contextid());
6565
        \core_search\manager::request_index($context);
6566
    }
6567
}
6568
 
6569
/**
6570
 * Index block after restore (when not restoring whole course).
6571
 *
6572
 * @package core_backup
6573
 * @copyright 2017 The Open University
6574
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6575
 */
6576
class restore_block_search_index extends restore_execution_step {
6577
    /**
6578
     * When this step is executed, we add the block context to the queue for reindexing.
6579
     */
6580
    protected function define_execution() {
6581
        // A block in the restore list may be skipped because a duplicate is detected.
6582
        // In this case, there is no new blockid (or context) to get.
6583
        if (!empty($this->task->get_blockid())) {
6584
            $context = \context_block::instance($this->task->get_blockid());
6585
            \core_search\manager::request_index($context);
6586
        }
6587
    }
6588
}
6589
 
6590
/**
6591
 * Restore action events.
6592
 *
6593
 * @package     core_backup
6594
 * @copyright   2017 onwards Ankit Agarwal
6595
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6596
 */
6597
class restore_calendar_action_events extends restore_execution_step {
6598
    /**
6599
     * What to do when this step is executed.
6600
     */
6601
    protected function define_execution() {
6602
        // We just queue the task here rather trying to recreate everything manually.
6603
        // The task will automatically populate all data.
6604
        $task = new \core\task\refresh_mod_calendar_events_task();
6605
        $task->set_custom_data(array('courseid' => $this->get_courseid()));
6606
        \core\task\manager::queue_adhoc_task($task, true);
6607
    }
6608
}