Merge branch 'MDL-81456-main' of https://github.com/andrewnicols/moodle
[moodle.git] / backup / moodle2 / restore_stepslib.php
bloba652f344d59f282dd036ae693977b3b27450817e
1 <?php
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.
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/>.
18 /**
19 * Defines various restore steps that will be used by common tasks in restore
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
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * delete old directories and conditionally create backup_temp_ids table
33 class restore_create_and_clean_temp_stuff extends restore_execution_step {
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();
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);
59 /**
60 * Drop temp ids table and delete the temp dir used by backup/restore (conditionally).
62 class restore_drop_and_clean_temp_stuff extends restore_execution_step {
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();
76 /**
77 * Restore calculated grade items, grade categories etc
79 class restore_gradebook_structure_step extends restore_structure_step {
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...)
87 protected function execute_condition() {
88 global $CFG, $DB;
90 if ($this->get_courseid() == SITEID) {
91 return false;
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;
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;
107 // Some activity has been excluded to be restored, don't execute
108 if ($this->task->is_excluding_activities()) {
109 return false;
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;
122 $restoretask = $this->get_task();
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);
133 // Arrived here, execute the step
134 return true;
137 protected function define_structure() {
138 $paths = array();
139 $userinfo = $this->task->get_setting_value('users');
141 $paths[] = new restore_path_element('attributes', '/gradebook/attributes');
142 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
144 $gradeitem = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
145 $paths[] = $gradeitem;
146 $this->add_plugin_structure('local', $gradeitem);
148 if ($userinfo) {
149 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
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');
154 return $paths;
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);
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']);
172 protected function process_grade_item($data) {
173 global $DB;
175 $data = (object)$data;
177 $oldid = $data->id;
178 $data->course = $this->get_courseid();
180 $data->courseid = $this->get_courseid();
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;
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);
201 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
202 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
204 $data->locktime = $this->apply_date_offset($data->locktime);
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;
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;
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);
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,
236 $newitemid = $DB->get_field('grade_items', 'id', $gi);
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;
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();
250 $this->set_mapping('grade_item', $oldid, $newitemid);
253 protected function process_grade_grade($data) {
254 global $DB;
256 $data = (object)$data;
257 $oldid = $data->id;
258 $olduserid = $data->userid;
260 $data->itemid = $this->get_new_parentid('grade_item');
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);
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);
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);
281 protected function process_grade_category($data) {
282 global $DB;
284 $data = (object)$data;
285 $oldid = $data->id;
287 $data->course = $this->get_courseid();
288 $data->courseid = $data->course;
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;
296 //get the already created course level grade category
297 $category = new stdclass();
298 $category->courseid = $this->get_courseid();
299 $category->parent = null;
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);
308 // Add a warning about a removed setting.
309 if (!empty($data->aggregatesubcats)) {
310 set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
313 //need to insert a course category
314 if (empty($newitemid)) {
315 $newitemid = $DB->insert_record('grade_categories', $data);
317 $this->set_mapping('grade_category', $oldid, $newitemid);
319 protected function process_grade_letter($data) {
320 global $DB;
322 $data = (object)$data;
323 $oldid = $data->id;
325 $data->contextid = context_course::instance($this->get_courseid())->id;
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;
335 $this->set_mapping('grade_letter', $oldid, $newitemid);
337 protected function process_grade_setting($data) {
338 global $DB;
340 $data = (object)$data;
341 $oldid = $data->id;
343 $data->courseid = $this->get_courseid();
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;
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;
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);
365 * put all activity grade items in the correct grade category and mark all for recalculation
367 protected function after_execute() {
368 global $DB;
370 $conditions = array(
371 'backupid' => $this->get_restoreid(),
372 'itemname' => 'grade_item'//,
373 //'itemid' => $itemid
375 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
377 // We need this for calculation magic later on.
378 $mappings = array();
380 if (!empty($rs)) {
381 foreach($rs as $grade_item_backup) {
383 // Store the oldid with the new id.
384 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
386 $updateobj = new stdclass();
387 $updateobj->id = $grade_item_backup->newitemid;
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);
396 } else {
397 //mark course and category items as needing to be recalculated
398 $updateobj->needsupdate=1;
399 $DB->update_record('grade_items', $updateobj);
403 $rs->close();
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;
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;
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++;
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);
450 // Update the calculation now that its being remapped
451 $DB->update_record('grade_items', $gradeitem);
453 $rs->close();
455 // Need to correct the grade category path and parent
456 $conditions = array(
457 'courseid' => $this->get_courseid()
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);
470 $rs->close();
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);
481 $rs->close();
483 // Check what to do with the minmaxtouse setting.
484 $this->check_minmaxtouse();
486 // Freeze gradebook calculations if needed.
487 $this->gradebook_calculation_freeze();
489 // Ensure the module cache is current when recalculating grades.
490 rebuild_course_cache($this->get_courseid(), true);
492 // Restore marks items as needing update. Update everything now.
493 grade_regrade_final_grades($this->get_courseid());
497 * Freeze gradebook calculation if needed.
499 * This is similar to various upgrade scripts that check if the freeze is needed.
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();
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());
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());
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());
530 * Checks what should happen with the course grade setting minmaxtouse.
532 * This is related to the upgrade step at the time the setting was added.
534 * @see MDL-48618
535 * @return void
537 protected function check_minmaxtouse() {
538 global $CFG, $DB;
539 require_once($CFG->libdir . '/gradelib.php');
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;
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;
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);
563 } else if (($version >= $version28start && $version < $version28last) ||
564 ($version >= $version29start && $version < $version29last)) {
565 // They should be using grade_grade when the course has inconsistencies.
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)";
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'))) {
579 // Display the notice as we do during upgrade.
580 set_config('show_min_max_grades_changed_' . $courseid, 1);
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);
589 } else {
590 // This should never happen because from now on minmaxtouse is always saved in backups.
596 * Rewrite step definition to handle the legacy freeze attribute.
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.
602 * We had:
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>
614 * And this method will convert it to:
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>
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.
633 * @param string $filepath The absolute path to the XML file.
634 * @return void
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";
653 fputs($fw, $line);
655 if (!feof($fr)) {
656 throw new restore_step_exception('Error while attempting to rewrite the gradebook step file.');
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.');
663 } else {
664 if ($fr) {
665 fclose($fr);
667 if ($fw) {
668 fclose($fw);
676 * Step in charge of restoring the grade history of a course.
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.
682 class restore_grade_history_structure_step extends restore_structure_step {
684 protected function execute_condition() {
685 global $CFG, $DB;
687 if ($this->get_courseid() == SITEID) {
688 return false;
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;
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;
703 // Some activity has been excluded to be restored, don't execute.
704 if ($this->task->is_excluding_activities()) {
705 return false;
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;
716 // Arrived here, execute the step.
717 return true;
720 protected function define_structure() {
721 $paths = array();
723 // Settings to use.
724 $userinfo = $this->get_setting_value('users');
725 $history = $this->get_setting_value('grade_histories');
727 if ($userinfo && $history) {
728 $paths[] = new restore_path_element('grade_grade',
729 '/grade_history/grade_grades/grade_grade');
732 return $paths;
735 protected function process_grade_grade($data) {
736 global $DB;
738 $data = (object)($data);
739 $olduserid = $data->userid;
740 unset($data->id);
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);
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
763 class restore_decode_interlinks extends restore_execution_step {
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();
776 * first, ensure that we have no gaps in section numbers
777 * and then, rebuid the course cache
779 class restore_rebuild_course_cache extends restore_execution_step {
781 protected function define_execution() {
782 global $DB;
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
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');
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.
812 class restore_execute_after_restore extends restore_execution_step {
814 protected function define_execution() {
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();
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
828 class restore_review_pending_block_positions extends restore_execution_step {
830 protected function define_execution() {
831 global $DB;
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);
849 $rs->close();
855 * Updates the availability data for course modules and sections.
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.
861 * @package core_backup
862 * @copyright 2014 The Open University
863 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
865 class restore_update_availability extends restore_execution_step {
867 protected function define_execution() {
868 global $CFG, $DB;
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.)
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());
879 // Get the date offset for this restore.
880 $dateoffset = $this->apply_date_offset(1) - 1;
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;
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;
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);
907 $rs->close();
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;
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);
927 $rs->close();
933 * Process legacy module availability records in backup_ids.
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.
939 * This step is included only to handle legacy backups (2.6 and before). It does not
940 * do anything for newer backups.
942 * @copyright 2014 The Open University
943 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
945 class restore_process_course_modules_availability extends restore_execution_step {
947 protected function define_execution() {
948 global $CFG, $DB;
950 // Site hasn't availability enabled
951 if (empty($CFG->enableavailability)) {
952 return;
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);
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.
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');
978 $show = $showrec->info->showavailability;
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));
989 $rs->close();
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
1000 class restore_load_included_inforef_records extends restore_execution_step {
1002 protected function define_execution() {
1004 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1005 return;
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);
1020 $progress->end_progress();
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)
1029 class restore_load_included_files extends restore_structure_step {
1031 protected function define_structure() {
1033 $file = new restore_path_element('file', '/files/file');
1035 return array($file);
1039 * Process one <file> element from files.xml
1041 * @param array $data the element data
1043 public function process_file($data) {
1045 $data = (object)$data; // handy
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);
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
1072 class restore_load_and_map_roles extends restore_execution_step {
1074 protected function define_execution() {
1075 if ($this->task->get_preloaded_information()) { // if info is already preloaded
1076 return;
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);
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);
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
1096 class restore_load_included_users extends restore_execution_step {
1098 protected function define_execution() {
1100 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1101 return;
1103 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1104 return;
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());
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)
1119 class restore_process_included_users extends restore_execution_step {
1121 protected function define_execution() {
1123 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1124 return;
1126 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1127 return;
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());
1135 * Execution step that will create all the needed users as calculated
1136 * by @restore_process_included_users (those having newiteind = 0)
1138 class restore_create_included_users extends restore_execution_step {
1140 protected function define_execution() {
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());
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
1152 class restore_groups_structure_step extends restore_structure_step {
1154 protected function define_structure() {
1156 $paths = array(); // Add paths here
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');
1168 return $paths;
1171 // Processing functions go here
1172 public function process_group($data) {
1173 global $DB;
1175 $data = (object)$data; // handy
1176 $data->courseid = $this->get_courseid();
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);
1185 } else {
1186 unset($data->idnumber);
1189 $oldid = $data->id; // need this saved for later
1191 $restorefiles = false; // Only if we end creating the group
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);
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;
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;
1219 // Save the id mapping
1220 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
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);
1227 // Invalidate the course group data cache just in case.
1228 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1232 * Restore group custom field values.
1233 * @param array $data data for group custom field
1234 * @return void
1236 public function process_groupcustomfield($data) {
1237 $newgroup = $this->get_mapping('group', $data['groupid']);
1238 $data['groupid'] = $newgroup->newitemid;
1239 $handler = \core_group\customfield\group_handler::create();
1240 $handler->restore_instance_data_from_backup($this->task, $data);
1243 public function process_grouping($data) {
1244 global $DB;
1246 $data = (object)$data; // handy
1247 $data->courseid = $this->get_courseid();
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);
1256 } else {
1257 unset($data->idnumber);
1260 $oldid = $data->id; // need this saved for later
1261 $restorefiles = false; // Only if we end creating the grouping
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;
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;
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));
1289 * Restore grouping custom field values.
1290 * @param array $data data for grouping custom field
1291 * @return void
1293 public function process_groupingcustomfield($data) {
1294 $newgroup = $this->get_mapping('grouping', $data['groupingid']);
1295 $data['groupingid'] = $newgroup->newitemid;
1296 $handler = \core_group\customfield\grouping_handler::create();
1297 $handler->restore_instance_data_from_backup($this->task, $data);
1300 public function process_grouping_group($data) {
1301 global $CFG;
1303 require_once($CFG->dirroot.'/group/lib.php');
1305 $data = (object)$data;
1306 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
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()));
1321 * Structure step that will create all the needed group memberships
1322 * by loading them from the groups.xml file performing the required matches.
1324 class restore_groups_members_structure_step extends restore_structure_step {
1326 protected $plugins = null;
1328 protected function define_structure() {
1330 $paths = array(); // Add paths here
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');
1337 return $paths;
1340 public function process_group($data) {
1341 $data = (object)$data; // handy
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.
1347 $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1350 public function process_member($data) {
1351 global $DB, $CFG;
1352 require_once("$CFG->dirroot/group/lib.php");
1354 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1356 $data = (object)$data; // handy
1358 // get parent group->id
1359 $data->groupid = $this->get_new_parentid('group');
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);
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);
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);
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;
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);
1400 * Structure step that will create all the needed scales
1401 * by loading them from the scales.xml
1403 class restore_scales_structure_step extends restore_structure_step {
1405 protected function define_structure() {
1407 $paths = array(); // Add paths here
1408 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1409 return $paths;
1412 protected function process_scale($data) {
1413 global $DB;
1415 $data = (object)$data;
1417 $restorefiles = false; // Only if we end creating the group
1419 $oldid = $data->id; // need this saved for later
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();
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;
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());
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());
1462 * Structure step that will create all the needed outocomes
1463 * by loading them from the outcomes.xml
1465 class restore_outcomes_structure_step extends restore_structure_step {
1467 protected function define_structure() {
1469 $paths = array(); // Add paths here
1470 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1471 return $paths;
1474 protected function process_outcome($data) {
1475 global $DB;
1477 $data = (object)$data;
1479 $restorefiles = false; // Only if we end creating the group
1481 $oldid = $data->id; // need this saved for later
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();
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;
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);
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());
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());
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
1536 class restore_load_categories_and_questions extends restore_execution_step {
1538 protected function define_execution() {
1540 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1541 return;
1543 $file = $this->get_basepath() . '/questions.xml';
1544 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
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)
1555 class restore_process_categories_and_questions extends restore_execution_step {
1557 protected function define_execution() {
1559 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1560 return;
1562 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1567 * Structure step that will read the section.xml creating/updating sections
1568 * as needed, rebuilding course cache and other friends
1570 class restore_section_structure_step extends restore_structure_step {
1571 /** @var array Cache: Array of id => course format */
1572 private static $courseformats = array();
1575 * Resets a static cache of course formats. Required for unit testing.
1577 public static function reset_caches() {
1578 self::$courseformats = array();
1581 protected function define_structure() {
1582 global $CFG;
1584 $paths = array();
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');
1592 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1594 // Apply for 'format' plugins optional paths at section level
1595 $this->add_plugin_structure('format', $section);
1597 // Apply for 'local' plugins optional paths at section level
1598 $this->add_plugin_structure('local', $section);
1600 return $paths;
1603 public function process_section($data) {
1604 global $CFG, $DB;
1605 $data = (object)$data;
1606 $oldid = $data->id; // We'll need this later
1608 $restorefiles = false;
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);
1632 $section->component = $data->component ?? null;
1633 $section->itemid = $data->itemid ?? null;
1634 $newitemid = $DB->insert_record('course_sections', $section);
1635 $section->id = $newitemid;
1637 core\event\course_section_created::create_from_section($section)->trigger();
1639 $restorefiles = true;
1641 // Section exists, update non-empty information
1642 } else {
1643 $section->id = $secrec->id;
1644 if ((string)$secrec->name === '') {
1645 $section->name = $data->name;
1647 if (empty($secrec->summary)) {
1648 $section->summary = $data->summary;
1649 $section->summaryformat = $data->summaryformat;
1650 $restorefiles = true;
1653 // Don't update availability (I didn't see a useful way to define
1654 // whether existing or new one should take precedence).
1656 $DB->update_record('course_sections', $section);
1657 $newitemid = $secrec->id;
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)
1668 $event->trigger();
1671 // Annotate the section mapping, with restorefiles option if needed
1672 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1674 // set the new course_section id in the task
1675 $this->task->set_sectionid($newitemid);
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));
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 // }
1699 * Process the legacy availability table record. This table does not exist
1700 * in Moodle 2.7+ but we still support restore.
1702 * @param stdClass $data Record data
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);
1715 * Process the legacy availability fields table record. This table does not
1716 * exist in Moodle 2.7+ but we still support restore.
1718 * @param stdClass $data Record data
1720 public function process_availability_field($data) {
1721 global $DB, $CFG;
1722 require_once($CFG->dirroot.'/user/profile/lib.php');
1724 $data = (object)$data;
1725 // Mark it is as passed by default
1726 $passed = true;
1727 $customfieldid = null;
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;
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;
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');
1756 $show = $showrec->info->showavailability;
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);
1765 $section = new stdClass();
1766 $section->id = $availfield->coursesectionid;
1767 $section->availability = $newvalue;
1768 $section->timemodified = time();
1769 $DB->update_record('course_sections', $section);
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));
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']
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);
1797 $this->set_mapping('course_format_options', $data['id'], $newid);
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');
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)
1813 class restore_course_structure_step extends restore_structure_step {
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()}.
1819 protected $legacyrestrictmodules = false;
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.
1828 protected $legacyallowedmodules = array();
1830 protected function define_structure() {
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');
1839 // Apply for 'format' plugins optional paths at course level
1840 $this->add_plugin_structure('format', $course);
1842 // Apply for 'theme' plugins optional paths at course level
1843 $this->add_plugin_structure('theme', $course);
1845 // Apply for 'report' plugins optional paths at course level
1846 $this->add_plugin_structure('report', $course);
1848 // Apply for 'course report' plugins optional paths at course level
1849 $this->add_plugin_structure('coursereport', $course);
1851 // Apply for plagiarism plugins optional paths at course level
1852 $this->add_plugin_structure('plagiarism', $course);
1854 // Apply for local plugins optional paths at course level
1855 $this->add_plugin_structure('local', $course);
1857 // Apply for admin tool plugins optional paths at course level.
1858 $this->add_plugin_structure('tool', $course);
1860 return array($course, $category, $tag, $customfield, $allowedmodule, $courseformatoptions);
1864 * Processing functions go here
1866 * @global moodledatabase $DB
1867 * @param stdClass $data
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;
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);
1881 $data = (object)$data;
1882 $data->id = $this->get_courseid();
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);
1894 if (!$isnewcourse && $shortname === false) {
1895 unset($data->shortname);
1898 // Unset summary if user can't change it.
1899 if (!$canchangesummary) {
1900 unset($data->summary);
1901 unset($data->summaryformat);
1904 // Unset lang if user can't change it.
1905 if (!$canforcelanguage) {
1906 unset($data->lang);
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.
1915 } else if (!$isnewcourse) {
1916 // Prevent override when restoring as merge.
1917 unset($data->idnumber);
1919 } else {
1920 $data->idnumber = '';
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();
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;
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);
1938 $data->startdate= $this->apply_date_offset($data->startdate);
1939 if (isset($data->enddate)) {
1940 $data->enddate = $this->apply_date_offset($data->enddate);
1943 if ($data->defaultgroupingid) {
1944 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1947 $courseconfig = get_config('moodlecourse');
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;
1960 $showactivitydatesdefault = ($courseconfig->showactivitydates ?? null);
1961 $data->showactivitydates = $data->showactivitydates ?? $showactivitydatesdefault;
1963 $pdffontdefault = ($courseconfig->pdfexportfont ?? null);
1964 $data->pdfexportfont = $data->pdfexportfont ?? $pdffontdefault;
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 = '';
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 = '';
1976 // Check if this is an old SCORM course format.
1977 if ($data->format == 'scorm') {
1978 $data->format = 'singleactivity';
1979 $data->activitytype = 'scorm';
1982 // Course record ready, update it
1983 $DB->update_record('course', $data);
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);
1989 // Role name aliases
1990 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1993 public function process_category($data) {
1994 // Nothing to do with the category. UI sets it before restore starts
1997 public function process_tag($data) {
1998 global $CFG, $DB;
2000 $data = (object)$data;
2002 core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
2003 context_course::instance($this->get_courseid()), $data->rawname);
2007 * Process custom fields
2009 * @param array $data
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);
2015 if ($newid) {
2016 $handler->restore_define_structure($this, $newid, $data['id']);
2021 * Processes a course format option.
2023 * @param array $data The record being restored.
2024 * @throws base_step_exception
2025 * @throws dml_exception
2027 public function process_course_format_option(array $data): void {
2028 global $DB;
2030 if ($data['sectionid']) {
2031 // Ignore section-level format options saved course-level in earlier-version backups.
2032 return;
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);
2046 public function process_allowed_module($data) {
2047 $data = (object)$data;
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;
2056 protected function after_execute() {
2057 global $DB;
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);
2063 // Deal with legacy allowed modules.
2064 if ($this->legacyrestrictmodules) {
2065 $context = context_course::instance($this->get_courseid());
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]);
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;
2079 $capability = 'mod/' . $modname . ':addinstance';
2081 if (!get_capability_info($capability)) {
2082 $this->log("Capability '{$capability}' was not found!", backup::LOG_WARNING);
2083 continue;
2086 foreach ($roleids as $roleid) {
2087 assign_capability($capability, CAP_PREVENT, $roleid, $context);
2095 * Execution step that will migrate legacy files if present.
2097 class restore_course_legacy_files_step extends restore_execution_step {
2098 public function define_execution() {
2099 global $DB;
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');
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());
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.
2124 * Note: this needs to be executed after all users are enrolled.
2126 class restore_ras_and_caps_structure_step extends restore_structure_step {
2127 protected $plugins = null;
2129 protected function define_structure() {
2131 $paths = array();
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');
2137 if ($this->get_setting_value('permissions')) {
2138 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
2141 return $paths;
2145 * Assign roles
2147 * This has to be called after enrolments processing.
2149 * @param mixed $data
2150 * @return void
2152 public function process_assignment($data) {
2153 global $DB;
2155 $data = (object)$data;
2157 // Check roleid, userid are one of the mapped ones
2158 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
2159 return;
2161 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
2162 return;
2164 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
2165 // Only assign roles to not deleted users
2166 return;
2168 if (!$contextid = $this->task->get_contextid()) {
2169 return;
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);
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);
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);
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;
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);
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();
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);
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)))
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);
2240 * If no instances yet add default enrol methods the same way as when creating new course in UI.
2242 class restore_default_enrolments_step extends restore_execution_step {
2244 public function define_execution() {
2245 global $DB;
2247 // No enrolments in front page.
2248 if ($this->get_courseid() == SITEID) {
2249 return;
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);
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);
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);
2269 $plugin->restore_sync_course($course);
2272 } else {
2273 // Looks like a newly created course.
2274 enrol_course_updated(true, $course, null);
2280 * This structure steps restores the enrol plugins and their underlying
2281 * enrolments, performing all the mappings and/or movements required
2283 class restore_enrolments_structure_step extends restore_structure_step {
2284 protected $enrolsynced = false;
2285 protected $plugins = null;
2286 protected $originalstatus = array();
2289 * Conditionally decide if this step should be executed.
2291 * This function checks the following parameter:
2293 * 1. the course/enrolments.xml file exists
2295 * @return bool true is safe to execute, false otherwise
2297 protected function execute_condition() {
2299 if ($this->get_courseid() == SITEID) {
2300 return false;
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;
2311 return true;
2314 protected function define_structure() {
2316 $userinfo = $this->get_setting_value('users');
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');
2323 // Attach local plugin stucture to enrol element.
2324 $this->add_plugin_structure('enrol', $enrol);
2326 return $paths;
2330 * Create enrolment instances.
2332 * This has to be called after creation of roles
2333 * and before adding of role assignments.
2335 * @param mixed $data
2336 * @return void
2338 public function process_enrol($data) {
2339 global $DB;
2341 $data = (object)$data;
2342 $oldid = $data->id; // We'll need this later.
2343 unset($data->id);
2345 $this->originalstatus[$oldid] = $data->status;
2347 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2348 $this->set_mapping('enrol', $oldid, 0);
2349 return;
2352 if (!isset($this->plugins)) {
2353 $this->plugins = enrol_get_plugins(true);
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);
2363 $this->enrolsynced = true;
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;
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);
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;
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);
2392 $this->set_mapping('enrol', $oldid, $instanceid);
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;
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);
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);
2415 * Create user enrolments.
2417 * This has to be called after creation of enrolment instances
2418 * and before adding of role assignments.
2420 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2422 * @param mixed $data
2423 * @return void
2425 public function process_enrolment($data) {
2426 global $DB;
2428 if (!isset($this->plugins)) {
2429 $this->plugins = enrol_get_plugins(true);
2432 $data = (object)$data;
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];
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);
2455 * Make sure the user restoring the course can actually access it.
2457 class restore_fix_restorer_access_step extends restore_execution_step {
2458 protected function define_execution() {
2459 global $CFG, $DB;
2461 if (!$userid = $this->task->get_userid()) {
2462 return;
2465 if (empty($CFG->restorernewroleid)) {
2466 // Bad luck, no fallback role for restorers specified
2467 return;
2470 $courseid = $this->get_courseid();
2471 $context = context_course::instance($courseid);
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;
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);
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;
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;
2491 if (!$enrol = enrol_get_plugin('manual')) {
2492 return;
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);
2500 enrol_try_internal_enrol($courseid, $userid);
2506 * This structure steps restores the filters and their configs
2508 class restore_filters_structure_step extends restore_structure_step {
2510 protected function define_structure() {
2512 $paths = array();
2514 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2515 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2517 return $paths;
2520 public function process_active($data) {
2522 $data = (object)$data;
2524 if (strpos($data->filter, 'filter/') === 0) {
2525 $data->filter = substr($data->filter, 7);
2527 } else if (strpos($data->filter, '/') !== false) {
2528 // Unsupported old filter.
2529 return;
2532 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2533 return;
2535 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2538 public function process_config($data) {
2540 $data = (object)$data;
2542 if (strpos($data->filter, 'filter/') === 0) {
2543 $data->filter = substr($data->filter, 7);
2545 } else if (strpos($data->filter, '/') !== false) {
2546 // Unsupported old filter.
2547 return;
2550 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2551 return;
2553 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
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
2563 class restore_comments_structure_step extends restore_structure_step {
2565 protected function define_structure() {
2567 $paths = array();
2569 $paths[] = new restore_path_element('comment', '/comments/comment');
2571 return $paths;
2574 public function process_comment($data) {
2575 global $DB;
2577 $data = (object)$data;
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);
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);
2602 * This structure steps restores the badges and their configs
2604 class restore_badges_structure_step extends restore_structure_step {
2607 * Conditionally decide if this step should be executed.
2609 * This function checks the following parameters:
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.
2616 * @return bool True is safe to execute, false otherwise
2618 protected function execute_condition() {
2619 global $CFG;
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;
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;
2635 // Check we are able to restore all backed up modules.
2636 if ($this->task->is_missing_modules()) {
2637 return false;
2640 // Finally check all modules within the backup are being restored.
2641 if ($this->task->is_excluding_activities()) {
2642 return false;
2645 return true;
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');
2659 return $paths;
2662 public function process_badge($data) {
2663 global $DB, $CFG;
2665 require_once($CFG->libdir . '/badgeslib.php');
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();
2672 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2673 if (empty($data->usermodified)) {
2674 $data->usermodified = $this->task->get_userid();
2677 // We'll restore the badge image.
2678 $restorefiles = true;
2680 $courseid = $this->get_courseid();
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
2710 $newid = $DB->insert_record('badge', $params);
2711 $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2715 * Create an endorsement for a badge.
2717 * @param mixed $data
2718 * @return void
2720 public function process_endorsement($data) {
2721 global $DB;
2723 $data = (object)$data;
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)
2734 $newid = $DB->insert_record('badge_endorsement', $params);
2735 $this->set_mapping('endorsement', $data->id, $newid);
2739 * Link to related badges for a badge. This relies on post processing in after_execute().
2741 * @param mixed $data
2742 * @return void
2744 public function process_relatedbadge($data) {
2745 global $DB;
2747 $data = (object)$data;
2748 $relatedbadgeid = $data->relatedbadgeid;
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
2756 $newid = $DB->insert_record('badge_related', $params);
2761 * Link to an alignment for a badge.
2763 * @param mixed $data
2764 * @return void
2766 public function process_alignment($data) {
2767 global $DB;
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
2778 $newid = $DB->insert_record('badge_alignment', $params);
2779 $this->set_mapping('alignment', $data->id, $newid);
2782 public function process_criterion($data) {
2783 global $DB;
2785 $data = (object)$data;
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,
2795 $newid = $DB->insert_record('badge_criteria', $params);
2796 $this->set_mapping('criterion', $data->id, $newid);
2799 public function process_parameter($data) {
2800 global $DB, $CFG;
2802 require_once($CFG->libdir . '/badgeslib.php');
2804 $data = (object)$data;
2805 $criteriaid = $this->get_new_parentid('criterion');
2807 // Parameter array that will go to database.
2808 $params = array();
2809 $params['critid'] = $criteriaid;
2811 $oldparam = explode('_', $data->name);
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;
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;
2838 if (!$DB->record_exists('badge_criteria_param', $params)) {
2839 $DB->insert_record('badge_criteria_param', $params);
2843 public function process_manual_award($data) {
2844 global $DB;
2846 $data = (object)$data;
2847 $role = $this->get_mappingid('role', $data->issuerrole);
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)
2858 // Skip the manual award if recipient or issuer can not be mapped to.
2859 if (empty($award['recipientid']) || empty($award['issuerid'])) {
2860 return;
2863 $DB->insert_record('badge_manual_award', $award);
2868 * Process tag.
2870 * @param array $data The data.
2871 * @throws base_step_exception
2873 public function process_tag(array $data): void {
2874 $data = (object)$data;
2875 $badgeid = $this->get_new_parentid('badge');
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);
2883 protected function after_execute() {
2884 global $DB;
2885 // Add related files.
2886 $this->add_related_files('badges', 'badgeimage', 'badge');
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;
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;
2914 $DB->insert_records('badge_related', $relatedbadges);
2920 * This structure steps restores the calendar events
2922 class restore_calendarevents_structure_step extends restore_structure_step {
2924 protected function define_structure() {
2926 $paths = array();
2928 $paths[] = new restore_path_element('calendarevents', '/events/event');
2930 return $paths;
2933 public function process_calendarevents($data) {
2934 global $DB, $SITE, $USER;
2936 $data = (object)$data;
2937 $oldid = $data->id;
2938 $restorefiles = true; // We'll restore the files
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;
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;
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;
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;
2964 if (!empty($data->groupid)) {
2965 $data->groupid = $this->get_mappingid('group', $data->groupid);
2966 if ($data->groupid === false) {
2967 return;
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;
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;
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);
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'];
3043 protected function after_execute() {
3044 // Add related files
3045 $this->add_related_files('calendar', 'event_description', 'event_description');
3049 class restore_course_completion_structure_step extends restore_structure_step {
3052 * Conditionally decide if this step should be executed.
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.
3057 * This function checks the following four parameters:
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.
3065 * @return bool True is safe to execute, false otherwise
3067 protected function execute_condition() {
3068 global $CFG, $DB;
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;
3076 // No course completion on the front page.
3077 if ($this->get_courseid() == SITEID) {
3078 return false;
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;
3089 // Check we are able to restore all backed up modules
3090 if ($this->task->is_missing_modules()) {
3091 return false;
3094 // Check all modules within the backup are being restored.
3095 if ($this->task->is_excluding_activities()) {
3096 return false;
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;
3104 return true;
3108 * Define the course completion structure
3110 * @return array Array of restore_path_element
3112 protected function define_structure() {
3114 // To know if we are including user completion info
3115 $userinfo = $this->get_setting_value('userscompletion');
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');
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');
3126 return $paths;
3131 * Process course completion criteria
3133 * @global moodle_database $DB
3134 * @param stdClass $data
3136 public function process_course_completion_criteria($data) {
3137 global $DB;
3139 $data = (object)$data;
3140 $data->course = $this->get_courseid();
3142 // Apply the date offset to the time end field
3143 $data->timeend = $this->apply_date_offset($data->timeend);
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
3155 return;
3157 $data->role = $roleinstanceid;
3158 } else {
3159 $data->role = $this->get_mappingid('role', $data->role);
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
3168 return;
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
3181 return;
3183 } else {
3184 $data->module = null;
3185 $data->moduleinstance = null;
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
3196 return;
3198 } else {
3199 $courseinstanceid = null;
3201 $data->courseinstance = $courseinstanceid;
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
3214 $newid = $DB->insert_record('course_completion_criteria', $params);
3215 $this->set_mapping('course_completion_criteria', $data->id, $newid);
3219 * Processes course compltion criteria complete records
3221 * @global moodle_database $DB
3222 * @param stdClass $data
3224 public function process_course_completion_crit_compl($data) {
3225 global $DB;
3227 $data = (object)$data;
3229 // This may be empty if criteria could not be restored
3230 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
3232 $data->course = $this->get_courseid();
3233 $data->userid = $this->get_mappingid('user', $data->userid);
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
3242 if (isset($data->gradefinal)) {
3243 $params['gradefinal'] = $data->gradefinal;
3245 if (isset($data->unenroled)) {
3246 $params['unenroled'] = $data->unenroled;
3248 $DB->insert_record('course_completion_crit_compl', $params);
3253 * Process course completions
3255 * @global moodle_database $DB
3256 * @param stdClass $data
3258 public function process_course_completions($data) {
3259 global $DB;
3261 $data = (object)$data;
3263 $data->course = $this->get_courseid();
3264 $data->userid = $this->get_mappingid('user', $data->userid);
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
3276 $existing = $DB->get_record('course_completions', array(
3277 'userid' => $data->userid,
3278 'course' => $data->course
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);
3294 * Process course completion aggregate methods
3296 * @global moodle_database $DB
3297 * @param stdClass $data
3299 public function process_course_completion_aggr_methd($data) {
3300 global $DB;
3302 $data = (object)$data;
3304 $data->course = $this->get_courseid();
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,
3317 $DB->insert_record('course_completion_aggr_methd', $params);
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.
3329 * NOTE: This is executed by final task, to have all the activities already restored
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.
3335 * NOTE: All the missing actions (not able to be restored) are sent to logs for
3336 * debugging purposes
3338 class restore_course_logs_structure_step extends restore_structure_step {
3341 * Conditionally decide if this step should be executed.
3343 * This function checks the following parameter:
3345 * 1. the course/logs.xml file exists
3347 * @return bool true is safe to execute, false otherwise
3349 protected function execute_condition() {
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;
3359 return true;
3362 protected function define_structure() {
3364 $paths = array();
3366 // Simple, one plain level of information contains them
3367 $paths[] = new restore_path_element('log', '/logs/log');
3369 return $paths;
3372 protected function process_log($data) {
3373 global $DB;
3375 $data = (object)($data);
3377 // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3379 $data->userid = $this->get_mappingid('user', $data->userid);
3380 $data->course = $this->get_courseid();
3381 $data->cmid = 0;
3383 // For any reason user wasn't remapped ok, stop processing this
3384 if (empty($data->userid)) {
3385 return;
3388 // Everything ready, let's delegate to the restore_logs_processor
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);
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 = '';
3401 if (empty($data->info)) {
3402 $data->info = '';
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);
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
3418 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
3420 protected function process_log($data) {
3421 global $DB;
3423 $data = (object)($data);
3425 // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3427 $data->userid = $this->get_mappingid('user', $data->userid);
3428 $data->course = $this->get_courseid();
3429 $data->cmid = $this->task->get_moduleid();
3431 // For any reason user wasn't remapped ok, stop processing this
3432 if (empty($data->userid)) {
3433 return;
3436 // Everything ready, let's delegate to the restore_logs_processor
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);
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 = '';
3451 if (empty($data->info)) {
3452 $data->info = '';
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);
3465 * Structure step in charge of restoring the logstores.xml file for the course logs.
3467 * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3468 * it, for logs belonging to the course level.
3470 class restore_course_logstores_structure_step extends restore_structure_step {
3473 * Conditionally decide if this step should be executed.
3475 * This function checks the following parameter:
3477 * 1. the logstores.xml file exists
3479 * @return bool true is safe to execute, false otherwise
3481 protected function execute_condition() {
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;
3491 return true;
3495 * Return the elements to be processed on restore of logstores.
3497 * @return restore_path_element[] array of elements to be processed on restore.
3499 protected function define_structure() {
3501 $paths = array();
3503 $logstore = new restore_path_element('logstore', '/logstores/logstore');
3504 $paths[] = $logstore;
3506 // Add logstore subplugin support to the 'logstore' element.
3507 $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3509 return array($logstore);
3513 * Process the 'logstore' element,
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.
3518 * @param array $data element data
3520 protected function process_logstore($data) {
3521 return;
3526 * Structure step in charge of restoring the loglastaccess.xml file for the course logs.
3528 * This restore step will rebuild the table for user_lastaccess table.
3530 class restore_course_loglastaccess_structure_step extends restore_structure_step {
3533 * Conditionally decide if this step should be executed.
3535 * This function checks the following parameter:
3537 * 1. the loglastaccess.xml file exists
3539 * @return bool true is safe to execute, false otherwise
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;
3550 return true;
3554 * Return the elements to be processed on restore of loglastaccess.
3556 * @return restore_path_element[] array of elements to be processed on restore.
3558 protected function define_structure() {
3560 $paths = array();
3561 // To know if we are including userinfo.
3562 $userinfo = $this->get_setting_value('users');
3564 if ($userinfo) {
3565 $paths[] = new restore_path_element('lastaccess', '/lastaccesses/lastaccess');
3567 // Return the paths wrapped.
3568 return $paths;
3572 * Process the 'lastaccess' elements.
3574 * @param array $data element data
3576 protected function process_lastaccess($data) {
3577 global $DB;
3579 $data = (object)$data;
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.
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);
3594 } else {
3595 $DB->insert_record('user_lastaccess', $data);
3601 * Structure step in charge of restoring the logstores.xml file for the activity logs.
3603 * Note: Activity structure is completely equivalent to the course one, so just extend it.
3605 class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3609 * Restore course competencies structure step.
3611 class restore_course_competencies_structure_step extends restore_structure_step {
3614 * Returns the structure.
3616 * @return array
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'),
3624 if ($userinfo) {
3625 $paths[] = new restore_path_element('user_competency_course',
3626 '/course_competencies/user_competencies/user_competency');
3628 return $paths;
3632 * Process a course competency settings.
3634 * @param array $data The data.
3636 public function process_course_competency_settings($data) {
3637 global $DB;
3638 $data = (object) $data;
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;
3646 $courseid = $this->task->get_courseid();
3647 $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3648 array('courseid' => $courseid));
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;
3656 $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3657 $settings = new \core_competency\course_competency_settings(0, $data);
3658 $settings->create();
3662 * Process a course competency.
3664 * @param array $data The data.
3666 public function process_course_competency($data) {
3667 $data = (object) $data;
3669 // Mapping the competency by ID numbers.
3670 $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3671 if (!$framework) {
3672 return;
3674 $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3675 'competencyframeworkid' => $framework->get('id')));
3676 if (!$competency) {
3677 return;
3679 $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get('id'));
3681 $params = array(
3682 'competencyid' => $competency->get('id'),
3683 'courseid' => $this->task->get_courseid()
3685 $query = 'competencyid = :competencyid AND courseid = :courseid';
3686 $existing = \core_competency\course_competency::record_exists_select($query, $params);
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();
3698 * Process the user competency course.
3700 * @param array $data The data.
3702 public function process_user_competency_course($data) {
3703 global $USER, $DB;
3704 $data = (object) $data;
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;
3715 $data->userid = $this->get_mappingid('user', $data->userid);
3716 $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
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);
3733 * Execute conditions.
3735 * @return bool
3737 protected function execute_condition() {
3739 // Do not execute if competencies are not included.
3740 if (!$this->get_setting_value('competencies')) {
3741 return false;
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;
3751 return true;
3756 * Restore activity competencies structure step.
3758 class restore_activity_competencies_structure_step extends restore_structure_step {
3761 * Defines the structure.
3763 * @return array
3765 protected function define_structure() {
3766 $paths = array(
3767 new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3769 return $paths;
3773 * Process a course module competency.
3775 * @param array $data The data.
3777 public function process_course_module_competency($data) {
3778 $data = (object) $data;
3780 // Mapping the competency by ID numbers.
3781 $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3782 if (!$framework) {
3783 return;
3785 $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3786 'competencyframeworkid' => $framework->get('id')));
3787 if (!$competency) {
3788 return;
3791 $params = array(
3792 'competencyid' => $competency->get('id'),
3793 'cmid' => $this->task->get_moduleid()
3795 $query = 'competencyid = :competencyid AND cmid = :cmid';
3796 $existing = \core_competency\course_module_competency::record_exists_select($query, $params);
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();
3809 * Execute conditions.
3811 * @return bool
3813 protected function execute_condition() {
3815 // Do not execute if competencies are not included.
3816 if (!$this->get_setting_value('competencies')) {
3817 return false;
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;
3827 return true;
3832 * Defines the restore step for advanced grading methods attached to the activity module
3834 class restore_activity_grading_structure_step extends restore_structure_step {
3837 * This step is executed only if the grading file is present
3839 protected function execute_condition() {
3841 if ($this->get_courseid() == SITEID) {
3842 return false;
3845 $fullpath = $this->task->get_taskbasepath();
3846 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3847 if (!file_exists($fullpath)) {
3848 return false;
3851 return true;
3856 * Declares paths in the grading.xml file we are interested in
3858 protected function define_structure() {
3860 $paths = array();
3861 $userinfo = $this->get_setting_value('userinfo');
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);
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);
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);
3884 return $paths;
3888 * Processes one grading area element
3890 * @param array $data element data
3892 protected function process_grading_area($data) {
3893 global $DB;
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();
3901 $newid = $DB->insert_record('grading_areas', $data);
3902 $this->set_mapping('grading_area', $oldid, $newid);
3906 * Processes one grading definition element
3908 * @param array $data element data
3910 protected function process_grading_definition($data) {
3911 global $DB;
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;
3923 $newid = $DB->insert_record('grading_definitions', $data);
3924 $this->set_mapping('grading_definition', $oldid, $newid, true);
3928 * Processes one grading form instance element
3930 * @param array $data element data
3932 protected function process_grading_instance($data) {
3933 global $DB;
3935 $data = (object)$data;
3937 // new form definition id
3938 $newformid = $this->get_new_parentid('grading_definition');
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);
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);
3951 $oldid = $data->id;
3952 $data->definitionid = $newformid;
3953 $data->raterid = $this->get_mappingid('user', $data->raterid);
3954 $data->itemid = $newitemid;
3956 $newid = $DB->insert_record('grading_instances', $data);
3957 $this->set_mapping('grading_instance', $oldid, $newid);
3961 * Final operations when the database records are inserted
3963 protected function after_execute() {
3964 // Add files embedded into the definition description
3965 $this->add_related_files('grading', 'description', 'grading_definition');
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
3977 class restore_activity_grades_structure_step extends restore_structure_step {
3980 * No grades in front page.
3981 * @return bool
3983 protected function execute_condition() {
3984 return ($this->get_courseid() != SITEID);
3987 protected function define_structure() {
3989 $paths = array();
3990 $userinfo = $this->get_setting_value('userinfo');
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');
3998 return $paths;
4001 protected function process_grade_item($data) {
4002 global $DB;
4004 $data = (object)($data);
4005 $oldid = $data->id; // We'll need these later
4006 $oldparentid = $data->categoryid;
4007 $courseid = $this->get_courseid();
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()
4028 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
4029 $idnumber = $data->idnumber;
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);
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);
4051 $gradeitem = new grade_item($data, false);
4052 $gradeitem->insert('restore');
4054 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
4055 $gradeitem->sortorder = $data->sortorder;
4056 $gradeitem->update('restore');
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);
4063 protected function process_grade_grade($data) {
4064 global $CFG;
4066 require_once($CFG->libdir . '/grade/constants.php');
4068 $data = (object)($data);
4069 $olduserid = $data->userid;
4070 $oldid = $data->id;
4071 unset($data->id);
4073 $data->itemid = $this->get_new_parentid('grade_item');
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);
4080 $grade = new grade_grade($data, false);
4081 $grade->insert('restore');
4083 $this->set_mapping('grade_grades', $oldid, $grade->id, true);
4085 $this->add_related_files(
4086 GRADE_FILE_COMPONENT,
4087 GRADE_FEEDBACK_FILEAREA,
4088 'grade_grades',
4089 null,
4090 $oldid
4092 } else {
4093 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
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.
4103 protected function process_grade_letter($data) {
4104 global $DB;
4106 $data['contextid'] = $this->task->get_contextid();
4107 $gradeletter = (object)$data;
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);
4114 // no need to save any grade_letter mapping
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);
4125 * Step in charge of restoring the grade history of an activity.
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.
4131 class restore_activity_grade_history_structure_step extends restore_structure_step {
4134 * This step is executed only if the grade history file is present.
4136 protected function execute_condition() {
4138 if ($this->get_courseid() == SITEID) {
4139 return false;
4142 $fullpath = $this->task->get_taskbasepath();
4143 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4144 if (!file_exists($fullpath)) {
4145 return false;
4147 return true;
4150 protected function define_structure() {
4151 $paths = array();
4153 // Settings to use.
4154 $userinfo = $this->get_setting_value('userinfo');
4155 $history = $this->get_setting_value('grade_histories');
4157 if ($userinfo && $history) {
4158 $paths[] = new restore_path_element('grade_grade',
4159 '/grade_history/grade_grades/grade_grade');
4162 return $paths;
4165 protected function process_grade_grade($data) {
4166 global $CFG, $DB;
4168 require_once($CFG->libdir . '/grade/constants.php');
4170 $data = (object) $data;
4171 $oldhistoryid = $data->id;
4172 $olduserid = $data->userid;
4173 unset($data->id);
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);
4183 $newhistoryid = $DB->insert_record('grade_grades_history', $data);
4185 $this->set_mapping('grade_grades_history', $oldhistoryid, $newhistoryid, true);
4187 $this->add_related_files(
4188 GRADE_FILE_COMPONENT,
4189 GRADE_HISTORY_FEEDBACK_FILEAREA,
4190 'grade_grades_history',
4191 null,
4192 $oldhistoryid
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);
4202 * This structure steps restores the content bank content
4204 class restore_contentbankcontent_structure_step extends restore_structure_step {
4207 * Define structure for content bank step
4209 protected function define_structure() {
4211 $paths = [];
4212 $paths[] = new restore_path_element('contentbankcontent', '/contents/content');
4214 return $paths;
4218 * Define data processed for content bank
4220 * @param mixed $data
4222 public function process_contentbankcontent($data) {
4223 global $DB;
4225 $data = (object)$data;
4226 $oldid = $data->id;
4228 $params = [
4229 'name' => $data->name,
4230 'contextid' => $this->task->get_contextid(),
4231 'contenttype' => $data->contenttype,
4232 'instanceid' => $data->instanceid,
4233 'timecreated' => $data->timecreated,
4235 $exists = $DB->record_exists('contentbank_content', $params);
4236 if (!$exists) {
4237 $params['configdata'] = $data->configdata;
4238 $params['timemodified'] = time();
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();
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();
4262 $newitemid = $DB->insert_record('contentbank_content', $params);
4263 $this->set_mapping('contentbank_content', $oldid, $newitemid, true);
4268 * Define data processed after execute for content bank
4270 protected function after_execute() {
4271 // Add related files.
4272 $this->add_related_files('contentbank', 'public', 'contentbank_content');
4277 * This structure steps restores the xAPI states.
4279 class restore_xapistate_structure_step extends restore_structure_step {
4282 * Define structure for xAPI state step
4284 protected function define_structure() {
4285 return [new restore_path_element('xapistate', '/states/state')];
4289 * Define data processed for xAPI state.
4291 * @param array|stdClass $data
4293 public function process_xapistate($data) {
4294 global $DB;
4296 $data = (object)$data;
4297 $oldid = $data->id;
4298 $exists = false;
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(),
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;
4318 $filter = $params;
4319 unset($filter['statedata']);
4320 $exists = $DB->record_exists('xapi_states', $filter);
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);
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)
4337 class restore_block_instance_structure_step extends restore_structure_step {
4339 protected function define_structure() {
4341 $paths = array();
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');
4346 return $paths;
4349 public function process_block($data) {
4350 global $DB, $CFG;
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();
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;
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;
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
4380 // Context matching test.
4381 $context = context::instance_by_id($data->parentcontextid);
4382 $contextsql = 'bi.parentcontextid = :contextid';
4383 $params['contextid'] = $context->id;
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);
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);
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;
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;
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;
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);
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);
4458 foreach ($configdata as $attribute => $value) {
4459 if (in_array($attribute, $attrstotransform)) {
4460 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
4463 $data->configdata = base64_encode(serialize((object)$configdata));
4466 // Set timecreated, timemodified if not included (older backup).
4467 if (empty($data->timecreated)) {
4468 $data->timecreated = time();
4470 if (empty($data->timemodified)) {
4471 $data->timemodified = $data->timecreated;
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);
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);
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);
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);
4513 * Structure step to restore common course_module information
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
4521 class restore_module_structure_step extends restore_structure_step {
4523 protected function define_structure() {
4524 global $CFG;
4526 $paths = array();
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');
4535 $paths[] = new restore_path_element('tag', '/module/tags/tag');
4537 // Apply for 'format' plugins optional paths at module level
4538 $this->add_plugin_structure('format', $module);
4540 // Apply for 'report' plugins optional paths at module level.
4541 $this->add_plugin_structure('report', $module);
4543 // Apply for 'plagiarism' plugins optional paths at module level
4544 $this->add_plugin_structure('plagiarism', $module);
4546 // Apply for 'local' plugins optional paths at module level
4547 $this->add_plugin_structure('local', $module);
4549 // Apply for 'admin tool' plugins optional paths at module level.
4550 $this->add_plugin_structure('tool', $module);
4552 return $paths;
4555 protected function process_module($data) {
4556 global $CFG, $DB;
4558 $data = (object)$data;
4559 $oldid = $data->id;
4560 $this->task->set_old_moduleversion($data->version);
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);
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);
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
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 = '';
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);
4601 if (empty($CFG->enableavailability)) {
4602 $data->availability = null;
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;
4610 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
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);
4624 if (!has_capability('moodle/course:setforcedlanguage', context_course::instance($data->course))) {
4625 unset($data->lang);
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;
4645 $updatesection = new \stdClass();
4646 $updatesection->id = $data->section;
4647 $updatesection->sequence = $sequence;
4648 $updatesection->timemodified = time();
4649 $DB->update_record('course_sections', $updatesection);
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));
4662 * Fetch all the existing because tag_set() deletes them
4663 * so everything must be reinserted on each call.
4665 * @param stdClass $data Record data
4667 protected function process_tag($data) {
4668 global $CFG;
4670 $data = (object)$data;
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();
4676 core_tag_tag::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname);
4681 * Process the legacy availability table record. This table does not exist
4682 * in Moodle 2.7+ but we still support restore.
4684 * @param stdClass $data Record data
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);
4696 * Process the legacy availability fields table record. This table does not
4697 * exist in Moodle 2.7+ but we still support restore.
4699 * @param stdClass $data Record data
4701 protected function process_availability_field($data) {
4702 global $DB, $CFG;
4703 require_once($CFG->dirroot.'/user/profile/lib.php');
4705 $data = (object)$data;
4706 // Mark it is as passed by default
4707 $passed = true;
4708 $customfieldid = null;
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;
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;
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');
4737 $show = $showrec->info->showavailability;
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));
4750 * This method will be executed after the rest of the restore has been processed.
4752 * Update old tag instance itemid(s).
4754 protected function after_restore() {
4755 global $DB;
4757 $contextid = $this->task->get_contextid();
4758 $instanceid = $this->task->get_activityid();
4759 $olditemid = $this->task->get_old_activityid();
4761 $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
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)
4771 class restore_userscompletion_structure_step extends restore_structure_step {
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...)
4778 protected function execute_condition() {
4779 global $CFG;
4781 // Completion disabled in this site, don't execute
4782 if (empty($CFG->enablecompletion)) {
4783 return false;
4786 // No completion on the front page.
4787 if ($this->get_courseid() == SITEID) {
4788 return false;
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;
4798 // Arrived here, execute the step
4799 return true;
4802 protected function define_structure() {
4804 $paths = array();
4806 // Restore completion.
4807 $paths[] = new restore_path_element('completion', '/completions/completion');
4809 // Restore completion view.
4810 $paths[] = new restore_path_element('completionview', '/completions/completionviews/completionview');
4812 return $paths;
4815 protected function process_completion($data) {
4816 global $DB;
4818 $data = (object)$data;
4820 $data->coursemoduleid = $this->task->get_moduleid();
4821 $data->userid = $this->get_mappingid('user', $data->userid);
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);
4836 } else {
4837 // Normal entry where it doesn't exist already
4838 $DB->insert_record('course_modules_completion', $data);
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);
4852 * Process the completioinview data.
4853 * @param array $data The data from the XML file.
4855 protected function process_completionview(array $data) {
4856 global $DB;
4858 $data = (object)$data;
4859 $data->coursemoduleid = $this->task->get_moduleid();
4860 $data->userid = $this->get_mappingid('user', $data->userid);
4862 $DB->insert_record('course_modules_viewed', $data);
4867 * Abstract structure step, parent of all the activity structure steps. Used to support
4868 * the main <activity ...> tag and process it.
4870 abstract class restore_activity_structure_step extends restore_structure_step {
4873 * Adds support for the 'activity' path that is common to all the activities
4874 * and will be processed globally here
4876 protected function prepare_activity_structure($paths) {
4878 $paths[] = new restore_path_element('activity', '/activity');
4880 return $paths;
4884 * Process the activity path, informing the task about various ids, needed later
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
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
4897 protected function apply_activity_instance($newitemid) {
4898 global $DB;
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);
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.
4916 class restore_create_categories_and_questions extends restore_structure_step {
4918 /** @var array $cachedcategory store a question category */
4919 protected $cachedcategory = null;
4921 protected function define_structure() {
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');
4934 // Apply for 'qtype' plugins optional paths at question level.
4935 $this->add_plugin_structure('qtype', $question);
4937 // Apply for 'local' plugins optional paths at question level.
4938 $this->add_plugin_structure('local', $question);
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');
4953 // Apply for 'qtype' plugins optional paths at question level.
4954 $this->add_plugin_structure('qtype', $question);
4956 // Apply for 'qbank' plugins optional paths at question level.
4957 $this->add_plugin_structure('qbank', $question);
4959 // Apply for 'local' plugins optional paths at question level.
4960 $this->add_plugin_structure('local', $question);
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');
4969 return $paths;
4973 * Process question category restore.
4975 * @param array $data the data from the XML file.
4977 protected function process_question_category($data) {
4978 global $DB;
4980 $data = (object)$data;
4981 $oldid = $data->id;
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
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
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());
5003 $data->contextid = $mapping->parentitemid;
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;
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);
5019 $this->set_mapping('question_category', $oldid, $top->id);
5020 } else {
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();
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);
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);
5046 * Process pre 4.0 question data where in creates the record for version and entry table.
5048 * @param array $data the data from the XML file.
5050 protected function process_question_legacy_data($data) {
5051 global $DB;
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();
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;
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;
5082 $versiondata->status = $versionstatus;
5083 $newversionid = $DB->insert_record('question_versions', $versiondata);
5084 $this->set_mapping('question_version_created', $oldid, $newversionid);
5088 * Process question bank entry data.
5090 * @param array $data the data from the XML file.
5092 protected function process_question_bank_entry($data) {
5093 global $DB;
5095 $data = (object)$data;
5096 $oldid = $data->id;
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;
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();
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);
5122 $newitemid = $DB->insert_record('question_bank_entries', $data);
5123 $this->set_mapping('question_bank_entry', $oldid, $newitemid);
5127 * Process question versions.
5129 * @param array $data the data from the XML file.
5131 protected function process_question_versions($data) {
5132 global $DB;
5134 $data = (object)$data;
5135 $oldid = $data->id;
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);
5145 * Process the actual question.
5147 * @param array $data the data from the XML file.
5149 protected function process_question($data) {
5150 global $DB;
5152 $data = (object)$data;
5153 $oldid = $data->id;
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.
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);
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;
5175 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
5176 $data->penalty = 0.6666667;
5178 if ($data->penalty >= 1) {
5179 $data->penalty = 1;
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();
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();
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');
5219 $version = new stdClass();
5220 $version->id = $parentitemid;
5221 $version->questionid = $newitemid;
5222 $DB->update_record('question_versions', $version);
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.
5231 protected function process_question_hint($data) {
5232 global $DB;
5234 $data = (object)$data;
5235 $oldid = $data->id;
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;
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);
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);
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;
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);
5284 // Create mapping (I'm not sure if this is really needed?)
5285 $this->set_mapping('question_hint', $oldid, $newitemid);
5288 protected function process_tag($data) {
5289 global $DB;
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;
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));
5309 $tagcontextid = $this->cachedcategory->contextid;
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);
5318 protected function after_execute() {
5319 global $DB;
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
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));
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));
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
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)
5377 class restore_move_module_questions_categories extends restore_execution_step {
5379 protected function define_execution() {
5380 global $DB;
5382 $after35 = $this->task->backup_release_compare('3.5', '>=') && $this->task->backup_version_compare(20180205, '>');
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;
5411 $DB->update_record('question_categories', $cat);
5412 $categoryids[] = (int)$cat->id;
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);
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(),
5441 $params += $categoryidparams;
5442 $DB->execute($sqlupdate, $params);
5445 // Now set the parent id for the question categories that were in the top category in the course context
5446 // and have been moved now.
5447 if ($oldtopid) {
5448 $DB->set_field('question_categories', 'parent', $top->id,
5449 array('contextid' => $newcontext->newitemid, 'parent' => $oldtopid));
5457 * Execution step that will create all the question/answers/qtype-specific files for the restored
5458 * questions. It must be executed after {@link restore_move_module_questions_categories}
5459 * because only then each question is in its final category and only then the
5460 * contexts can be determined.
5462 class restore_create_question_files extends restore_execution_step {
5464 /** @var array Question-type specific component items cache. */
5465 private $qtypecomponentscache = array();
5468 * Preform the restore_create_question_files step.
5470 protected function define_execution() {
5471 global $DB;
5473 // Track progress, as this task can take a long time.
5474 $progress = $this->task->get_progress();
5475 $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
5477 // Parentitemids of question_createds in backup_ids_temp are the category it is in.
5478 // MUST use a recordset, as there is no unique key in the first (or any) column.
5479 $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
5480 FROM {backup_ids_temp} bi
5481 JOIN {question} q ON q.id = bi.newitemid
5482 WHERE bi.backupid = ?
5483 AND bi.itemname = 'question_created'
5484 ORDER BY categoryid ASC", array($this->get_restoreid()));
5486 $currentcatid = -1;
5487 foreach ($catqtypes as $categoryid => $row) {
5488 $qtype = $row->qtype;
5490 // Check if we are in a new category.
5491 if ($currentcatid !== $categoryid) {
5492 // Report progress for each category.
5493 $progress->progress();
5495 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
5496 'question_category', $categoryid)) {
5497 // Something went really wrong, cannot find the question_category for the question_created records.
5498 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
5499 continue;
5502 // Calculate source and target contexts.
5503 $oldctxid = $qcatmapping->info->contextid;
5504 $newctxid = $qcatmapping->parentitemid;
5506 $this->send_common_files($oldctxid, $newctxid, $progress);
5507 $currentcatid = $categoryid;
5510 $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
5512 $catqtypes->close();
5513 $progress->end_progress();
5517 * Send the common question files to a new context.
5519 * @param int $oldctxid Old context id.
5520 * @param int $newctxid New context id.
5521 * @param \core\progress\base $progress Progress object to use.
5523 private function send_common_files($oldctxid, $newctxid, $progress) {
5524 // Add common question files (question and question_answer ones).
5525 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
5526 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5527 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
5528 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5529 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
5530 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5531 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
5532 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5533 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
5534 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
5535 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
5536 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5537 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
5538 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5539 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
5540 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5544 * Send the question type specific files to a new context.
5546 * @param text $qtype The qtype name to send.
5547 * @param int $oldctxid Old context id.
5548 * @param int $newctxid New context id.
5549 * @param \core\progress\base $progress Progress object to use.
5551 private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
5552 if (!isset($this->qtypecomponentscache[$qtype])) {
5553 $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
5555 $components = $this->qtypecomponentscache[$qtype];
5556 foreach ($components as $component => $fileareas) {
5557 foreach ($fileareas as $filearea => $mapping) {
5558 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
5559 $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
5566 * Try to restore aliases and references to external files.
5568 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
5569 * We expect that all regular (non-alias) files have already been restored. Make sure
5570 * there is no restore step executed after this one that would call send_files_to_pool() again.
5572 * You may notice we have hardcoded support for Server files, Legacy course files
5573 * and user Private files here at the moment. This could be eventually replaced with a set of
5574 * callbacks in the future if needed.
5576 * @copyright 2012 David Mudrak <david@moodle.com>
5577 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5579 class restore_process_file_aliases_queue extends restore_execution_step {
5581 /** @var array internal cache for {@link choose_repository()} */
5582 private $cachereposbyid = array();
5584 /** @var array internal cache for {@link choose_repository()} */
5585 private $cachereposbytype = array();
5588 * What to do when this step is executed.
5590 protected function define_execution() {
5591 global $DB;
5593 $fs = get_file_storage();
5595 // Load the queue.
5596 $aliascount = $DB->count_records('backup_ids_temp',
5597 ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue']);
5598 $rs = $DB->get_recordset('backup_ids_temp',
5599 ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'],
5600 '', 'info');
5602 $this->log('processing file aliases queue. ' . $aliascount . ' entries.', backup::LOG_DEBUG);
5603 $progress = $this->task->get_progress();
5604 $progress->start_progress('Processing file aliases queue', $aliascount);
5606 // Iterate over aliases in the queue.
5607 foreach ($rs as $record) {
5608 $progress->increment_progress();
5609 $info = backup_controller_dbops::decode_backup_temp_info($record->info);
5611 // Try to pick a repository instance that should serve the alias.
5612 $repository = $this->choose_repository($info);
5614 if (is_null($repository)) {
5615 $this->notify_failure($info, 'unable to find a matching repository instance');
5616 continue;
5619 if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5620 || $info->oldfile->repositorytype === 'contentbank') {
5621 // Aliases to Server files and Legacy course files may refer to a file
5622 // contained in the backup file or to some existing file (if we are on the
5623 // same site).
5624 try {
5625 $reference = file_storage::unpack_reference($info->oldfile->reference);
5626 } catch (Exception $e) {
5627 $this->notify_failure($info, 'invalid reference field format');
5628 continue;
5631 // Let's see if the referred source file was also included in the backup.
5632 $candidates = $DB->get_recordset('backup_files_temp', array(
5633 'backupid' => $this->get_restoreid(),
5634 'contextid' => $reference['contextid'],
5635 'component' => $reference['component'],
5636 'filearea' => $reference['filearea'],
5637 'itemid' => $reference['itemid'],
5638 ), '', 'info, newcontextid, newitemid');
5640 $source = null;
5642 foreach ($candidates as $candidate) {
5643 $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
5644 if ($candidateinfo->filename === $reference['filename']
5645 and $candidateinfo->filepath === $reference['filepath']
5646 and !is_null($candidate->newcontextid)
5647 and !is_null($candidate->newitemid) ) {
5648 $source = $candidateinfo;
5649 $source->contextid = $candidate->newcontextid;
5650 $source->itemid = $candidate->newitemid;
5651 break;
5654 $candidates->close();
5656 if ($source) {
5657 // We have an alias that refers to another file also included in
5658 // the backup. Let us change the reference field so that it refers
5659 // to the restored copy of the original file.
5660 $reference = file_storage::pack_reference($source);
5662 // Send the new alias to the filepool.
5663 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5664 $this->notify_success($info);
5665 continue;
5667 } else {
5668 // This is a reference to some moodle file that was not contained in the backup
5669 // file. If we are restoring to the same site, keep the reference untouched
5670 // and restore the alias as is if the referenced file exists.
5671 if ($this->task->is_samesite()) {
5672 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5673 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5674 $reference = file_storage::pack_reference($reference);
5675 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5676 $this->notify_success($info);
5677 continue;
5678 } else {
5679 $this->notify_failure($info, 'referenced file not found');
5680 continue;
5683 // If we are at other site, we can't restore this alias.
5684 } else {
5685 $this->notify_failure($info, 'referenced file not included');
5686 continue;
5690 } else if ($info->oldfile->repositorytype === 'user') {
5691 if ($this->task->is_samesite()) {
5692 // For aliases to user Private files at the same site, we have a chance to check
5693 // if the referenced file still exists.
5694 try {
5695 $reference = file_storage::unpack_reference($info->oldfile->reference);
5696 } catch (Exception $e) {
5697 $this->notify_failure($info, 'invalid reference field format');
5698 continue;
5700 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5701 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5702 $reference = file_storage::pack_reference($reference);
5703 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5704 $this->notify_success($info);
5705 continue;
5706 } else {
5707 $this->notify_failure($info, 'referenced file not found');
5708 continue;
5711 // If we are at other site, we can't restore this alias.
5712 } else {
5713 $this->notify_failure($info, 'restoring at another site');
5714 continue;
5717 } else {
5718 // This is a reference to some external file such as dropbox.
5719 // If we are restoring to the same site, keep the reference untouched and
5720 // restore the alias as is.
5721 if ($this->task->is_samesite()) {
5722 $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
5723 $this->notify_success($info);
5724 continue;
5726 // If we are at other site, we can't restore this alias.
5727 } else {
5728 $this->notify_failure($info, 'restoring at another site');
5729 continue;
5733 $progress->end_progress();
5734 $rs->close();
5738 * Choose the repository instance that should handle the alias.
5740 * At the same site, we can rely on repository instance id and we just
5741 * check it still exists. On other site, try to find matching Server files or
5742 * Legacy course files repository instance. Return null if no matching
5743 * repository instance can be found.
5745 * @param stdClass $info
5746 * @return repository|null
5748 private function choose_repository(stdClass $info) {
5749 global $DB, $CFG;
5750 require_once($CFG->dirroot.'/repository/lib.php');
5752 if ($this->task->is_samesite()) {
5753 // We can rely on repository instance id.
5755 if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
5756 return $this->cachereposbyid[$info->oldfile->repositoryid];
5759 $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
5761 try {
5762 $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
5763 return $this->cachereposbyid[$info->oldfile->repositoryid];
5764 } catch (Exception $e) {
5765 $this->cachereposbyid[$info->oldfile->repositoryid] = null;
5766 return null;
5769 } else {
5770 // We can rely on repository type only.
5772 if (empty($info->oldfile->repositorytype)) {
5773 return null;
5776 if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
5777 return $this->cachereposbytype[$info->oldfile->repositorytype];
5780 $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
5782 // Both Server files and Legacy course files repositories have a single
5783 // instance at the system context to use. Let us try to find it.
5784 if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5785 || $info->oldfile->repositorytype === 'contentbank') {
5786 $sql = "SELECT ri.id
5787 FROM {repository} r
5788 JOIN {repository_instances} ri ON ri.typeid = r.id
5789 WHERE r.type = ? AND ri.contextid = ?";
5790 $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
5791 if (empty($ris)) {
5792 return null;
5794 $repoids = array_keys($ris);
5795 $repoid = reset($repoids);
5796 try {
5797 $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
5798 return $this->cachereposbytype[$info->oldfile->repositorytype];
5799 } catch (Exception $e) {
5800 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5801 return null;
5805 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5806 return null;
5811 * Let the user know that the given alias was successfully restored
5813 * @param stdClass $info
5815 private function notify_success(stdClass $info) {
5816 $filedesc = $this->describe_alias($info);
5817 $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
5821 * Let the user know that the given alias can't be restored
5823 * @param stdClass $info
5824 * @param string $reason detailed reason to be logged
5826 private function notify_failure(stdClass $info, $reason = '') {
5827 $filedesc = $this->describe_alias($info);
5828 if ($reason) {
5829 $reason = ' ('.$reason.')';
5831 $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
5832 $this->add_result_item('file_aliases_restore_failures', $filedesc);
5836 * Return a human readable description of the alias file
5838 * @param stdClass $info
5839 * @return string
5841 private function describe_alias(stdClass $info) {
5843 $filedesc = $this->expected_alias_location($info->newfile);
5845 if (!is_null($info->oldfile->source)) {
5846 $filedesc .= ' ('.$info->oldfile->source.')';
5849 return $filedesc;
5853 * Return the expected location of a file
5855 * Please note this may and may not work as a part of URL to pluginfile.php
5856 * (depends on how the given component/filearea deals with the itemid).
5858 * @param stdClass $filerecord
5859 * @return string
5861 private function expected_alias_location($filerecord) {
5863 $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
5864 if (!is_null($filerecord->itemid)) {
5865 $filedesc .= '/'.$filerecord->itemid;
5867 $filedesc .= $filerecord->filepath.$filerecord->filename;
5869 return $filedesc;
5873 * Append a value to the given resultset
5875 * @param string $name name of the result containing a list of values
5876 * @param mixed $value value to add as another item in that result
5878 private function add_result_item($name, $value) {
5880 $results = $this->task->get_results();
5882 if (isset($results[$name])) {
5883 if (!is_array($results[$name])) {
5884 throw new coding_exception('Unable to append a result item into a non-array structure.');
5886 $current = $results[$name];
5887 $current[] = $value;
5888 $this->task->add_result(array($name => $current));
5890 } else {
5891 $this->task->add_result(array($name => array($value)));
5898 * Helper code for use by any plugin that stores question attempt data that it needs to back up.
5900 trait restore_questions_attempt_data_trait {
5901 /** @var array question_attempt->id to qtype. */
5902 protected $qtypes = array();
5903 /** @var array question_attempt->id to questionid. */
5904 protected $newquestionids = array();
5907 * Attach below $element (usually attempts) the needed restore_path_elements
5908 * to restore question_usages and all they contain.
5910 * If you use the $nameprefix parameter, then you will need to implement some
5911 * extra methods in your class, like
5913 * protected function process_{nameprefix}question_attempt($data) {
5914 * $this->restore_question_usage_worker($data, '{nameprefix}');
5916 * protected function process_{nameprefix}question_attempt($data) {
5917 * $this->restore_question_attempt_worker($data, '{nameprefix}');
5919 * protected function process_{nameprefix}question_attempt_step($data) {
5920 * $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5923 * @param restore_path_element $element the parent element that the usages are stored inside.
5924 * @param array $paths the paths array that is being built.
5925 * @param string $nameprefix should match the prefix passed to the corresponding
5926 * backup_questions_activity_structure_step::add_question_usages call.
5928 protected function add_question_usages($element, &$paths, $nameprefix = '') {
5929 // Check $element is restore_path_element
5930 if (! $element instanceof restore_path_element) {
5931 throw new restore_step_exception('element_must_be_restore_path_element', $element);
5934 // Check $paths is one array
5935 if (!is_array($paths)) {
5936 throw new restore_step_exception('paths_must_be_array', $paths);
5938 $paths[] = new restore_path_element($nameprefix . 'question_usage',
5939 $element->get_path() . "/{$nameprefix}question_usage");
5940 $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5941 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5942 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5943 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5944 true);
5945 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5946 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5950 * Process question_usages
5952 public function process_question_usage($data) {
5953 $this->restore_question_usage_worker($data, '');
5957 * Process question_attempts
5959 public function process_question_attempt($data) {
5960 $this->restore_question_attempt_worker($data, '');
5964 * Process question_attempt_steps
5966 public function process_question_attempt_step($data) {
5967 $this->restore_question_attempt_step_worker($data, '');
5971 * This method does the actual work for process_question_usage or
5972 * process_{nameprefix}_question_usage.
5973 * @param array $data the data from the XML file.
5974 * @param string $nameprefix the element name prefix.
5976 protected function restore_question_usage_worker($data, $nameprefix) {
5977 global $DB;
5979 // Clear our caches.
5980 $this->qtypes = array();
5981 $this->newquestionids = array();
5983 $data = (object)$data;
5984 $oldid = $data->id;
5986 $data->contextid = $this->task->get_contextid();
5988 // Everything ready, insert (no mapping needed)
5989 $newitemid = $DB->insert_record('question_usages', $data);
5991 $this->inform_new_usage_id($newitemid);
5993 $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
5997 * When process_question_usage creates the new usage, it calls this method
5998 * to let the activity link to the new usage. For example, the quiz uses
5999 * this method to set quiz_attempts.uniqueid to the new usage id.
6000 * @param integer $newusageid
6002 abstract protected function inform_new_usage_id($newusageid);
6005 * This method does the actual work for process_question_attempt or
6006 * process_{nameprefix}_question_attempt.
6007 * @param array $data the data from the XML file.
6008 * @param string $nameprefix the element name prefix.
6010 protected function restore_question_attempt_worker($data, $nameprefix) {
6011 global $DB;
6013 $data = (object)$data;
6014 $oldid = $data->id;
6016 $questioncreated = $this->get_mappingid('question_created', $data->questionid) ? true : false;
6017 $question = $this->get_mapping('question', $data->questionid);
6018 if ($questioncreated) {
6019 $data->questionid = $question->newitemid;
6022 $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
6024 if (!property_exists($data, 'variant')) {
6025 $data->variant = 1;
6028 if (!property_exists($data, 'maxfraction')) {
6029 $data->maxfraction = 1;
6032 $newitemid = $DB->insert_record('question_attempts', $data);
6034 $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
6035 if (isset($question->info->qtype)) {
6036 $qtype = $question->info->qtype;
6037 } else {
6038 $qtype = $DB->get_record('question', ['id' => $data->questionid])->qtype;
6040 $this->qtypes[$newitemid] = $qtype;
6041 $this->newquestionids[$newitemid] = $data->questionid;
6045 * This method does the actual work for process_question_attempt_step or
6046 * process_{nameprefix}_question_attempt_step.
6047 * @param array $data the data from the XML file.
6048 * @param string $nameprefix the element name prefix.
6050 protected function restore_question_attempt_step_worker($data, $nameprefix) {
6051 global $DB;
6053 $data = (object)$data;
6054 $oldid = $data->id;
6056 // Pull out the response data.
6057 $response = array();
6058 if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
6059 foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
6060 $response[$variable['name']] = $variable['value'];
6063 unset($data->response);
6065 $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
6066 $data->userid = $this->get_mappingid('user', $data->userid);
6068 // Everything ready, insert and create mapping (needed by question_sessions)
6069 $newitemid = $DB->insert_record('question_attempt_steps', $data);
6070 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
6072 // Now process the response data.
6073 $response = $this->questions_recode_response_data(
6074 $this->qtypes[$data->questionattemptid],
6075 $this->newquestionids[$data->questionattemptid],
6076 $data->sequencenumber, $response);
6078 foreach ($response as $name => $value) {
6079 $row = new stdClass();
6080 $row->attemptstepid = $newitemid;
6081 $row->name = $name;
6082 $row->value = $value;
6083 $DB->insert_record('question_attempt_step_data', $row, false);
6088 * Recode the respones data for a particular step of an attempt at at particular question.
6089 * @param string $qtype the question type.
6090 * @param int $newquestionid the question id.
6091 * @param int $sequencenumber the sequence number.
6092 * @param array $response the response data to recode.
6094 public function questions_recode_response_data(
6095 $qtype, $newquestionid, $sequencenumber, array $response) {
6096 $qtyperestorer = $this->get_qtype_restorer($qtype);
6097 if ($qtyperestorer) {
6098 $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
6100 return $response;
6104 * Given a list of question->ids, separated by commas, returns the
6105 * recoded list, with all the restore question mappings applied.
6106 * Note: Used by quiz->questions and quiz_attempts->layout
6107 * Note: 0 = page break (unconverted)
6109 protected function questions_recode_layout($layout) {
6110 // Extracts question id from sequence
6111 if ($questionids = explode(',', $layout)) {
6112 foreach ($questionids as $id => $questionid) {
6113 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
6114 $newquestionid = $this->get_mappingid('question', $questionid);
6115 $questionids[$id] = $newquestionid;
6119 return implode(',', $questionids);
6123 * Get the restore_qtype_plugin subclass for a specific question type.
6124 * @param string $qtype e.g. multichoice.
6125 * @return restore_qtype_plugin instance.
6127 protected function get_qtype_restorer($qtype) {
6128 // Build one static cache to store {@link restore_qtype_plugin}
6129 // while we are needing them, just to save zillions of instantiations
6130 // or using static stuff that will break our nice API
6131 static $qtypeplugins = array();
6133 if (!isset($qtypeplugins[$qtype])) {
6134 $classname = 'restore_qtype_' . $qtype . '_plugin';
6135 if (class_exists($classname)) {
6136 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
6137 } else {
6138 $qtypeplugins[$qtype] = null;
6141 return $qtypeplugins[$qtype];
6144 protected function after_execute() {
6145 parent::after_execute();
6147 // Restore any files belonging to responses.
6148 foreach (question_engine::get_all_response_file_areas() as $filearea) {
6149 $this->add_related_files('question', $filearea, 'question_attempt_step');
6155 * Helper trait to restore question reference data.
6157 trait restore_question_reference_data_trait {
6160 * Attach the question reference data to the restore.
6162 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6163 * @param array $paths the paths array that is being built to describe the structure.
6165 protected function add_question_references($element, &$paths) {
6166 // Check $element is restore_path_element.
6167 if (! $element instanceof restore_path_element) {
6168 throw new restore_step_exception('element_must_be_restore_path_element', $element);
6171 // Check $paths is one array.
6172 if (!is_array($paths)) {
6173 throw new restore_step_exception('paths_must_be_array', $paths);
6176 $paths[] = new restore_path_element('question_reference',
6177 $element->get_path() . '/question_reference');
6181 * Process question references which replaces the direct connection to quiz slots to question.
6183 * @param array $data the data from the XML file.
6185 public function process_question_reference($data) {
6186 global $DB;
6187 $data = (object) $data;
6188 $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6189 $data->itemid = $this->get_new_parentid('quiz_question_instance');
6190 if ($entry = $this->get_mappingid('question_bank_entry', $data->questionbankentryid)) {
6191 $data->questionbankentryid = $entry;
6193 $DB->insert_record('question_references', $data);
6198 * Helper trait to restore question set reference data.
6200 trait restore_question_set_reference_data_trait {
6203 * Attach the question reference data to the restore.
6205 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6206 * @param array $paths the paths array that is being built to describe the structure.
6208 protected function add_question_set_references($element, &$paths) {
6209 // Check $element is restore_path_element.
6210 if (! $element instanceof restore_path_element) {
6211 throw new restore_step_exception('element_must_be_restore_path_element', $element);
6214 // Check $paths is one array.
6215 if (!is_array($paths)) {
6216 throw new restore_step_exception('paths_must_be_array', $paths);
6219 $paths[] = new restore_path_element('question_set_reference',
6220 $element->get_path() . '/question_set_reference');
6224 * Process question set references data which replaces the random qtype.
6226 * @param array $data the data from the XML file.
6228 public function process_question_set_reference($data) {
6229 global $DB;
6230 $data = (object) $data;
6231 $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6232 $data->itemid = $this->get_new_parentid('quiz_question_instance');
6233 $filtercondition = json_decode($data->filtercondition, true);
6235 if (!isset($filtercondition['filter'])) {
6236 // Pre-4.3, convert the old filtercondition format to the new format.
6237 $filtercondition = \core_question\question_reference_manager::convert_legacy_set_reference_filter_condition(
6238 $filtercondition);
6241 // Map category id used for category filter condition and corresponding context id.
6242 $oldcategoryid = $filtercondition['filter']['category']['values'][0];
6243 $newcategoryid = $this->get_mappingid('question_category', $oldcategoryid);
6244 $filtercondition['filter']['category']['values'][0] = $newcategoryid;
6246 if ($context = $this->get_mappingid('context', $data->questionscontextid)) {
6247 $data->questionscontextid = $context;
6250 $filtercondition['cat'] = implode(',', [
6251 $filtercondition['filter']['category']['values'][0],
6252 $data->questionscontextid,
6255 $data->filtercondition = json_encode($filtercondition);
6257 $DB->insert_record('question_set_references', $data);
6263 * Abstract structure step to help activities that store question attempt data.
6265 * @copyright 2011 The Open University
6266 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6268 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
6269 use restore_questions_attempt_data_trait;
6270 use restore_question_reference_data_trait;
6271 use restore_question_set_reference_data_trait;
6273 /** @var \question_engine_attempt_upgrader manages upgrading all the question attempts. */
6274 private $attemptupgrader;
6277 * Attach below $element (usually attempts) the needed restore_path_elements
6278 * to restore question attempt data from Moodle 2.0.
6280 * When using this method, the parent element ($element) must be defined with
6281 * $grouped = true. Then, in that elements process method, you must call
6282 * {@link process_legacy_attempt_data()} with the groupded data. See, for
6283 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
6284 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6285 * @param array $paths the paths array that is being built to describe the
6286 * structure.
6288 protected function add_legacy_question_attempt_data($element, &$paths) {
6289 global $CFG;
6290 require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
6292 // Check $element is restore_path_element
6293 if (!($element instanceof restore_path_element)) {
6294 throw new restore_step_exception('element_must_be_restore_path_element', $element);
6296 // Check $paths is one array
6297 if (!is_array($paths)) {
6298 throw new restore_step_exception('paths_must_be_array', $paths);
6301 $paths[] = new restore_path_element('question_state',
6302 $element->get_path() . '/states/state');
6303 $paths[] = new restore_path_element('question_session',
6304 $element->get_path() . '/sessions/session');
6307 protected function get_attempt_upgrader() {
6308 if (empty($this->attemptupgrader)) {
6309 $this->attemptupgrader = new question_engine_attempt_upgrader();
6310 $this->attemptupgrader->prepare_to_restore();
6312 return $this->attemptupgrader;
6316 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
6317 * @param object $data contains all the grouped attempt data to process.
6318 * @param object $quiz data about the activity the attempts belong to. Required
6319 * fields are (basically this only works for the quiz module):
6320 * oldquestions => list of question ids in this activity - using old ids.
6321 * preferredbehaviour => the behaviour to use for questionattempts.
6323 protected function process_legacy_quiz_attempt_data($data, $quiz) {
6324 global $DB;
6325 $upgrader = $this->get_attempt_upgrader();
6327 $data = (object)$data;
6329 $layout = explode(',', $data->layout);
6330 $newlayout = $layout;
6332 // Convert each old question_session into a question_attempt.
6333 $qas = array();
6334 foreach (explode(',', $quiz->oldquestions) as $questionid) {
6335 if ($questionid == 0) {
6336 continue;
6339 $newquestionid = $this->get_mappingid('question', $questionid);
6340 if (!$newquestionid) {
6341 throw new restore_step_exception('questionattemptreferstomissingquestion',
6342 $questionid, $questionid);
6345 $question = $upgrader->load_question($newquestionid, $quiz->id);
6347 foreach ($layout as $key => $qid) {
6348 if ($qid == $questionid) {
6349 $newlayout[$key] = $newquestionid;
6353 list($qsession, $qstates) = $this->find_question_session_and_states(
6354 $data, $questionid);
6356 if (empty($qsession) || empty($qstates)) {
6357 throw new restore_step_exception('questionattemptdatamissing',
6358 $questionid, $questionid);
6361 list($qsession, $qstates) = $this->recode_legacy_response_data(
6362 $question, $qsession, $qstates);
6364 $data->layout = implode(',', $newlayout);
6365 $qas[$newquestionid] = $upgrader->convert_question_attempt(
6366 $quiz, $data, $question, $qsession, $qstates);
6369 // Now create a new question_usage.
6370 $usage = new stdClass();
6371 $usage->component = 'mod_quiz';
6372 $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
6373 $usage->preferredbehaviour = $quiz->preferredbehaviour;
6374 $usage->id = $DB->insert_record('question_usages', $usage);
6376 $this->inform_new_usage_id($usage->id);
6378 $data->uniqueid = $usage->id;
6379 $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
6380 $this->questions_recode_layout($quiz->oldquestions));
6383 protected function find_question_session_and_states($data, $questionid) {
6384 $qsession = null;
6385 foreach ($data->sessions['session'] as $session) {
6386 if ($session['questionid'] == $questionid) {
6387 $qsession = (object) $session;
6388 break;
6392 $qstates = array();
6393 foreach ($data->states['state'] as $state) {
6394 if ($state['question'] == $questionid) {
6395 // It would be natural to use $state['seq_number'] as the array-key
6396 // here, but it seems that buggy behaviour in 2.0 and early can
6397 // mean that that is not unique, so we use id, which is guaranteed
6398 // to be unique.
6399 $qstates[$state['id']] = (object) $state;
6402 ksort($qstates);
6403 $qstates = array_values($qstates);
6405 return array($qsession, $qstates);
6409 * Recode any ids in the response data
6410 * @param object $question the question data
6411 * @param object $qsession the question sessions.
6412 * @param array $qstates the question states.
6414 protected function recode_legacy_response_data($question, $qsession, $qstates) {
6415 $qsession->questionid = $question->id;
6417 foreach ($qstates as &$state) {
6418 $state->question = $question->id;
6419 $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
6422 return array($qsession, $qstates);
6426 * Recode the legacy answer field.
6427 * @param object $state the state to recode the answer of.
6428 * @param string $qtype the question type.
6430 public function restore_recode_legacy_answer($state, $qtype) {
6431 $restorer = $this->get_qtype_restorer($qtype);
6432 if ($restorer) {
6433 return $restorer->recode_legacy_state_answer($state);
6434 } else {
6435 return $state->answer;
6442 * Restore completion defaults for each module type
6444 * @package core_backup
6445 * @copyright 2017 Marina Glancy
6446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6448 class restore_completion_defaults_structure_step extends restore_structure_step {
6450 * To conditionally decide if this step must be executed.
6452 protected function execute_condition() {
6453 // No completion on the front page.
6454 if ($this->get_courseid() == SITEID) {
6455 return false;
6458 // No default completion info found, don't execute.
6459 $fullpath = $this->task->get_taskbasepath();
6460 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
6461 if (!file_exists($fullpath)) {
6462 return false;
6465 // Arrived here, execute the step.
6466 return true;
6470 * Function that will return the structure to be processed by this restore_step.
6472 * @return restore_path_element[]
6474 protected function define_structure() {
6475 return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
6479 * Processor for path element 'completion_defaults'
6481 * @param stdClass|array $data
6483 protected function process_completion_defaults($data) {
6484 global $DB;
6486 $data = (array)$data;
6487 $oldid = $data['id'];
6488 unset($data['id']);
6490 // Find the module by name since id may be different in another site.
6491 if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
6492 return;
6494 unset($data['modulename']);
6496 // Find the existing record.
6497 $newid = $DB->get_field('course_completion_defaults', 'id',
6498 ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
6499 if (!$newid) {
6500 $newid = $DB->insert_record('course_completion_defaults',
6501 ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
6502 } else {
6503 $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
6506 // Save id mapping for restoring associated events.
6507 $this->set_mapping('course_completion_defaults', $oldid, $newid);
6512 * Index course after restore.
6514 * @package core_backup
6515 * @copyright 2017 The Open University
6516 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6518 class restore_course_search_index extends restore_execution_step {
6520 * When this step is executed, we add the course context to the queue for reindexing.
6522 protected function define_execution() {
6523 $context = \context_course::instance($this->task->get_courseid());
6524 \core_search\manager::request_index($context);
6529 * Index activity after restore (when not restoring whole course).
6531 * @package core_backup
6532 * @copyright 2017 The Open University
6533 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6535 class restore_activity_search_index extends restore_execution_step {
6537 * When this step is executed, we add the activity context to the queue for reindexing.
6539 protected function define_execution() {
6540 $context = \context::instance_by_id($this->task->get_contextid());
6541 \core_search\manager::request_index($context);
6546 * Index block after restore (when not restoring whole course).
6548 * @package core_backup
6549 * @copyright 2017 The Open University
6550 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6552 class restore_block_search_index extends restore_execution_step {
6554 * When this step is executed, we add the block context to the queue for reindexing.
6556 protected function define_execution() {
6557 // A block in the restore list may be skipped because a duplicate is detected.
6558 // In this case, there is no new blockid (or context) to get.
6559 if (!empty($this->task->get_blockid())) {
6560 $context = \context_block::instance($this->task->get_blockid());
6561 \core_search\manager::request_index($context);
6567 * Restore action events.
6569 * @package core_backup
6570 * @copyright 2017 onwards Ankit Agarwal
6571 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6573 class restore_calendar_action_events extends restore_execution_step {
6575 * What to do when this step is executed.
6577 protected function define_execution() {
6578 // We just queue the task here rather trying to recreate everything manually.
6579 // The task will automatically populate all data.
6580 $task = new \core\task\refresh_mod_calendar_events_task();
6581 $task->set_custom_data(array('courseid' => $this->get_courseid()));
6582 \core\task\manager::queue_adhoc_task($task, true);