MDL-60915 core_dml: fix miscellaneous incorrect recordset usage
[moodle.git] / backup / moodle2 / restore_stepslib.php
blob529645f9bf899b6dfe937b2ada4fdcc055375452
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 * delete the temp dir used by backup/restore (conditionally),
61 * delete old directories and drop temp ids table
63 class restore_drop_and_clean_temp_stuff extends restore_execution_step {
65 protected function define_execution() {
66 global $CFG;
67 restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
68 $progress = $this->task->get_progress();
69 $progress->start_progress('Deleting backup dir');
70 backup_helper::delete_old_backup_dirs(strtotime('-1 week'), $progress); // Delete > 1 week old temp dirs.
71 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
72 backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir
74 $progress->end_progress();
78 /**
79 * Restore calculated grade items, grade categories etc
81 class restore_gradebook_structure_step extends restore_structure_step {
83 /**
84 * To conditionally decide if this step must be executed
85 * Note the "settings" conditions are evaluated in the
86 * corresponding task. Here we check for other conditions
87 * not being restore settings (files, site settings...)
89 protected function execute_condition() {
90 global $CFG, $DB;
92 if ($this->get_courseid() == SITEID) {
93 return false;
96 // No gradebook info found, don't execute
97 $fullpath = $this->task->get_taskbasepath();
98 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
99 if (!file_exists($fullpath)) {
100 return false;
103 // Some module present in backup file isn't available to restore
104 // in this site, don't execute
105 if ($this->task->is_missing_modules()) {
106 return false;
109 // Some activity has been excluded to be restored, don't execute
110 if ($this->task->is_excluding_activities()) {
111 return false;
114 // There should only be one grade category (the 1 associated with the course itself)
115 // If other categories already exist we're restoring into an existing course.
116 // Restoring categories into a course with an existing category structure is unlikely to go well
117 $category = new stdclass();
118 $category->courseid = $this->get_courseid();
119 $catcount = $DB->count_records('grade_categories', (array)$category);
120 if ($catcount>1) {
121 return false;
124 // Identify the backup we're dealing with.
125 $backuprelease = floatval($this->get_task()->get_info()->backup_release); // The major version: 2.9, 3.0, ...
126 $backupbuild = 0;
127 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
128 if (!empty($matches[1])) {
129 $backupbuild = (int) $matches[1]; // The date of Moodle build at the time of the backup.
132 // On older versions the freeze value has to be converted.
133 // We do this from here as it is happening right before the file is read.
134 // This only targets the backup files that can contain the legacy freeze.
135 if ($backupbuild > 20150618 && ($backuprelease < 3.0 || $backupbuild < 20160527)) {
136 $this->rewrite_step_backup_file_for_legacy_freeze($fullpath);
139 // Arrived here, execute the step
140 return true;
143 protected function define_structure() {
144 $paths = array();
145 $userinfo = $this->task->get_setting_value('users');
147 $paths[] = new restore_path_element('attributes', '/gradebook/attributes');
148 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
149 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
150 if ($userinfo) {
151 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
153 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
154 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
156 return $paths;
159 protected function process_attributes($data) {
160 // For non-merge restore types:
161 // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
162 $target = $this->get_task()->get_target();
163 if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) {
164 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
166 if (!empty($data['calculations_freeze'])) {
167 if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING ||
168 $target == backup::TARGET_EXISTING_DELETING) {
169 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
174 protected function process_grade_item($data) {
175 global $DB;
177 $data = (object)$data;
179 $oldid = $data->id;
180 $data->course = $this->get_courseid();
182 $data->courseid = $this->get_courseid();
184 if ($data->itemtype=='manual') {
185 // manual grade items store category id in categoryid
186 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
187 // if mapping failed put in course's grade category
188 if (NULL == $data->categoryid) {
189 $coursecat = grade_category::fetch_course_category($this->get_courseid());
190 $data->categoryid = $coursecat->id;
192 } else if ($data->itemtype=='course') {
193 // course grade item stores their category id in iteminstance
194 $coursecat = grade_category::fetch_course_category($this->get_courseid());
195 $data->iteminstance = $coursecat->id;
196 } else if ($data->itemtype=='category') {
197 // category grade items store their category id in iteminstance
198 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
199 } else {
200 throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
203 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
204 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
206 $data->locktime = $this->apply_date_offset($data->locktime);
208 $coursecategory = $newitemid = null;
209 //course grade item should already exist so updating instead of inserting
210 if($data->itemtype=='course') {
211 //get the ID of the already created grade item
212 $gi = new stdclass();
213 $gi->courseid = $this->get_courseid();
214 $gi->itemtype = $data->itemtype;
216 //need to get the id of the grade_category that was automatically created for the course
217 $category = new stdclass();
218 $category->courseid = $this->get_courseid();
219 $category->parent = null;
220 //course category fullname starts out as ? but may be edited
221 //$category->fullname = '?';
222 $coursecategory = $DB->get_record('grade_categories', (array)$category);
223 $gi->iteminstance = $coursecategory->id;
225 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
226 if (!empty($existinggradeitem)) {
227 $data->id = $newitemid = $existinggradeitem->id;
228 $DB->update_record('grade_items', $data);
230 } else if ($data->itemtype == 'manual') {
231 // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
232 $gi = array(
233 'itemtype' => $data->itemtype,
234 'courseid' => $data->courseid,
235 'itemname' => $data->itemname,
236 'categoryid' => $data->categoryid,
238 $newitemid = $DB->get_field('grade_items', 'id', $gi);
241 if (empty($newitemid)) {
242 //in case we found the course category but still need to insert the course grade item
243 if ($data->itemtype=='course' && !empty($coursecategory)) {
244 $data->iteminstance = $coursecategory->id;
247 $newitemid = $DB->insert_record('grade_items', $data);
249 $this->set_mapping('grade_item', $oldid, $newitemid);
252 protected function process_grade_grade($data) {
253 global $DB;
255 $data = (object)$data;
256 $oldid = $data->id;
257 $olduserid = $data->userid;
259 $data->itemid = $this->get_new_parentid('grade_item');
261 $data->userid = $this->get_mappingid('user', $data->userid, null);
262 if (!empty($data->userid)) {
263 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
264 $data->locktime = $this->apply_date_offset($data->locktime);
266 $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
267 if ($gradeexists) {
268 $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
269 $this->log($message, backup::LOG_DEBUG);
270 } else {
271 $newitemid = $DB->insert_record('grade_grades', $data);
272 $this->set_mapping('grade_grades', $oldid, $newitemid);
274 } else {
275 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
276 $this->log($message, backup::LOG_DEBUG);
280 protected function process_grade_category($data) {
281 global $DB;
283 $data = (object)$data;
284 $oldid = $data->id;
286 $data->course = $this->get_courseid();
287 $data->courseid = $data->course;
289 $newitemid = null;
290 //no parent means a course level grade category. That may have been created when the course was created
291 if(empty($data->parent)) {
292 //parent was being saved as 0 when it should be null
293 $data->parent = null;
295 //get the already created course level grade category
296 $category = new stdclass();
297 $category->courseid = $this->get_courseid();
298 $category->parent = null;
300 $coursecategory = $DB->get_record('grade_categories', (array)$category);
301 if (!empty($coursecategory)) {
302 $data->id = $newitemid = $coursecategory->id;
303 $DB->update_record('grade_categories', $data);
307 // Add a warning about a removed setting.
308 if (!empty($data->aggregatesubcats)) {
309 set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
312 //need to insert a course category
313 if (empty($newitemid)) {
314 $newitemid = $DB->insert_record('grade_categories', $data);
316 $this->set_mapping('grade_category', $oldid, $newitemid);
318 protected function process_grade_letter($data) {
319 global $DB;
321 $data = (object)$data;
322 $oldid = $data->id;
324 $data->contextid = context_course::instance($this->get_courseid())->id;
326 $gradeletter = (array)$data;
327 unset($gradeletter['id']);
328 if (!$DB->record_exists('grade_letters', $gradeletter)) {
329 $newitemid = $DB->insert_record('grade_letters', $data);
330 } else {
331 $newitemid = $data->id;
334 $this->set_mapping('grade_letter', $oldid, $newitemid);
336 protected function process_grade_setting($data) {
337 global $DB;
339 $data = (object)$data;
340 $oldid = $data->id;
342 $data->courseid = $this->get_courseid();
344 $target = $this->get_task()->get_target();
345 if ($data->name == 'minmaxtouse' &&
346 ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) {
347 // We never restore minmaxtouse during merge.
348 return;
351 if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
352 $newitemid = $DB->insert_record('grade_settings', $data);
353 } else {
354 $newitemid = $data->id;
357 if (!empty($oldid)) {
358 // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
359 $this->set_mapping('grade_setting', $oldid, $newitemid);
364 * put all activity grade items in the correct grade category and mark all for recalculation
366 protected function after_execute() {
367 global $DB;
369 $conditions = array(
370 'backupid' => $this->get_restoreid(),
371 'itemname' => 'grade_item'//,
372 //'itemid' => $itemid
374 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
376 // We need this for calculation magic later on.
377 $mappings = array();
379 if (!empty($rs)) {
380 foreach($rs as $grade_item_backup) {
382 // Store the oldid with the new id.
383 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
385 $updateobj = new stdclass();
386 $updateobj->id = $grade_item_backup->newitemid;
388 //if this is an activity grade item that needs to be put back in its correct category
389 if (!empty($grade_item_backup->parentitemid)) {
390 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
391 if (!is_null($oldcategoryid)) {
392 $updateobj->categoryid = $oldcategoryid;
393 $DB->update_record('grade_items', $updateobj);
395 } else {
396 //mark course and category items as needing to be recalculated
397 $updateobj->needsupdate=1;
398 $DB->update_record('grade_items', $updateobj);
402 $rs->close();
404 // We need to update the calculations for calculated grade items that may reference old
405 // grade item ids using ##gi\d+##.
406 // $mappings can be empty, use 0 if so (won't match ever)
407 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
408 $sql = "SELECT gi.id, gi.calculation
409 FROM {grade_items} gi
410 WHERE gi.id {$sql} AND
411 calculation IS NOT NULL";
412 $rs = $DB->get_recordset_sql($sql, $params);
413 foreach ($rs as $gradeitem) {
414 // Collect all of the used grade item id references
415 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
416 // This calculation doesn't reference any other grade items... EASY!
417 continue;
419 // For this next bit we are going to do the replacement of id's in two steps:
420 // 1. We will replace all old id references with a special mapping reference.
421 // 2. We will replace all mapping references with id's
422 // Why do we do this?
423 // Because there potentially there will be an overlap of ids within the query and we
424 // we substitute the wrong id.. safest way around this is the two step system
425 $calculationmap = array();
426 $mapcount = 0;
427 foreach ($matches[1] as $match) {
428 // Check that the old id is known to us, if not it was broken to begin with and will
429 // continue to be broken.
430 if (!array_key_exists($match, $mappings)) {
431 continue;
433 // Our special mapping key
434 $mapping = '##MAPPING'.$mapcount.'##';
435 // The old id that exists within the calculation now
436 $oldid = '##gi'.$match.'##';
437 // The new id that we want to replace the old one with.
438 $newid = '##gi'.$mappings[$match].'##';
439 // Replace in the special mapping key
440 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
441 // And record the mapping
442 $calculationmap[$mapping] = $newid;
443 $mapcount++;
445 // Iterate all special mappings for this calculation and replace in the new id's
446 foreach ($calculationmap as $mapping => $newid) {
447 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
449 // Update the calculation now that its being remapped
450 $DB->update_record('grade_items', $gradeitem);
452 $rs->close();
454 // Need to correct the grade category path and parent
455 $conditions = array(
456 'courseid' => $this->get_courseid()
459 $rs = $DB->get_recordset('grade_categories', $conditions);
460 // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
461 foreach ($rs as $gc) {
462 if (!empty($gc->parent)) {
463 $grade_category = new stdClass();
464 $grade_category->id = $gc->id;
465 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
466 $DB->update_record('grade_categories', $grade_category);
469 $rs->close();
471 // Now we can rebuild all the paths
472 $rs = $DB->get_recordset('grade_categories', $conditions);
473 foreach ($rs as $gc) {
474 $grade_category = new stdClass();
475 $grade_category->id = $gc->id;
476 $grade_category->path = grade_category::build_path($gc);
477 $grade_category->depth = substr_count($grade_category->path, '/') - 1;
478 $DB->update_record('grade_categories', $grade_category);
480 $rs->close();
482 // Check what to do with the minmaxtouse setting.
483 $this->check_minmaxtouse();
485 // Freeze gradebook calculations if needed.
486 $this->gradebook_calculation_freeze();
488 // Restore marks items as needing update. Update everything now.
489 grade_regrade_final_grades($this->get_courseid());
493 * Freeze gradebook calculation if needed.
495 * This is similar to various upgrade scripts that check if the freeze is needed.
497 protected function gradebook_calculation_freeze() {
498 global $CFG;
499 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
500 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
501 $backupbuild = (int)$matches[1];
502 // The function floatval will return a float even if there is text mixed with the release number.
503 $backuprelease = floatval($this->get_task()->get_info()->backup_release);
505 // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
506 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) {
507 require_once($CFG->libdir . '/db/upgradelib.php');
508 upgrade_extra_credit_weightoverride($this->get_courseid());
510 // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
511 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) {
512 require_once($CFG->libdir . '/db/upgradelib.php');
513 upgrade_calculated_grade_items($this->get_courseid());
515 // Courses from before 3.1 (20160518) may have a letter boundary problem and should be checked for this issue.
516 // Backups from before and including 2.9 could have a build number that is greater than 20160518 and should
517 // be checked for this problem.
518 if (!$gradebookcalculationsfreeze && ($backupbuild < 20160518 || $backuprelease <= 2.9)) {
519 require_once($CFG->libdir . '/db/upgradelib.php');
520 upgrade_course_letter_boundary($this->get_courseid());
526 * Checks what should happen with the course grade setting minmaxtouse.
528 * This is related to the upgrade step at the time the setting was added.
530 * @see MDL-48618
531 * @return void
533 protected function check_minmaxtouse() {
534 global $CFG, $DB;
535 require_once($CFG->libdir . '/gradelib.php');
537 $userinfo = $this->task->get_setting_value('users');
538 $settingname = 'minmaxtouse';
539 $courseid = $this->get_courseid();
540 $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
541 $version28start = 2014111000.00;
542 $version28last = 2014111006.05;
543 $version29start = 2015051100.00;
544 $version29last = 2015060400.02;
546 $target = $this->get_task()->get_target();
547 if ($minmaxtouse === false &&
548 ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
549 // The setting was not found because this setting did not exist at the time the backup was made.
550 // And we are not restoring as merge, in which case we leave the course as it was.
551 $version = $this->get_task()->get_info()->moodle_version;
553 if ($version < $version28start) {
554 // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
555 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
556 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
559 } else if (($version >= $version28start && $version < $version28last) ||
560 ($version >= $version29start && $version < $version29last)) {
561 // They should be using grade_grade when the course has inconsistencies.
563 $sql = "SELECT gi.id
564 FROM {grade_items} gi
565 JOIN {grade_grades} gg
566 ON gg.itemid = gi.id
567 WHERE gi.courseid = ?
568 AND (gi.itemtype != ? AND gi.itemtype != ?)
569 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
571 // The course can only have inconsistencies when we restore the user info,
572 // we do not need to act on existing grades that were not restored as part of this backup.
573 if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
575 // Display the notice as we do during upgrade.
576 set_config('show_min_max_grades_changed_' . $courseid, 1);
578 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
579 // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
580 // If they are using the site-wide grade_grade setting, we only want to notice them.
581 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
585 } else {
586 // This should never happen because from now on minmaxtouse is always saved in backups.
592 * Rewrite step definition to handle the legacy freeze attribute.
594 * In previous backups the calculations_freeze property was stored as an attribute of the
595 * top level node <gradebook>. The backup API, however, do not process grandparent nodes.
596 * It only processes definitive children, and their parent attributes.
598 * We had:
600 * <gradebook calculations_freeze="20160511">
601 * <grade_categories>
602 * <grade_category id="10">
603 * <depth>1</depth>
604 * ...
605 * </grade_category>
606 * </grade_categories>
607 * ...
608 * </gradebook>
610 * And this method will convert it to:
612 * <gradebook >
613 * <attributes>
614 * <calculations_freeze>20160511</calculations_freeze>
615 * </attributes>
616 * <grade_categories>
617 * <grade_category id="10">
618 * <depth>1</depth>
619 * ...
620 * </grade_category>
621 * </grade_categories>
622 * ...
623 * </gradebook>
625 * Note that we cannot just load the XML file in memory as it could potentially be huge.
626 * We can also completely ignore if the node <attributes> is already in the backup
627 * file as it never existed before.
629 * @param string $filepath The absolute path to the XML file.
630 * @return void
632 protected function rewrite_step_backup_file_for_legacy_freeze($filepath) {
633 $foundnode = false;
634 $newfile = make_request_directory(true) . DIRECTORY_SEPARATOR . 'file.xml';
635 $fr = fopen($filepath, 'r');
636 $fw = fopen($newfile, 'w');
637 if ($fr && $fw) {
638 while (($line = fgets($fr, 4096)) !== false) {
639 if (!$foundnode && strpos($line, '<gradebook ') === 0) {
640 $foundnode = true;
641 $matches = array();
642 $pattern = '@calculations_freeze=.([0-9]+).@';
643 if (preg_match($pattern, $line, $matches)) {
644 $freeze = $matches[1];
645 $line = preg_replace($pattern, '', $line);
646 $line .= " <attributes>\n <calculations_freeze>$freeze</calculations_freeze>\n </attributes>\n";
649 fputs($fw, $line);
651 if (!feof($fr)) {
652 throw new restore_step_exception('Error while attempting to rewrite the gradebook step file.');
654 fclose($fr);
655 fclose($fw);
656 if (!rename($newfile, $filepath)) {
657 throw new restore_step_exception('Error while attempting to rename the gradebook step file.');
659 } else {
660 if ($fr) {
661 fclose($fr);
663 if ($fw) {
664 fclose($fw);
672 * Step in charge of restoring the grade history of a course.
674 * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
675 * we do not want to restore the history if the gradebook and its content has not been
676 * restored. At least for now.
678 class restore_grade_history_structure_step extends restore_structure_step {
680 protected function execute_condition() {
681 global $CFG, $DB;
683 if ($this->get_courseid() == SITEID) {
684 return false;
687 // No gradebook info found, don't execute.
688 $fullpath = $this->task->get_taskbasepath();
689 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
690 if (!file_exists($fullpath)) {
691 return false;
694 // Some module present in backup file isn't available to restore in this site, don't execute.
695 if ($this->task->is_missing_modules()) {
696 return false;
699 // Some activity has been excluded to be restored, don't execute.
700 if ($this->task->is_excluding_activities()) {
701 return false;
704 // There should only be one grade category (the 1 associated with the course itself).
705 $category = new stdclass();
706 $category->courseid = $this->get_courseid();
707 $catcount = $DB->count_records('grade_categories', (array)$category);
708 if ($catcount > 1) {
709 return false;
712 // Arrived here, execute the step.
713 return true;
716 protected function define_structure() {
717 $paths = array();
719 // Settings to use.
720 $userinfo = $this->get_setting_value('users');
721 $history = $this->get_setting_value('grade_histories');
723 if ($userinfo && $history) {
724 $paths[] = new restore_path_element('grade_grade',
725 '/grade_history/grade_grades/grade_grade');
728 return $paths;
731 protected function process_grade_grade($data) {
732 global $DB;
734 $data = (object)($data);
735 $olduserid = $data->userid;
736 unset($data->id);
738 $data->userid = $this->get_mappingid('user', $data->userid, null);
739 if (!empty($data->userid)) {
740 // Do not apply the date offsets as this is history.
741 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
742 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
743 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
744 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
745 $DB->insert_record('grade_grades_history', $data);
746 } else {
747 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
748 $this->log($message, backup::LOG_DEBUG);
755 * decode all the interlinks present in restored content
756 * relying 100% in the restore_decode_processor that handles
757 * both the contents to modify and the rules to be applied
759 class restore_decode_interlinks extends restore_execution_step {
761 protected function define_execution() {
762 // Get the decoder (from the plan)
763 $decoder = $this->task->get_decoder();
764 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
765 // And launch it, everything will be processed
766 $decoder->execute();
771 * first, ensure that we have no gaps in section numbers
772 * and then, rebuid the course cache
774 class restore_rebuild_course_cache extends restore_execution_step {
776 protected function define_execution() {
777 global $DB;
779 // Although there is some sort of auto-recovery of missing sections
780 // present in course/formats... here we check that all the sections
781 // from 0 to MAX(section->section) exist, creating them if necessary
782 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
783 // Iterate over all sections
784 for ($i = 0; $i <= $maxsection; $i++) {
785 // If the section $i doesn't exist, create it
786 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
787 $sectionrec = array(
788 'course' => $this->get_courseid(),
789 'section' => $i,
790 'timemodified' => time());
791 $DB->insert_record('course_sections', $sectionrec); // missing section created
795 // Rebuild cache now that all sections are in place
796 rebuild_course_cache($this->get_courseid());
797 cache_helper::purge_by_event('changesincourse');
798 cache_helper::purge_by_event('changesincoursecat');
803 * Review all the tasks having one after_restore method
804 * executing it to perform some final adjustments of information
805 * not available when the task was executed.
807 class restore_execute_after_restore extends restore_execution_step {
809 protected function define_execution() {
811 // Simply call to the execute_after_restore() method of the task
812 // that always is the restore_final_task
813 $this->task->launch_execute_after_restore();
819 * Review all the (pending) block positions in backup_ids, matching by
820 * contextid, creating positions as needed. This is executed by the
821 * final task, once all the contexts have been created
823 class restore_review_pending_block_positions extends restore_execution_step {
825 protected function define_execution() {
826 global $DB;
828 // Get all the block_position objects pending to match
829 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
830 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
831 // Process block positions, creating them or accumulating for final step
832 foreach($rs as $posrec) {
833 // Get the complete position object out of the info field.
834 $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
835 // If position is for one already mapped (known) contextid
836 // process it now, creating the position, else nothing to
837 // do, position finally discarded
838 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
839 $position->contextid = $newctx->newitemid;
840 // Create the block position
841 $DB->insert_record('block_positions', $position);
844 $rs->close();
850 * Updates the availability data for course modules and sections.
852 * Runs after the restore of all course modules, sections, and grade items has
853 * completed. This is necessary in order to update IDs that have changed during
854 * restore.
856 * @package core_backup
857 * @copyright 2014 The Open University
858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
860 class restore_update_availability extends restore_execution_step {
862 protected function define_execution() {
863 global $CFG, $DB;
865 // Note: This code runs even if availability is disabled when restoring.
866 // That will ensure that if you later turn availability on for the site,
867 // there will be no incorrect IDs. (It doesn't take long if the restored
868 // data does not contain any availability information.)
870 // Get modinfo with all data after resetting cache.
871 rebuild_course_cache($this->get_courseid(), true);
872 $modinfo = get_fast_modinfo($this->get_courseid());
874 // Get the date offset for this restore.
875 $dateoffset = $this->apply_date_offset(1) - 1;
877 // Update all sections that were restored.
878 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
879 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
880 $sectionsbyid = null;
881 foreach ($rs as $rec) {
882 if (is_null($sectionsbyid)) {
883 $sectionsbyid = array();
884 foreach ($modinfo->get_section_info_all() as $section) {
885 $sectionsbyid[$section->id] = $section;
888 if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
889 // If the section was not fully restored for some reason
890 // (e.g. due to an earlier error), skip it.
891 $this->get_logger()->process('Section not fully restored: id ' .
892 $rec->newitemid, backup::LOG_WARNING);
893 continue;
895 $section = $sectionsbyid[$rec->newitemid];
896 if (!is_null($section->availability)) {
897 $info = new \core_availability\info_section($section);
898 $info->update_after_restore($this->get_restoreid(),
899 $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
902 $rs->close();
904 // Update all modules that were restored.
905 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
906 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
907 foreach ($rs as $rec) {
908 if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
909 // If the module was not fully restored for some reason
910 // (e.g. due to an earlier error), skip it.
911 $this->get_logger()->process('Module not fully restored: id ' .
912 $rec->newitemid, backup::LOG_WARNING);
913 continue;
915 $cm = $modinfo->get_cm($rec->newitemid);
916 if (!is_null($cm->availability)) {
917 $info = new \core_availability\info_module($cm);
918 $info->update_after_restore($this->get_restoreid(),
919 $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
922 $rs->close();
928 * Process legacy module availability records in backup_ids.
930 * Matches course modules and grade item id once all them have been already restored.
931 * Only if all matchings are satisfied the availability condition will be created.
932 * At the same time, it is required for the site to have that functionality enabled.
934 * This step is included only to handle legacy backups (2.6 and before). It does not
935 * do anything for newer backups.
937 * @copyright 2014 The Open University
938 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
940 class restore_process_course_modules_availability extends restore_execution_step {
942 protected function define_execution() {
943 global $CFG, $DB;
945 // Site hasn't availability enabled
946 if (empty($CFG->enableavailability)) {
947 return;
950 // Do both modules and sections.
951 foreach (array('module', 'section') as $table) {
952 // Get all the availability objects to process.
953 $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
954 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
955 // Process availabilities, creating them if everything matches ok.
956 foreach ($rs as $availrec) {
957 $allmatchesok = true;
958 // Get the complete legacy availability object.
959 $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
961 // Note: This code used to update IDs, but that is now handled by the
962 // current code (after restore) instead of this legacy code.
964 // Get showavailability option.
965 $thingid = ($table === 'module') ? $availability->coursemoduleid :
966 $availability->coursesectionid;
967 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
968 $table . '_showavailability', $thingid);
969 if (!$showrec) {
970 // Should not happen.
971 throw new coding_exception('No matching showavailability record');
973 $show = $showrec->info->showavailability;
975 // The $availability object is now in the format used in the old
976 // system. Interpret this and convert to new system.
977 $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
978 array('id' => $thingid), MUST_EXIST);
979 $newvalue = \core_availability\info::add_legacy_availability_condition(
980 $currentvalue, $availability, $show);
981 $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
982 array('id' => $thingid));
984 $rs->close();
991 * Execution step that, *conditionally* (if there isn't preloaded information)
992 * will load the inforef files for all the included course/section/activity tasks
993 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
995 class restore_load_included_inforef_records extends restore_execution_step {
997 protected function define_execution() {
999 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1000 return;
1003 // Get all the included tasks
1004 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
1005 $progress = $this->task->get_progress();
1006 $progress->start_progress($this->get_name(), count($tasks));
1007 foreach ($tasks as $task) {
1008 // Load the inforef.xml file if exists
1009 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
1010 if (file_exists($inforefpath)) {
1011 // Load each inforef file to temp_ids.
1012 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
1015 $progress->end_progress();
1020 * Execution step that will load all the needed files into backup_files_temp
1021 * - info: contains the whole original object (times, names...)
1022 * (all them being original ids as loaded from xml)
1024 class restore_load_included_files extends restore_structure_step {
1026 protected function define_structure() {
1028 $file = new restore_path_element('file', '/files/file');
1030 return array($file);
1034 * Process one <file> element from files.xml
1036 * @param array $data the element data
1038 public function process_file($data) {
1040 $data = (object)$data; // handy
1042 // load it if needed:
1043 // - it it is one of the annotated inforef files (course/section/activity/block)
1044 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
1045 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
1046 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
1047 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
1048 $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
1049 $data->component == 'grouping' || $data->component == 'grade' ||
1050 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
1051 if ($isfileref || $iscomponent) {
1052 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
1058 * Execution step that, *conditionally* (if there isn't preloaded information),
1059 * will load all the needed roles to backup_temp_ids. They will be stored with
1060 * "role" itemname. Also it will perform one automatic mapping to roles existing
1061 * in the target site, based in permissions of the user performing the restore,
1062 * archetypes and other bits. At the end, each original role will have its associated
1063 * target role or 0 if it's going to be skipped. Note we wrap everything over one
1064 * restore_dbops method, as far as the same stuff is going to be also executed
1065 * by restore prechecks
1067 class restore_load_and_map_roles extends restore_execution_step {
1069 protected function define_execution() {
1070 if ($this->task->get_preloaded_information()) { // if info is already preloaded
1071 return;
1074 $file = $this->get_basepath() . '/roles.xml';
1075 // Load needed toles to temp_ids
1076 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
1078 // Process roles, mapping/skipping. Any error throws exception
1079 // Note we pass controller's info because it can contain role mapping information
1080 // about manual mappings performed by UI
1081 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);
1086 * Execution step that, *conditionally* (if there isn't preloaded information
1087 * and users have been selected in settings, will load all the needed users
1088 * to backup_temp_ids. They will be stored with "user" itemname and with
1089 * their original contextid as paremitemid
1091 class restore_load_included_users extends restore_execution_step {
1093 protected function define_execution() {
1095 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1096 return;
1098 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1099 return;
1101 $file = $this->get_basepath() . '/users.xml';
1102 // Load needed users to temp_ids.
1103 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
1108 * Execution step that, *conditionally* (if there isn't preloaded information
1109 * and users have been selected in settings, will process all the needed users
1110 * in order to decide and perform any action with them (create / map / error)
1111 * Note: Any error will cause exception, as far as this is the same processing
1112 * than the one into restore prechecks (that should have stopped process earlier)
1114 class restore_process_included_users extends restore_execution_step {
1116 protected function define_execution() {
1118 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1119 return;
1121 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1122 return;
1124 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
1125 $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
1130 * Execution step that will create all the needed users as calculated
1131 * by @restore_process_included_users (those having newiteind = 0)
1133 class restore_create_included_users extends restore_execution_step {
1135 protected function define_execution() {
1137 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
1138 $this->task->get_userid(), $this->task->get_progress());
1143 * Structure step that will create all the needed groups and groupings
1144 * by loading them from the groups.xml file performing the required matches.
1145 * Note group members only will be added if restoring user info
1147 class restore_groups_structure_step extends restore_structure_step {
1149 protected function define_structure() {
1151 $paths = array(); // Add paths here
1153 // Do not include group/groupings information if not requested.
1154 $groupinfo = $this->get_setting_value('groups');
1155 if ($groupinfo) {
1156 $paths[] = new restore_path_element('group', '/groups/group');
1157 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
1158 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
1160 return $paths;
1163 // Processing functions go here
1164 public function process_group($data) {
1165 global $DB;
1167 $data = (object)$data; // handy
1168 $data->courseid = $this->get_courseid();
1170 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1171 // another a group in the same course
1172 $context = context_course::instance($data->courseid);
1173 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1174 if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
1175 unset($data->idnumber);
1177 } else {
1178 unset($data->idnumber);
1181 $oldid = $data->id; // need this saved for later
1183 $restorefiles = false; // Only if we end creating the group
1185 // Search if the group already exists (by name & description) in the target course
1186 $description_clause = '';
1187 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1188 if (!empty($data->description)) {
1189 $description_clause = ' AND ' .
1190 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1191 $params['description'] = $data->description;
1193 if (!$groupdb = $DB->get_record_sql("SELECT *
1194 FROM {groups}
1195 WHERE courseid = :courseid
1196 AND name = :grname $description_clause", $params)) {
1197 // group doesn't exist, create
1198 $newitemid = $DB->insert_record('groups', $data);
1199 $restorefiles = true; // We'll restore the files
1200 } else {
1201 // group exists, use it
1202 $newitemid = $groupdb->id;
1204 // Save the id mapping
1205 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
1206 // Invalidate the course group data cache just in case.
1207 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1210 public function process_grouping($data) {
1211 global $DB;
1213 $data = (object)$data; // handy
1214 $data->courseid = $this->get_courseid();
1216 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1217 // another a grouping in the same course
1218 $context = context_course::instance($data->courseid);
1219 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1220 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
1221 unset($data->idnumber);
1223 } else {
1224 unset($data->idnumber);
1227 $oldid = $data->id; // need this saved for later
1228 $restorefiles = false; // Only if we end creating the grouping
1230 // Search if the grouping already exists (by name & description) in the target course
1231 $description_clause = '';
1232 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1233 if (!empty($data->description)) {
1234 $description_clause = ' AND ' .
1235 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1236 $params['description'] = $data->description;
1238 if (!$groupingdb = $DB->get_record_sql("SELECT *
1239 FROM {groupings}
1240 WHERE courseid = :courseid
1241 AND name = :grname $description_clause", $params)) {
1242 // grouping doesn't exist, create
1243 $newitemid = $DB->insert_record('groupings', $data);
1244 $restorefiles = true; // We'll restore the files
1245 } else {
1246 // grouping exists, use it
1247 $newitemid = $groupingdb->id;
1249 // Save the id mapping
1250 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1251 // Invalidate the course group data cache just in case.
1252 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1255 public function process_grouping_group($data) {
1256 global $CFG;
1258 require_once($CFG->dirroot.'/group/lib.php');
1260 $data = (object)$data;
1261 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
1264 protected function after_execute() {
1265 // Add group related files, matching with "group" mappings
1266 $this->add_related_files('group', 'icon', 'group');
1267 $this->add_related_files('group', 'description', 'group');
1268 // Add grouping related files, matching with "grouping" mappings
1269 $this->add_related_files('grouping', 'description', 'grouping');
1270 // Invalidate the course group data.
1271 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1277 * Structure step that will create all the needed group memberships
1278 * by loading them from the groups.xml file performing the required matches.
1280 class restore_groups_members_structure_step extends restore_structure_step {
1282 protected $plugins = null;
1284 protected function define_structure() {
1286 $paths = array(); // Add paths here
1288 if ($this->get_setting_value('groups') && $this->get_setting_value('users')) {
1289 $paths[] = new restore_path_element('group', '/groups/group');
1290 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1293 return $paths;
1296 public function process_group($data) {
1297 $data = (object)$data; // handy
1299 // HACK ALERT!
1300 // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1301 // Let's fake internal state to make $this->get_new_parentid('group') work.
1303 $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1306 public function process_member($data) {
1307 global $DB, $CFG;
1308 require_once("$CFG->dirroot/group/lib.php");
1310 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1312 $data = (object)$data; // handy
1314 // get parent group->id
1315 $data->groupid = $this->get_new_parentid('group');
1317 // map user newitemid and insert if not member already
1318 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1319 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1320 // Check the component, if any, exists.
1321 if (empty($data->component)) {
1322 groups_add_member($data->groupid, $data->userid);
1324 } else if ((strpos($data->component, 'enrol_') === 0)) {
1325 // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1326 // it is possible that enrolment was restored using different plugin type.
1327 if (!isset($this->plugins)) {
1328 $this->plugins = enrol_get_plugins(true);
1330 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1331 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1332 if (isset($this->plugins[$instance->enrol])) {
1333 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1338 } else {
1339 $dir = core_component::get_component_directory($data->component);
1340 if ($dir and is_dir($dir)) {
1341 if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1342 return;
1345 // Bad luck, plugin could not restore the data, let's add normal membership.
1346 groups_add_member($data->groupid, $data->userid);
1347 $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1348 $this->log($message, backup::LOG_WARNING);
1356 * Structure step that will create all the needed scales
1357 * by loading them from the scales.xml
1359 class restore_scales_structure_step extends restore_structure_step {
1361 protected function define_structure() {
1363 $paths = array(); // Add paths here
1364 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1365 return $paths;
1368 protected function process_scale($data) {
1369 global $DB;
1371 $data = (object)$data;
1373 $restorefiles = false; // Only if we end creating the group
1375 $oldid = $data->id; // need this saved for later
1377 // Look for scale (by 'scale' both in standard (course=0) and current course
1378 // with priority to standard scales (ORDER clause)
1379 // scale is not course unique, use get_record_sql to suppress warning
1380 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1381 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
1382 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1383 if (!$scadb = $DB->get_record_sql("SELECT *
1384 FROM {scale}
1385 WHERE courseid IN (0, :courseid)
1386 AND $compare_scale_clause
1387 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1388 // Remap the user if possible, defaut to user performing the restore if not
1389 $userid = $this->get_mappingid('user', $data->userid);
1390 $data->userid = $userid ? $userid : $this->task->get_userid();
1391 // Remap the course if course scale
1392 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1393 // If global scale (course=0), check the user has perms to create it
1394 // falling to course scale if not
1395 $systemctx = context_system::instance();
1396 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1397 $data->courseid = $this->get_courseid();
1399 // scale doesn't exist, create
1400 $newitemid = $DB->insert_record('scale', $data);
1401 $restorefiles = true; // We'll restore the files
1402 } else {
1403 // scale exists, use it
1404 $newitemid = $scadb->id;
1406 // Save the id mapping (with files support at system context)
1407 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1410 protected function after_execute() {
1411 // Add scales related files, matching with "scale" mappings
1412 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1418 * Structure step that will create all the needed outocomes
1419 * by loading them from the outcomes.xml
1421 class restore_outcomes_structure_step extends restore_structure_step {
1423 protected function define_structure() {
1425 $paths = array(); // Add paths here
1426 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1427 return $paths;
1430 protected function process_outcome($data) {
1431 global $DB;
1433 $data = (object)$data;
1435 $restorefiles = false; // Only if we end creating the group
1437 $oldid = $data->id; // need this saved for later
1439 // Look for outcome (by shortname both in standard (courseid=null) and current course
1440 // with priority to standard outcomes (ORDER clause)
1441 // outcome is not course unique, use get_record_sql to suppress warning
1442 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1443 if (!$outdb = $DB->get_record_sql('SELECT *
1444 FROM {grade_outcomes}
1445 WHERE shortname = :shortname
1446 AND (courseid = :courseid OR courseid IS NULL)
1447 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1448 // Remap the user
1449 $userid = $this->get_mappingid('user', $data->usermodified);
1450 $data->usermodified = $userid ? $userid : $this->task->get_userid();
1451 // Remap the scale
1452 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1453 // Remap the course if course outcome
1454 $data->courseid = $data->courseid ? $this->get_courseid() : null;
1455 // If global outcome (course=null), check the user has perms to create it
1456 // falling to course outcome if not
1457 $systemctx = context_system::instance();
1458 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1459 $data->courseid = $this->get_courseid();
1461 // outcome doesn't exist, create
1462 $newitemid = $DB->insert_record('grade_outcomes', $data);
1463 $restorefiles = true; // We'll restore the files
1464 } else {
1465 // scale exists, use it
1466 $newitemid = $outdb->id;
1468 // Set the corresponding grade_outcomes_courses record
1469 $outcourserec = new stdclass();
1470 $outcourserec->courseid = $this->get_courseid();
1471 $outcourserec->outcomeid = $newitemid;
1472 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1473 $DB->insert_record('grade_outcomes_courses', $outcourserec);
1475 // Save the id mapping (with files support at system context)
1476 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1479 protected function after_execute() {
1480 // Add outcomes related files, matching with "outcome" mappings
1481 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1486 * Execution step that, *conditionally* (if there isn't preloaded information
1487 * will load all the question categories and questions (header info only)
1488 * to backup_temp_ids. They will be stored with "question_category" and
1489 * "question" itemnames and with their original contextid and question category
1490 * id as paremitemids
1492 class restore_load_categories_and_questions extends restore_execution_step {
1494 protected function define_execution() {
1496 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1497 return;
1499 $file = $this->get_basepath() . '/questions.xml';
1500 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1505 * Execution step that, *conditionally* (if there isn't preloaded information)
1506 * will process all the needed categories and questions
1507 * in order to decide and perform any action with them (create / map / error)
1508 * Note: Any error will cause exception, as far as this is the same processing
1509 * than the one into restore prechecks (that should have stopped process earlier)
1511 class restore_process_categories_and_questions extends restore_execution_step {
1513 protected function define_execution() {
1515 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1516 return;
1518 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1523 * Structure step that will read the section.xml creating/updating sections
1524 * as needed, rebuilding course cache and other friends
1526 class restore_section_structure_step extends restore_structure_step {
1527 /** @var array Cache: Array of id => course format */
1528 private static $courseformats = array();
1531 * Resets a static cache of course formats. Required for unit testing.
1533 public static function reset_caches() {
1534 self::$courseformats = array();
1537 protected function define_structure() {
1538 global $CFG;
1540 $paths = array();
1542 $section = new restore_path_element('section', '/section');
1543 $paths[] = $section;
1544 if ($CFG->enableavailability) {
1545 $paths[] = new restore_path_element('availability', '/section/availability');
1546 $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1548 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1550 // Apply for 'format' plugins optional paths at section level
1551 $this->add_plugin_structure('format', $section);
1553 // Apply for 'local' plugins optional paths at section level
1554 $this->add_plugin_structure('local', $section);
1556 return $paths;
1559 public function process_section($data) {
1560 global $CFG, $DB;
1561 $data = (object)$data;
1562 $oldid = $data->id; // We'll need this later
1564 $restorefiles = false;
1566 // Look for the section
1567 $section = new stdclass();
1568 $section->course = $this->get_courseid();
1569 $section->section = $data->number;
1570 $section->timemodified = $data->timemodified ?? 0;
1571 // Section doesn't exist, create it with all the info from backup
1572 if (!$secrec = $DB->get_record('course_sections', ['course' => $this->get_courseid(), 'section' => $data->number])) {
1573 $section->name = $data->name;
1574 $section->summary = $data->summary;
1575 $section->summaryformat = $data->summaryformat;
1576 $section->sequence = '';
1577 $section->visible = $data->visible;
1578 if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1579 $section->availability = null;
1580 } else {
1581 $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1582 // Include legacy [<2.7] availability data if provided.
1583 if (is_null($section->availability)) {
1584 $section->availability = \core_availability\info::convert_legacy_fields(
1585 $data, true);
1588 $newitemid = $DB->insert_record('course_sections', $section);
1589 $section->id = $newitemid;
1591 core\event\course_section_created::create_from_section($section)->trigger();
1593 $restorefiles = true;
1595 // Section exists, update non-empty information
1596 } else {
1597 $section->id = $secrec->id;
1598 if ((string)$secrec->name === '') {
1599 $section->name = $data->name;
1601 if (empty($secrec->summary)) {
1602 $section->summary = $data->summary;
1603 $section->summaryformat = $data->summaryformat;
1604 $restorefiles = true;
1607 // Don't update availability (I didn't see a useful way to define
1608 // whether existing or new one should take precedence).
1610 $DB->update_record('course_sections', $section);
1611 $newitemid = $secrec->id;
1613 // Trigger an event for course section update.
1614 $event = \core\event\course_section_updated::create(
1615 array(
1616 'objectid' => $section->id,
1617 'courseid' => $section->course,
1618 'context' => context_course::instance($section->course),
1619 'other' => array('sectionnum' => $section->section)
1622 $event->trigger();
1625 // Annotate the section mapping, with restorefiles option if needed
1626 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1628 // set the new course_section id in the task
1629 $this->task->set_sectionid($newitemid);
1631 // If there is the legacy showavailability data, store this for later use.
1632 // (This data is not present when restoring 'new' backups.)
1633 if (isset($data->showavailability)) {
1634 // Cache the showavailability flag using the backup_ids data field.
1635 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1636 'section_showavailability', $newitemid, 0, null,
1637 (object)array('showavailability' => $data->showavailability));
1640 // Commented out. We never modify course->numsections as far as that is used
1641 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1642 // Note: We keep the code here, to know about and because of the possibility of making this
1643 // optional based on some setting/attribute in the future
1644 // If needed, adjust course->numsections
1645 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1646 // if ($numsections < $section->section) {
1647 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1648 // }
1653 * Process the legacy availability table record. This table does not exist
1654 * in Moodle 2.7+ but we still support restore.
1656 * @param stdClass $data Record data
1658 public function process_availability($data) {
1659 $data = (object)$data;
1660 // Simply going to store the whole availability record now, we'll process
1661 // all them later in the final task (once all activities have been restored)
1662 // Let's call the low level one to be able to store the whole object.
1663 $data->coursesectionid = $this->task->get_sectionid();
1664 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1665 'section_availability', $data->id, 0, null, $data);
1669 * Process the legacy availability fields table record. This table does not
1670 * exist in Moodle 2.7+ but we still support restore.
1672 * @param stdClass $data Record data
1674 public function process_availability_field($data) {
1675 global $DB;
1676 $data = (object)$data;
1677 // Mark it is as passed by default
1678 $passed = true;
1679 $customfieldid = null;
1681 // If a customfield has been used in order to pass we must be able to match an existing
1682 // customfield by name (data->customfield) and type (data->customfieldtype)
1683 if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1684 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1685 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1686 $passed = false;
1687 } else if (!is_null($data->customfield)) {
1688 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1689 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1690 $passed = ($customfieldid !== false);
1693 if ($passed) {
1694 // Create the object to insert into the database
1695 $availfield = new stdClass();
1696 $availfield->coursesectionid = $this->task->get_sectionid();
1697 $availfield->userfield = $data->userfield;
1698 $availfield->customfieldid = $customfieldid;
1699 $availfield->operator = $data->operator;
1700 $availfield->value = $data->value;
1702 // Get showavailability option.
1703 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1704 'section_showavailability', $availfield->coursesectionid);
1705 if (!$showrec) {
1706 // Should not happen.
1707 throw new coding_exception('No matching showavailability record');
1709 $show = $showrec->info->showavailability;
1711 // The $availfield object is now in the format used in the old
1712 // system. Interpret this and convert to new system.
1713 $currentvalue = $DB->get_field('course_sections', 'availability',
1714 array('id' => $availfield->coursesectionid), MUST_EXIST);
1715 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1716 $currentvalue, $availfield, $show);
1718 $section = new stdClass();
1719 $section->id = $availfield->coursesectionid;
1720 $section->availability = $newvalue;
1721 $section->timemodified = time();
1722 $DB->update_record('course_sections', $section);
1726 public function process_course_format_options($data) {
1727 global $DB;
1728 $courseid = $this->get_courseid();
1729 if (!array_key_exists($courseid, self::$courseformats)) {
1730 // It is safe to have a static cache of course formats because format can not be changed after this point.
1731 self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1733 $data = (array)$data;
1734 if (self::$courseformats[$courseid] === $data['format']) {
1735 // Import section format options only if both courses (the one that was backed up
1736 // and the one we are restoring into) have same formats.
1737 $params = array(
1738 'courseid' => $this->get_courseid(),
1739 'sectionid' => $this->task->get_sectionid(),
1740 'format' => $data['format'],
1741 'name' => $data['name']
1743 if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1744 // Do not overwrite existing information.
1745 $newid = $record->id;
1746 } else {
1747 $params['value'] = $data['value'];
1748 $newid = $DB->insert_record('course_format_options', $params);
1750 $this->set_mapping('course_format_options', $data['id'], $newid);
1754 protected function after_execute() {
1755 // Add section related files, with 'course_section' itemid to match
1756 $this->add_related_files('course', 'section', 'course_section');
1761 * Structure step that will read the course.xml file, loading it and performing
1762 * various actions depending of the site/restore settings. Note that target
1763 * course always exist before arriving here so this step will be updating
1764 * the course record (never inserting)
1766 class restore_course_structure_step extends restore_structure_step {
1768 * @var bool this gets set to true by {@link process_course()} if we are
1769 * restoring an old coures that used the legacy 'module security' feature.
1770 * If so, we have to do more work in {@link after_execute()}.
1772 protected $legacyrestrictmodules = false;
1775 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1776 * array with array keys the module names ('forum', 'quiz', etc.). These are
1777 * the modules that are allowed according to the data in the backup file.
1778 * In {@link after_execute()} we then have to prevent adding of all the other
1779 * types of activity.
1781 protected $legacyallowedmodules = array();
1783 protected function define_structure() {
1785 $course = new restore_path_element('course', '/course');
1786 $category = new restore_path_element('category', '/course/category');
1787 $tag = new restore_path_element('tag', '/course/tags/tag');
1788 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1790 // Apply for 'format' plugins optional paths at course level
1791 $this->add_plugin_structure('format', $course);
1793 // Apply for 'theme' plugins optional paths at course level
1794 $this->add_plugin_structure('theme', $course);
1796 // Apply for 'report' plugins optional paths at course level
1797 $this->add_plugin_structure('report', $course);
1799 // Apply for 'course report' plugins optional paths at course level
1800 $this->add_plugin_structure('coursereport', $course);
1802 // Apply for plagiarism plugins optional paths at course level
1803 $this->add_plugin_structure('plagiarism', $course);
1805 // Apply for local plugins optional paths at course level
1806 $this->add_plugin_structure('local', $course);
1808 // Apply for admin tool plugins optional paths at course level.
1809 $this->add_plugin_structure('tool', $course);
1811 return array($course, $category, $tag, $allowed_module);
1815 * Processing functions go here
1817 * @global moodledatabase $DB
1818 * @param stdClass $data
1820 public function process_course($data) {
1821 global $CFG, $DB;
1822 $context = context::instance_by_id($this->task->get_contextid());
1823 $userid = $this->task->get_userid();
1824 $target = $this->get_task()->get_target();
1825 $isnewcourse = $target == backup::TARGET_NEW_COURSE;
1827 // When restoring to a new course we can set all the things except for the ID number.
1828 $canchangeidnumber = $isnewcourse || has_capability('moodle/course:changeidnumber', $context, $userid);
1829 $canchangesummary = $isnewcourse || has_capability('moodle/course:changesummary', $context, $userid);
1831 $data = (object)$data;
1832 $data->id = $this->get_courseid();
1834 // Calculate final course names, to avoid dupes.
1835 $fullname = $this->get_setting_value('course_fullname');
1836 $shortname = $this->get_setting_value('course_shortname');
1837 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names($this->get_courseid(),
1838 $fullname === false ? $data->fullname : $fullname,
1839 $shortname === false ? $data->shortname : $shortname);
1840 // Do not modify the course names at all when merging and user selected to keep the names (or prohibited by cap).
1841 if (!$isnewcourse && $fullname === false) {
1842 unset($data->fullname);
1844 if (!$isnewcourse && $shortname === false) {
1845 unset($data->shortname);
1848 // Unset summary if user can't change it.
1849 if (!$canchangesummary) {
1850 unset($data->summary);
1851 unset($data->summaryformat);
1854 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1855 // another course on this site.
1856 if (!empty($data->idnumber) && $canchangeidnumber && $this->task->is_samesite()
1857 && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1858 // Do not reset idnumber.
1860 } else if (!$isnewcourse) {
1861 // Prevent override when restoring as merge.
1862 unset($data->idnumber);
1864 } else {
1865 $data->idnumber = '';
1868 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1869 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1870 if (empty($data->hiddensections)) {
1871 $data->hiddensections = 0;
1874 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1875 // then we will need to process restricted modules after execution.
1876 $this->legacyrestrictmodules = !empty($data->restrictmodules);
1878 $data->startdate= $this->apply_date_offset($data->startdate);
1879 if (isset($data->enddate)) {
1880 $data->enddate = $this->apply_date_offset($data->enddate);
1883 if ($data->defaultgroupingid) {
1884 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1886 if (empty($CFG->enablecompletion)) {
1887 $data->enablecompletion = 0;
1888 $data->completionstartonenrol = 0;
1889 $data->completionnotify = 0;
1891 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1892 if (!array_key_exists($data->lang, $languages)) {
1893 $data->lang = '';
1896 $themes = get_list_of_themes(); // Get themes for quick search later
1897 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1898 $data->theme = '';
1901 // Check if this is an old SCORM course format.
1902 if ($data->format == 'scorm') {
1903 $data->format = 'singleactivity';
1904 $data->activitytype = 'scorm';
1907 // Course record ready, update it
1908 $DB->update_record('course', $data);
1910 course_get_format($data)->update_course_format_options($data);
1912 // Role name aliases
1913 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1916 public function process_category($data) {
1917 // Nothing to do with the category. UI sets it before restore starts
1920 public function process_tag($data) {
1921 global $CFG, $DB;
1923 $data = (object)$data;
1925 core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
1926 context_course::instance($this->get_courseid()), $data->rawname);
1929 public function process_allowed_module($data) {
1930 $data = (object)$data;
1932 // Backwards compatiblity support for the data that used to be in the
1933 // course_allowed_modules table.
1934 if ($this->legacyrestrictmodules) {
1935 $this->legacyallowedmodules[$data->modulename] = 1;
1939 protected function after_execute() {
1940 global $DB;
1942 // Add course related files, without itemid to match
1943 $this->add_related_files('course', 'summary', null);
1944 $this->add_related_files('course', 'overviewfiles', null);
1946 // Deal with legacy allowed modules.
1947 if ($this->legacyrestrictmodules) {
1948 $context = context_course::instance($this->get_courseid());
1950 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1951 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1952 foreach ($managerroleids as $roleid) {
1953 unset($roleids[$roleid]);
1956 foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1957 if (isset($this->legacyallowedmodules[$modname])) {
1958 // Module is allowed, no worries.
1959 continue;
1962 $capability = 'mod/' . $modname . ':addinstance';
1963 foreach ($roleids as $roleid) {
1964 assign_capability($capability, CAP_PREVENT, $roleid, $context);
1972 * Execution step that will migrate legacy files if present.
1974 class restore_course_legacy_files_step extends restore_execution_step {
1975 public function define_execution() {
1976 global $DB;
1978 // Do a check for legacy files and skip if there are none.
1979 $sql = 'SELECT count(*)
1980 FROM {backup_files_temp}
1981 WHERE backupid = ?
1982 AND contextid = ?
1983 AND component = ?
1984 AND filearea = ?';
1985 $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
1987 if ($DB->count_records_sql($sql, $params)) {
1988 $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
1989 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
1990 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
1996 * Structure step that will read the roles.xml file (at course/activity/block levels)
1997 * containing all the role_assignments and overrides for that context. If corresponding to
1998 * one mapped role, they will be applied to target context. Will observe the role_assignments
1999 * setting to decide if ras are restored.
2001 * Note: this needs to be executed after all users are enrolled.
2003 class restore_ras_and_caps_structure_step extends restore_structure_step {
2004 protected $plugins = null;
2006 protected function define_structure() {
2008 $paths = array();
2010 // Observe the role_assignments setting
2011 if ($this->get_setting_value('role_assignments')) {
2012 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
2014 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
2016 return $paths;
2020 * Assign roles
2022 * This has to be called after enrolments processing.
2024 * @param mixed $data
2025 * @return void
2027 public function process_assignment($data) {
2028 global $DB;
2030 $data = (object)$data;
2032 // Check roleid, userid are one of the mapped ones
2033 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
2034 return;
2036 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
2037 return;
2039 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
2040 // Only assign roles to not deleted users
2041 return;
2043 if (!$contextid = $this->task->get_contextid()) {
2044 return;
2047 if (empty($data->component)) {
2048 // assign standard manual roles
2049 // TODO: role_assign() needs one userid param to be able to specify our restore userid
2050 role_assign($newroleid, $newuserid, $contextid);
2052 } else if ((strpos($data->component, 'enrol_') === 0)) {
2053 // Deal with enrolment roles - ignore the component and just find out the instance via new id,
2054 // it is possible that enrolment was restored using different plugin type.
2055 if (!isset($this->plugins)) {
2056 $this->plugins = enrol_get_plugins(true);
2058 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
2059 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2060 if (isset($this->plugins[$instance->enrol])) {
2061 $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
2066 } else {
2067 $data->roleid = $newroleid;
2068 $data->userid = $newuserid;
2069 $data->contextid = $contextid;
2070 $dir = core_component::get_component_directory($data->component);
2071 if ($dir and is_dir($dir)) {
2072 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
2073 return;
2076 // Bad luck, plugin could not restore the data, let's add normal membership.
2077 role_assign($data->roleid, $data->userid, $data->contextid);
2078 $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
2079 $this->log($message, backup::LOG_WARNING);
2083 public function process_override($data) {
2084 $data = (object)$data;
2086 // Check roleid is one of the mapped ones
2087 $newroleid = $this->get_mappingid('role', $data->roleid);
2088 // If newroleid and context are valid assign it via API (it handles dupes and so on)
2089 if ($newroleid && $this->task->get_contextid()) {
2090 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
2091 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
2092 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
2098 * If no instances yet add default enrol methods the same way as when creating new course in UI.
2100 class restore_default_enrolments_step extends restore_execution_step {
2102 public function define_execution() {
2103 global $DB;
2105 // No enrolments in front page.
2106 if ($this->get_courseid() == SITEID) {
2107 return;
2110 $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
2112 if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
2113 // Something already added instances, do not add default instances.
2114 $plugins = enrol_get_plugins(true);
2115 foreach ($plugins as $plugin) {
2116 $plugin->restore_sync_course($course);
2119 } else {
2120 // Looks like a newly created course.
2121 enrol_course_updated(true, $course, null);
2127 * This structure steps restores the enrol plugins and their underlying
2128 * enrolments, performing all the mappings and/or movements required
2130 class restore_enrolments_structure_step extends restore_structure_step {
2131 protected $enrolsynced = false;
2132 protected $plugins = null;
2133 protected $originalstatus = array();
2136 * Conditionally decide if this step should be executed.
2138 * This function checks the following parameter:
2140 * 1. the course/enrolments.xml file exists
2142 * @return bool true is safe to execute, false otherwise
2144 protected function execute_condition() {
2146 if ($this->get_courseid() == SITEID) {
2147 return false;
2150 // Check it is included in the backup
2151 $fullpath = $this->task->get_taskbasepath();
2152 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2153 if (!file_exists($fullpath)) {
2154 // Not found, can't restore enrolments info
2155 return false;
2158 return true;
2161 protected function define_structure() {
2163 $userinfo = $this->get_setting_value('users');
2165 $paths = [];
2166 $paths[] = $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2167 if ($userinfo) {
2168 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2170 // Attach local plugin stucture to enrol element.
2171 $this->add_plugin_structure('enrol', $enrol);
2173 return $paths;
2177 * Create enrolment instances.
2179 * This has to be called after creation of roles
2180 * and before adding of role assignments.
2182 * @param mixed $data
2183 * @return void
2185 public function process_enrol($data) {
2186 global $DB;
2188 $data = (object)$data;
2189 $oldid = $data->id; // We'll need this later.
2190 unset($data->id);
2192 $this->originalstatus[$oldid] = $data->status;
2194 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2195 $this->set_mapping('enrol', $oldid, 0);
2196 return;
2199 if (!isset($this->plugins)) {
2200 $this->plugins = enrol_get_plugins(true);
2203 if (!$this->enrolsynced) {
2204 // Make sure that all plugin may create instances and enrolments automatically
2205 // before the first instance restore - this is suitable especially for plugins
2206 // that synchronise data automatically using course->idnumber or by course categories.
2207 foreach ($this->plugins as $plugin) {
2208 $plugin->restore_sync_course($courserec);
2210 $this->enrolsynced = true;
2213 // Map standard fields - plugin has to process custom fields manually.
2214 $data->roleid = $this->get_mappingid('role', $data->roleid);
2215 $data->courseid = $courserec->id;
2217 if (!$this->get_setting_value('users') && $this->get_setting_value('enrolments') == backup::ENROL_WITHUSERS) {
2218 $converttomanual = true;
2219 } else {
2220 $converttomanual = ($this->get_setting_value('enrolments') == backup::ENROL_NEVER);
2223 if ($converttomanual) {
2224 // Restore enrolments as manual enrolments.
2225 unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2226 if (!enrol_is_enabled('manual')) {
2227 $this->set_mapping('enrol', $oldid, 0);
2228 return;
2230 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2231 $instance = reset($instances);
2232 $this->set_mapping('enrol', $oldid, $instance->id);
2233 } else {
2234 if ($data->enrol === 'manual') {
2235 $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2236 } else {
2237 $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2239 $this->set_mapping('enrol', $oldid, $instanceid);
2242 } else {
2243 if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2244 $this->set_mapping('enrol', $oldid, 0);
2245 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, consider restoring without enrolment methods";
2246 $this->log($message, backup::LOG_WARNING);
2247 return;
2249 if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2250 // Let's keep the sortorder in old backups.
2251 } else {
2252 // Prevent problems with colliding sortorders in old backups,
2253 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2254 unset($data->sortorder);
2256 // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2257 $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2262 * Create user enrolments.
2264 * This has to be called after creation of enrolment instances
2265 * and before adding of role assignments.
2267 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2269 * @param mixed $data
2270 * @return void
2272 public function process_enrolment($data) {
2273 global $DB;
2275 if (!isset($this->plugins)) {
2276 $this->plugins = enrol_get_plugins(true);
2279 $data = (object)$data;
2281 // Process only if parent instance have been mapped.
2282 if ($enrolid = $this->get_new_parentid('enrol')) {
2283 $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2284 $oldenrolid = $this->get_old_parentid('enrol');
2285 if (isset($this->originalstatus[$oldenrolid])) {
2286 $oldinstancestatus = $this->originalstatus[$oldenrolid];
2288 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2289 // And only if user is a mapped one.
2290 if ($userid = $this->get_mappingid('user', $data->userid)) {
2291 if (isset($this->plugins[$instance->enrol])) {
2292 $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2302 * Make sure the user restoring the course can actually access it.
2304 class restore_fix_restorer_access_step extends restore_execution_step {
2305 protected function define_execution() {
2306 global $CFG, $DB;
2308 if (!$userid = $this->task->get_userid()) {
2309 return;
2312 if (empty($CFG->restorernewroleid)) {
2313 // Bad luck, no fallback role for restorers specified
2314 return;
2317 $courseid = $this->get_courseid();
2318 $context = context_course::instance($courseid);
2320 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2321 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2322 return;
2325 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2326 role_assign($CFG->restorernewroleid, $userid, $context);
2328 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2329 // Extra role is enough, yay!
2330 return;
2333 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2334 // hopefully admin selected suitable $CFG->restorernewroleid ...
2335 if (!enrol_is_enabled('manual')) {
2336 return;
2338 if (!$enrol = enrol_get_plugin('manual')) {
2339 return;
2341 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2342 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2343 $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2344 $enrol->add_instance($course, $fields);
2347 enrol_try_internal_enrol($courseid, $userid);
2353 * This structure steps restores the filters and their configs
2355 class restore_filters_structure_step extends restore_structure_step {
2357 protected function define_structure() {
2359 $paths = array();
2361 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2362 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2364 return $paths;
2367 public function process_active($data) {
2369 $data = (object)$data;
2371 if (strpos($data->filter, 'filter/') === 0) {
2372 $data->filter = substr($data->filter, 7);
2374 } else if (strpos($data->filter, '/') !== false) {
2375 // Unsupported old filter.
2376 return;
2379 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2380 return;
2382 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2385 public function process_config($data) {
2387 $data = (object)$data;
2389 if (strpos($data->filter, 'filter/') === 0) {
2390 $data->filter = substr($data->filter, 7);
2392 } else if (strpos($data->filter, '/') !== false) {
2393 // Unsupported old filter.
2394 return;
2397 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2398 return;
2400 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2406 * This structure steps restores the comments
2407 * Note: Cannot use the comments API because defaults to USER->id.
2408 * That should change allowing to pass $userid
2410 class restore_comments_structure_step extends restore_structure_step {
2412 protected function define_structure() {
2414 $paths = array();
2416 $paths[] = new restore_path_element('comment', '/comments/comment');
2418 return $paths;
2421 public function process_comment($data) {
2422 global $DB;
2424 $data = (object)$data;
2426 // First of all, if the comment has some itemid, ask to the task what to map
2427 $mapping = false;
2428 if ($data->itemid) {
2429 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2430 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2432 // Only restore the comment if has no mapping OR we have found the matching mapping
2433 if (!$mapping || $data->itemid) {
2434 // Only if user mapping and context
2435 $data->userid = $this->get_mappingid('user', $data->userid);
2436 if ($data->userid && $this->task->get_contextid()) {
2437 $data->contextid = $this->task->get_contextid();
2438 // Only if there is another comment with same context/user/timecreated
2439 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2440 if (!$DB->record_exists('comments', $params)) {
2441 $DB->insert_record('comments', $data);
2449 * This structure steps restores the badges and their configs
2451 class restore_badges_structure_step extends restore_structure_step {
2454 * Conditionally decide if this step should be executed.
2456 * This function checks the following parameters:
2458 * 1. Badges and course badges are enabled on the site.
2459 * 2. The course/badges.xml file exists.
2460 * 3. All modules are restorable.
2461 * 4. All modules are marked for restore.
2463 * @return bool True is safe to execute, false otherwise
2465 protected function execute_condition() {
2466 global $CFG;
2468 // First check is badges and course level badges are enabled on this site.
2469 if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2470 // Disabled, don't restore course badges.
2471 return false;
2474 // Check if badges.xml is included in the backup.
2475 $fullpath = $this->task->get_taskbasepath();
2476 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2477 if (!file_exists($fullpath)) {
2478 // Not found, can't restore course badges.
2479 return false;
2482 // Check we are able to restore all backed up modules.
2483 if ($this->task->is_missing_modules()) {
2484 return false;
2487 // Finally check all modules within the backup are being restored.
2488 if ($this->task->is_excluding_activities()) {
2489 return false;
2492 return true;
2495 protected function define_structure() {
2496 $paths = array();
2497 $paths[] = new restore_path_element('badge', '/badges/badge');
2498 $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2499 $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2500 $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2502 return $paths;
2505 public function process_badge($data) {
2506 global $DB, $CFG;
2508 require_once($CFG->libdir . '/badgeslib.php');
2510 $data = (object)$data;
2511 $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2512 if (empty($data->usercreated)) {
2513 $data->usercreated = $this->task->get_userid();
2515 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2516 if (empty($data->usermodified)) {
2517 $data->usermodified = $this->task->get_userid();
2520 // We'll restore the badge image.
2521 $restorefiles = true;
2523 $courseid = $this->get_courseid();
2525 $params = array(
2526 'name' => $data->name,
2527 'description' => $data->description,
2528 'timecreated' => $data->timecreated,
2529 'timemodified' => $data->timemodified,
2530 'usercreated' => $data->usercreated,
2531 'usermodified' => $data->usermodified,
2532 'issuername' => $data->issuername,
2533 'issuerurl' => $data->issuerurl,
2534 'issuercontact' => $data->issuercontact,
2535 'expiredate' => $this->apply_date_offset($data->expiredate),
2536 'expireperiod' => $data->expireperiod,
2537 'type' => BADGE_TYPE_COURSE,
2538 'courseid' => $courseid,
2539 'message' => $data->message,
2540 'messagesubject' => $data->messagesubject,
2541 'attachment' => $data->attachment,
2542 'notification' => $data->notification,
2543 'status' => BADGE_STATUS_INACTIVE,
2544 'nextcron' => $data->nextcron
2547 $newid = $DB->insert_record('badge', $params);
2548 $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2551 public function process_criterion($data) {
2552 global $DB;
2554 $data = (object)$data;
2556 $params = array(
2557 'badgeid' => $this->get_new_parentid('badge'),
2558 'criteriatype' => $data->criteriatype,
2559 'method' => $data->method,
2560 'description' => isset($data->description) ? $data->description : '',
2561 'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0,
2563 $newid = $DB->insert_record('badge_criteria', $params);
2564 $this->set_mapping('criterion', $data->id, $newid);
2567 public function process_parameter($data) {
2568 global $DB, $CFG;
2570 require_once($CFG->libdir . '/badgeslib.php');
2572 $data = (object)$data;
2573 $criteriaid = $this->get_new_parentid('criterion');
2575 // Parameter array that will go to database.
2576 $params = array();
2577 $params['critid'] = $criteriaid;
2579 $oldparam = explode('_', $data->name);
2581 if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2582 $module = $this->get_mappingid('course_module', $oldparam[1]);
2583 $params['name'] = $oldparam[0] . '_' . $module;
2584 $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2585 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2586 $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2587 $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2588 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2589 $role = $this->get_mappingid('role', $data->value);
2590 if (!empty($role)) {
2591 $params['name'] = 'role_' . $role;
2592 $params['value'] = $role;
2593 } else {
2594 return;
2598 if (!$DB->record_exists('badge_criteria_param', $params)) {
2599 $DB->insert_record('badge_criteria_param', $params);
2603 public function process_manual_award($data) {
2604 global $DB;
2606 $data = (object)$data;
2607 $role = $this->get_mappingid('role', $data->issuerrole);
2609 if (!empty($role)) {
2610 $award = array(
2611 'badgeid' => $this->get_new_parentid('badge'),
2612 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2613 'issuerid' => $this->get_mappingid('user', $data->issuerid),
2614 'issuerrole' => $role,
2615 'datemet' => $this->apply_date_offset($data->datemet)
2618 // Skip the manual award if recipient or issuer can not be mapped to.
2619 if (empty($award['recipientid']) || empty($award['issuerid'])) {
2620 return;
2623 $DB->insert_record('badge_manual_award', $award);
2627 protected function after_execute() {
2628 // Add related files.
2629 $this->add_related_files('badges', 'badgeimage', 'badge');
2634 * This structure steps restores the calendar events
2636 class restore_calendarevents_structure_step extends restore_structure_step {
2638 protected function define_structure() {
2640 $paths = array();
2642 $paths[] = new restore_path_element('calendarevents', '/events/event');
2644 return $paths;
2647 public function process_calendarevents($data) {
2648 global $DB, $SITE, $USER;
2650 $data = (object)$data;
2651 $oldid = $data->id;
2652 $restorefiles = true; // We'll restore the files
2654 // If this is a new action event, it will automatically be populated by the adhoc task.
2655 // Nothing to do here.
2656 if (isset($data->type) && $data->type == CALENDAR_EVENT_TYPE_ACTION) {
2657 return;
2660 // User overrides for activities are identified by having a courseid of zero with
2661 // both a modulename and instance value set.
2662 $isuseroverride = !$data->courseid && $data->modulename && $data->instance;
2664 // If we don't want to include user data and this record is a user override event
2665 // for an activity then we should not create it. (Only activity events can be user override events - which must have this
2666 // setting).
2667 if ($isuseroverride && $this->task->setting_exists('userinfo') && !$this->task->get_setting_value('userinfo')) {
2668 return;
2671 // Find the userid and the groupid associated with the event.
2672 $data->userid = $this->get_mappingid('user', $data->userid);
2673 if ($data->userid === false) {
2674 // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2675 // Use the current user ID for these events.
2676 $data->userid = $USER->id;
2678 if (!empty($data->groupid)) {
2679 $data->groupid = $this->get_mappingid('group', $data->groupid);
2680 if ($data->groupid === false) {
2681 return;
2684 // Handle events with empty eventtype //MDL-32827
2685 if(empty($data->eventtype)) {
2686 if ($data->courseid == $SITE->id) { // Site event
2687 $data->eventtype = "site";
2688 } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2689 // Course assingment event
2690 $data->eventtype = "due";
2691 } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event
2692 $data->eventtype = "course";
2693 } else if ($data->groupid) { // Group event
2694 $data->eventtype = "group";
2695 } else if ($data->userid) { // User event
2696 $data->eventtype = "user";
2697 } else {
2698 return;
2702 $params = array(
2703 'name' => $data->name,
2704 'description' => $data->description,
2705 'format' => $data->format,
2706 // User overrides in activities use a course id of zero. All other event types
2707 // must use the mapped course id.
2708 'courseid' => $data->courseid ? $this->get_courseid() : 0,
2709 'groupid' => $data->groupid,
2710 'userid' => $data->userid,
2711 'repeatid' => $this->get_mappingid('event', $data->repeatid),
2712 'modulename' => $data->modulename,
2713 'type' => isset($data->type) ? $data->type : 0,
2714 'eventtype' => $data->eventtype,
2715 'timestart' => $this->apply_date_offset($data->timestart),
2716 'timeduration' => $data->timeduration,
2717 'timesort' => isset($data->timesort) ? $this->apply_date_offset($data->timesort) : null,
2718 'visible' => $data->visible,
2719 'uuid' => $data->uuid,
2720 'sequence' => $data->sequence,
2721 'timemodified' => $data->timemodified,
2722 'priority' => isset($data->priority) ? $data->priority : null);
2723 if ($this->name == 'activity_calendar') {
2724 $params['instance'] = $this->task->get_activityid();
2725 } else {
2726 $params['instance'] = 0;
2728 $sql = "SELECT id
2729 FROM {event}
2730 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2731 AND courseid = ?
2732 AND modulename = ?
2733 AND instance = ?
2734 AND timestart = ?
2735 AND timeduration = ?
2736 AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2737 $arg = array ($params['name'], $params['courseid'], $params['modulename'], $params['instance'], $params['timestart'], $params['timeduration'], $params['description']);
2738 $result = $DB->record_exists_sql($sql, $arg);
2739 if (empty($result)) {
2740 $newitemid = $DB->insert_record('event', $params);
2741 $this->set_mapping('event', $oldid, $newitemid);
2742 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2744 // With repeating events, each event has the repeatid pointed at the first occurrence.
2745 // Since the repeatid will be empty when the first occurrence is restored,
2746 // Get the repeatid from the second occurrence of the repeating event and use that to update the first occurrence.
2747 // Then keep a list of repeatids so we only perform this update once.
2748 static $repeatids = array();
2749 if (!empty($params['repeatid']) && !in_array($params['repeatid'], $repeatids)) {
2750 // This entry is repeated so the repeatid field must be set.
2751 $DB->set_field('event', 'repeatid', $params['repeatid'], array('id' => $params['repeatid']));
2752 $repeatids[] = $params['repeatid'];
2756 protected function after_execute() {
2757 // Add related files
2758 $this->add_related_files('calendar', 'event_description', 'event_description');
2762 class restore_course_completion_structure_step extends restore_structure_step {
2765 * Conditionally decide if this step should be executed.
2767 * This function checks parameters that are not immediate settings to ensure
2768 * that the enviroment is suitable for the restore of course completion info.
2770 * This function checks the following four parameters:
2772 * 1. Course completion is enabled on the site
2773 * 2. The backup includes course completion information
2774 * 3. All modules are restorable
2775 * 4. All modules are marked for restore.
2776 * 5. No completion criteria already exist for the course.
2778 * @return bool True is safe to execute, false otherwise
2780 protected function execute_condition() {
2781 global $CFG, $DB;
2783 // First check course completion is enabled on this site
2784 if (empty($CFG->enablecompletion)) {
2785 // Disabled, don't restore course completion
2786 return false;
2789 // No course completion on the front page.
2790 if ($this->get_courseid() == SITEID) {
2791 return false;
2794 // Check it is included in the backup
2795 $fullpath = $this->task->get_taskbasepath();
2796 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2797 if (!file_exists($fullpath)) {
2798 // Not found, can't restore course completion
2799 return false;
2802 // Check we are able to restore all backed up modules
2803 if ($this->task->is_missing_modules()) {
2804 return false;
2807 // Check all modules within the backup are being restored.
2808 if ($this->task->is_excluding_activities()) {
2809 return false;
2812 // Check that no completion criteria is already set for the course.
2813 if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
2814 return false;
2817 return true;
2821 * Define the course completion structure
2823 * @return array Array of restore_path_element
2825 protected function define_structure() {
2827 // To know if we are including user completion info
2828 $userinfo = $this->get_setting_value('userscompletion');
2830 $paths = array();
2831 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2832 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2834 if ($userinfo) {
2835 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2836 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2839 return $paths;
2844 * Process course completion criteria
2846 * @global moodle_database $DB
2847 * @param stdClass $data
2849 public function process_course_completion_criteria($data) {
2850 global $DB;
2852 $data = (object)$data;
2853 $data->course = $this->get_courseid();
2855 // Apply the date offset to the time end field
2856 $data->timeend = $this->apply_date_offset($data->timeend);
2858 // Map the role from the criteria
2859 if (isset($data->role) && $data->role != '') {
2860 // Newer backups should include roleshortname, which makes this much easier.
2861 if (!empty($data->roleshortname)) {
2862 $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
2863 if (!$roleinstanceid) {
2864 $this->log(
2865 'Could not match the role shortname in course_completion_criteria, so skipping',
2866 backup::LOG_DEBUG
2868 return;
2870 $data->role = $roleinstanceid;
2871 } else {
2872 $data->role = $this->get_mappingid('role', $data->role);
2875 // Check we have an id, otherwise it causes all sorts of bugs.
2876 if (!$data->role) {
2877 $this->log(
2878 'Could not match role in course_completion_criteria, so skipping',
2879 backup::LOG_DEBUG
2881 return;
2885 // If the completion criteria is for a module we need to map the module instance
2886 // to the new module id.
2887 if (!empty($data->moduleinstance) && !empty($data->module)) {
2888 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
2889 if (empty($data->moduleinstance)) {
2890 $this->log(
2891 'Could not match the module instance in course_completion_criteria, so skipping',
2892 backup::LOG_DEBUG
2894 return;
2896 } else {
2897 $data->module = null;
2898 $data->moduleinstance = null;
2901 // We backup the course shortname rather than the ID so that we can match back to the course
2902 if (!empty($data->courseinstanceshortname)) {
2903 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
2904 if (!$courseinstanceid) {
2905 $this->log(
2906 'Could not match the course instance in course_completion_criteria, so skipping',
2907 backup::LOG_DEBUG
2909 return;
2911 } else {
2912 $courseinstanceid = null;
2914 $data->courseinstance = $courseinstanceid;
2916 $params = array(
2917 'course' => $data->course,
2918 'criteriatype' => $data->criteriatype,
2919 'enrolperiod' => $data->enrolperiod,
2920 'courseinstance' => $data->courseinstance,
2921 'module' => $data->module,
2922 'moduleinstance' => $data->moduleinstance,
2923 'timeend' => $data->timeend,
2924 'gradepass' => $data->gradepass,
2925 'role' => $data->role
2927 $newid = $DB->insert_record('course_completion_criteria', $params);
2928 $this->set_mapping('course_completion_criteria', $data->id, $newid);
2932 * Processes course compltion criteria complete records
2934 * @global moodle_database $DB
2935 * @param stdClass $data
2937 public function process_course_completion_crit_compl($data) {
2938 global $DB;
2940 $data = (object)$data;
2942 // This may be empty if criteria could not be restored
2943 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
2945 $data->course = $this->get_courseid();
2946 $data->userid = $this->get_mappingid('user', $data->userid);
2948 if (!empty($data->criteriaid) && !empty($data->userid)) {
2949 $params = array(
2950 'userid' => $data->userid,
2951 'course' => $data->course,
2952 'criteriaid' => $data->criteriaid,
2953 'timecompleted' => $data->timecompleted
2955 if (isset($data->gradefinal)) {
2956 $params['gradefinal'] = $data->gradefinal;
2958 if (isset($data->unenroled)) {
2959 $params['unenroled'] = $data->unenroled;
2961 $DB->insert_record('course_completion_crit_compl', $params);
2966 * Process course completions
2968 * @global moodle_database $DB
2969 * @param stdClass $data
2971 public function process_course_completions($data) {
2972 global $DB;
2974 $data = (object)$data;
2976 $data->course = $this->get_courseid();
2977 $data->userid = $this->get_mappingid('user', $data->userid);
2979 if (!empty($data->userid)) {
2980 $params = array(
2981 'userid' => $data->userid,
2982 'course' => $data->course,
2983 'timeenrolled' => $data->timeenrolled,
2984 'timestarted' => $data->timestarted,
2985 'timecompleted' => $data->timecompleted,
2986 'reaggregate' => $data->reaggregate
2989 $existing = $DB->get_record('course_completions', array(
2990 'userid' => $data->userid,
2991 'course' => $data->course
2994 // MDL-46651 - If cron writes out a new record before we get to it
2995 // then we should replace it with the Truth data from the backup.
2996 // This may be obsolete after MDL-48518 is resolved
2997 if ($existing) {
2998 $params['id'] = $existing->id;
2999 $DB->update_record('course_completions', $params);
3000 } else {
3001 $DB->insert_record('course_completions', $params);
3007 * Process course completion aggregate methods
3009 * @global moodle_database $DB
3010 * @param stdClass $data
3012 public function process_course_completion_aggr_methd($data) {
3013 global $DB;
3015 $data = (object)$data;
3017 $data->course = $this->get_courseid();
3019 // Only create the course_completion_aggr_methd records if
3020 // the target course has not them defined. MDL-28180
3021 if (!$DB->record_exists('course_completion_aggr_methd', array(
3022 'course' => $data->course,
3023 'criteriatype' => $data->criteriatype))) {
3024 $params = array(
3025 'course' => $data->course,
3026 'criteriatype' => $data->criteriatype,
3027 'method' => $data->method,
3028 'value' => $data->value,
3030 $DB->insert_record('course_completion_aggr_methd', $params);
3037 * This structure step restores course logs (cmid = 0), delegating
3038 * the hard work to the corresponding {@link restore_logs_processor} passing the
3039 * collection of {@link restore_log_rule} rules to be observed as they are defined
3040 * by the task. Note this is only executed based in the 'logs' setting.
3042 * NOTE: This is executed by final task, to have all the activities already restored
3044 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
3045 * records are. There are others like 'calendar' and 'upload' that will be handled
3046 * later.
3048 * NOTE: All the missing actions (not able to be restored) are sent to logs for
3049 * debugging purposes
3051 class restore_course_logs_structure_step extends restore_structure_step {
3054 * Conditionally decide if this step should be executed.
3056 * This function checks the following parameter:
3058 * 1. the course/logs.xml file exists
3060 * @return bool true is safe to execute, false otherwise
3062 protected function execute_condition() {
3064 // Check it is included in the backup
3065 $fullpath = $this->task->get_taskbasepath();
3066 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3067 if (!file_exists($fullpath)) {
3068 // Not found, can't restore course logs
3069 return false;
3072 return true;
3075 protected function define_structure() {
3077 $paths = array();
3079 // Simple, one plain level of information contains them
3080 $paths[] = new restore_path_element('log', '/logs/log');
3082 return $paths;
3085 protected function process_log($data) {
3086 global $DB;
3088 $data = (object)($data);
3090 // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3092 $data->userid = $this->get_mappingid('user', $data->userid);
3093 $data->course = $this->get_courseid();
3094 $data->cmid = 0;
3096 // For any reason user wasn't remapped ok, stop processing this
3097 if (empty($data->userid)) {
3098 return;
3101 // Everything ready, let's delegate to the restore_logs_processor
3103 // Set some fixed values that will save tons of DB requests
3104 $values = array(
3105 'course' => $this->get_courseid());
3106 // Get instance and process log record
3107 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3109 // If we have data, insert it, else something went wrong in the restore_logs_processor
3110 if ($data) {
3111 if (empty($data->url)) {
3112 $data->url = '';
3114 if (empty($data->info)) {
3115 $data->info = '';
3117 // Store the data in the legacy log table if we are still using it.
3118 $manager = get_log_manager();
3119 if (method_exists($manager, 'legacy_add_to_log')) {
3120 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3121 $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3128 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
3129 * sharing its same structure but modifying the way records are handled
3131 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
3133 protected function process_log($data) {
3134 global $DB;
3136 $data = (object)($data);
3138 // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3140 $data->userid = $this->get_mappingid('user', $data->userid);
3141 $data->course = $this->get_courseid();
3142 $data->cmid = $this->task->get_moduleid();
3144 // For any reason user wasn't remapped ok, stop processing this
3145 if (empty($data->userid)) {
3146 return;
3149 // Everything ready, let's delegate to the restore_logs_processor
3151 // Set some fixed values that will save tons of DB requests
3152 $values = array(
3153 'course' => $this->get_courseid(),
3154 'course_module' => $this->task->get_moduleid(),
3155 $this->task->get_modulename() => $this->task->get_activityid());
3156 // Get instance and process log record
3157 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3159 // If we have data, insert it, else something went wrong in the restore_logs_processor
3160 if ($data) {
3161 if (empty($data->url)) {
3162 $data->url = '';
3164 if (empty($data->info)) {
3165 $data->info = '';
3167 // Store the data in the legacy log table if we are still using it.
3168 $manager = get_log_manager();
3169 if (method_exists($manager, 'legacy_add_to_log')) {
3170 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3171 $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3178 * Structure step in charge of restoring the logstores.xml file for the course logs.
3180 * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3181 * it, for logs belonging to the course level.
3183 class restore_course_logstores_structure_step extends restore_structure_step {
3186 * Conditionally decide if this step should be executed.
3188 * This function checks the following parameter:
3190 * 1. the logstores.xml file exists
3192 * @return bool true is safe to execute, false otherwise
3194 protected function execute_condition() {
3196 // Check it is included in the backup.
3197 $fullpath = $this->task->get_taskbasepath();
3198 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3199 if (!file_exists($fullpath)) {
3200 // Not found, can't restore logstores.xml information.
3201 return false;
3204 return true;
3208 * Return the elements to be processed on restore of logstores.
3210 * @return restore_path_element[] array of elements to be processed on restore.
3212 protected function define_structure() {
3214 $paths = array();
3216 $logstore = new restore_path_element('logstore', '/logstores/logstore');
3217 $paths[] = $logstore;
3219 // Add logstore subplugin support to the 'logstore' element.
3220 $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3222 return array($logstore);
3226 * Process the 'logstore' element,
3228 * Note: This is empty by definition in backup, because stores do not share any
3229 * data between them, so there is nothing to process here.
3231 * @param array $data element data
3233 protected function process_logstore($data) {
3234 return;
3239 * Structure step in charge of restoring the logstores.xml file for the activity logs.
3241 * Note: Activity structure is completely equivalent to the course one, so just extend it.
3243 class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3247 * Restore course competencies structure step.
3249 class restore_course_competencies_structure_step extends restore_structure_step {
3252 * Returns the structure.
3254 * @return array
3256 protected function define_structure() {
3257 $userinfo = $this->get_setting_value('users');
3258 $paths = array(
3259 new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3260 new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3262 if ($userinfo) {
3263 $paths[] = new restore_path_element('user_competency_course',
3264 '/course_competencies/user_competencies/user_competency');
3266 return $paths;
3270 * Process a course competency settings.
3272 * @param array $data The data.
3274 public function process_course_competency_settings($data) {
3275 global $DB;
3276 $data = (object) $data;
3278 // We do not restore the course settings during merge.
3279 $target = $this->get_task()->get_target();
3280 if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) {
3281 return;
3284 $courseid = $this->task->get_courseid();
3285 $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3286 array('courseid' => $courseid));
3288 // Strangely the course settings already exist, let's just leave them as is then.
3289 if ($exists) {
3290 $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING);
3291 return;
3294 $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3295 $settings = new \core_competency\course_competency_settings(0, $data);
3296 $settings->create();
3300 * Process a course competency.
3302 * @param array $data The data.
3304 public function process_course_competency($data) {
3305 $data = (object) $data;
3307 // Mapping the competency by ID numbers.
3308 $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3309 if (!$framework) {
3310 return;
3312 $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3313 'competencyframeworkid' => $framework->get('id')));
3314 if (!$competency) {
3315 return;
3317 $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get('id'));
3319 $params = array(
3320 'competencyid' => $competency->get('id'),
3321 'courseid' => $this->task->get_courseid()
3323 $query = 'competencyid = :competencyid AND courseid = :courseid';
3324 $existing = \core_competency\course_competency::record_exists_select($query, $params);
3326 if (!$existing) {
3327 // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3328 $record = (object) $params;
3329 $record->ruleoutcome = $data->ruleoutcome;
3330 $coursecompetency = new \core_competency\course_competency(0, $record);
3331 $coursecompetency->create();
3336 * Process the user competency course.
3338 * @param array $data The data.
3340 public function process_user_competency_course($data) {
3341 global $USER, $DB;
3342 $data = (object) $data;
3344 $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid);
3345 if (!$data->competencyid) {
3346 // This is strange, the competency does not belong to the course.
3347 return;
3348 } else if ($data->grade === null) {
3349 // We do not need to do anything when there is no grade.
3350 return;
3353 $data->userid = $this->get_mappingid('user', $data->userid);
3354 $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
3356 // The method add_evidence also sets the course rating.
3357 \core_competency\api::add_evidence($data->userid,
3358 $data->competencyid,
3359 $this->task->get_contextid(),
3360 \core_competency\evidence::ACTION_OVERRIDE,
3361 'evidence_courserestored',
3362 'core_competency',
3363 $shortname,
3364 false,
3365 null,
3366 $data->grade,
3367 $USER->id);
3371 * Execute conditions.
3373 * @return bool
3375 protected function execute_condition() {
3377 // Do not execute if competencies are not included.
3378 if (!$this->get_setting_value('competencies')) {
3379 return false;
3382 // Do not execute if the competencies XML file is not found.
3383 $fullpath = $this->task->get_taskbasepath();
3384 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3385 if (!file_exists($fullpath)) {
3386 return false;
3389 return true;
3394 * Restore activity competencies structure step.
3396 class restore_activity_competencies_structure_step extends restore_structure_step {
3399 * Defines the structure.
3401 * @return array
3403 protected function define_structure() {
3404 $paths = array(
3405 new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3407 return $paths;
3411 * Process a course module competency.
3413 * @param array $data The data.
3415 public function process_course_module_competency($data) {
3416 $data = (object) $data;
3418 // Mapping the competency by ID numbers.
3419 $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3420 if (!$framework) {
3421 return;
3423 $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3424 'competencyframeworkid' => $framework->get('id')));
3425 if (!$competency) {
3426 return;
3429 $params = array(
3430 'competencyid' => $competency->get('id'),
3431 'cmid' => $this->task->get_moduleid()
3433 $query = 'competencyid = :competencyid AND cmid = :cmid';
3434 $existing = \core_competency\course_module_competency::record_exists_select($query, $params);
3436 if (!$existing) {
3437 // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3438 $record = (object) $params;
3439 $record->ruleoutcome = $data->ruleoutcome;
3440 $coursemodulecompetency = new \core_competency\course_module_competency(0, $record);
3441 $coursemodulecompetency->create();
3446 * Execute conditions.
3448 * @return bool
3450 protected function execute_condition() {
3452 // Do not execute if competencies are not included.
3453 if (!$this->get_setting_value('competencies')) {
3454 return false;
3457 // Do not execute if the competencies XML file is not found.
3458 $fullpath = $this->task->get_taskbasepath();
3459 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3460 if (!file_exists($fullpath)) {
3461 return false;
3464 return true;
3469 * Defines the restore step for advanced grading methods attached to the activity module
3471 class restore_activity_grading_structure_step extends restore_structure_step {
3474 * This step is executed only if the grading file is present
3476 protected function execute_condition() {
3478 if ($this->get_courseid() == SITEID) {
3479 return false;
3482 $fullpath = $this->task->get_taskbasepath();
3483 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3484 if (!file_exists($fullpath)) {
3485 return false;
3488 return true;
3493 * Declares paths in the grading.xml file we are interested in
3495 protected function define_structure() {
3497 $paths = array();
3498 $userinfo = $this->get_setting_value('userinfo');
3500 $area = new restore_path_element('grading_area', '/areas/area');
3501 $paths[] = $area;
3502 // attach local plugin stucture to $area element
3503 $this->add_plugin_structure('local', $area);
3505 $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
3506 $paths[] = $definition;
3507 $this->add_plugin_structure('gradingform', $definition);
3508 // attach local plugin stucture to $definition element
3509 $this->add_plugin_structure('local', $definition);
3512 if ($userinfo) {
3513 $instance = new restore_path_element('grading_instance',
3514 '/areas/area/definitions/definition/instances/instance');
3515 $paths[] = $instance;
3516 $this->add_plugin_structure('gradingform', $instance);
3517 // attach local plugin stucture to $intance element
3518 $this->add_plugin_structure('local', $instance);
3521 return $paths;
3525 * Processes one grading area element
3527 * @param array $data element data
3529 protected function process_grading_area($data) {
3530 global $DB;
3532 $task = $this->get_task();
3533 $data = (object)$data;
3534 $oldid = $data->id;
3535 $data->component = 'mod_'.$task->get_modulename();
3536 $data->contextid = $task->get_contextid();
3538 $newid = $DB->insert_record('grading_areas', $data);
3539 $this->set_mapping('grading_area', $oldid, $newid);
3543 * Processes one grading definition element
3545 * @param array $data element data
3547 protected function process_grading_definition($data) {
3548 global $DB;
3550 $task = $this->get_task();
3551 $data = (object)$data;
3552 $oldid = $data->id;
3553 $data->areaid = $this->get_new_parentid('grading_area');
3554 $data->copiedfromid = null;
3555 $data->timecreated = time();
3556 $data->usercreated = $task->get_userid();
3557 $data->timemodified = $data->timecreated;
3558 $data->usermodified = $data->usercreated;
3560 $newid = $DB->insert_record('grading_definitions', $data);
3561 $this->set_mapping('grading_definition', $oldid, $newid, true);
3565 * Processes one grading form instance element
3567 * @param array $data element data
3569 protected function process_grading_instance($data) {
3570 global $DB;
3572 $data = (object)$data;
3574 // new form definition id
3575 $newformid = $this->get_new_parentid('grading_definition');
3577 // get the name of the area we are restoring to
3578 $sql = "SELECT ga.areaname
3579 FROM {grading_definitions} gd
3580 JOIN {grading_areas} ga ON gd.areaid = ga.id
3581 WHERE gd.id = ?";
3582 $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
3584 // get the mapped itemid - the activity module is expected to define the mappings
3585 // for each gradable area
3586 $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
3588 $oldid = $data->id;
3589 $data->definitionid = $newformid;
3590 $data->raterid = $this->get_mappingid('user', $data->raterid);
3591 $data->itemid = $newitemid;
3593 $newid = $DB->insert_record('grading_instances', $data);
3594 $this->set_mapping('grading_instance', $oldid, $newid);
3598 * Final operations when the database records are inserted
3600 protected function after_execute() {
3601 // Add files embedded into the definition description
3602 $this->add_related_files('grading', 'description', 'grading_definition');
3608 * This structure step restores the grade items associated with one activity
3609 * All the grade items are made child of the "course" grade item but the original
3610 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3611 * the complete gradebook (categories and calculations), that information is
3612 * available there
3614 class restore_activity_grades_structure_step extends restore_structure_step {
3617 * No grades in front page.
3618 * @return bool
3620 protected function execute_condition() {
3621 return ($this->get_courseid() != SITEID);
3624 protected function define_structure() {
3626 $paths = array();
3627 $userinfo = $this->get_setting_value('userinfo');
3629 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3630 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3631 if ($userinfo) {
3632 $paths[] = new restore_path_element('grade_grade',
3633 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
3635 return $paths;
3638 protected function process_grade_item($data) {
3639 global $DB;
3641 $data = (object)($data);
3642 $oldid = $data->id; // We'll need these later
3643 $oldparentid = $data->categoryid;
3644 $courseid = $this->get_courseid();
3646 $idnumber = null;
3647 if (!empty($data->idnumber)) {
3648 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
3649 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
3650 // so the best is to keep the ones already in the gradebook
3651 // Potential problem: duplicates if same items are restored more than once. :-(
3652 // This needs to be fixed in some way (outcomes & activities with multiple items)
3653 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
3654 // In any case, verify always for uniqueness
3655 $sql = "SELECT cm.id
3656 FROM {course_modules} cm
3657 WHERE cm.course = :courseid AND
3658 cm.idnumber = :idnumber AND
3659 cm.id <> :cmid";
3660 $params = array(
3661 'courseid' => $courseid,
3662 'idnumber' => $data->idnumber,
3663 'cmid' => $this->task->get_moduleid()
3665 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
3666 $idnumber = $data->idnumber;
3670 if (!empty($data->categoryid)) {
3671 // If the grade category id of the grade item being restored belongs to this course
3672 // then it is a fair assumption that this is the correct grade category for the activity
3673 // and we should leave it in place, if not then unset it.
3674 // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
3675 $conditions = array('id' => $data->categoryid, 'courseid' => $courseid);
3676 if (!$this->task->is_samesite() || !$DB->record_exists('grade_categories', $conditions)) {
3677 unset($data->categoryid);
3681 unset($data->id);
3682 $data->courseid = $this->get_courseid();
3683 $data->iteminstance = $this->task->get_activityid();
3684 $data->idnumber = $idnumber;
3685 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
3686 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
3688 $gradeitem = new grade_item($data, false);
3689 $gradeitem->insert('restore');
3691 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
3692 $gradeitem->sortorder = $data->sortorder;
3693 $gradeitem->update('restore');
3695 // Set mapping, saving the original category id into parentitemid
3696 // gradebook restore (final task) will need it to reorganise items
3697 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
3700 protected function process_grade_grade($data) {
3701 $data = (object)($data);
3702 $olduserid = $data->userid;
3703 $oldid = $data->id;
3704 unset($data->id);
3706 $data->itemid = $this->get_new_parentid('grade_item');
3708 $data->userid = $this->get_mappingid('user', $data->userid, null);
3709 if (!empty($data->userid)) {
3710 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
3711 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
3713 $grade = new grade_grade($data, false);
3714 $grade->insert('restore');
3715 $this->set_mapping('grade_grades', $oldid, $grade->id);
3716 } else {
3717 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
3722 * process activity grade_letters. Note that, while these are possible,
3723 * because grade_letters are contextid based, in practice, only course
3724 * context letters can be defined. So we keep here this method knowing
3725 * it won't be executed ever. gradebook restore will restore course letters.
3727 protected function process_grade_letter($data) {
3728 global $DB;
3730 $data['contextid'] = $this->task->get_contextid();
3731 $gradeletter = (object)$data;
3733 // Check if it exists before adding it
3734 unset($data['id']);
3735 if (!$DB->record_exists('grade_letters', $data)) {
3736 $newitemid = $DB->insert_record('grade_letters', $gradeletter);
3738 // no need to save any grade_letter mapping
3741 public function after_restore() {
3742 // Fix grade item's sortorder after restore, as it might have duplicates.
3743 $courseid = $this->get_task()->get_courseid();
3744 grade_item::fix_duplicate_sortorder($courseid);
3749 * Step in charge of restoring the grade history of an activity.
3751 * This step is added to the task regardless of the setting 'grade_histories'.
3752 * The reason is to allow for a more flexible step in case the logic needs to be
3753 * split accross different settings to control the history of items and/or grades.
3755 class restore_activity_grade_history_structure_step extends restore_structure_step {
3758 * This step is executed only if the grade history file is present.
3760 protected function execute_condition() {
3762 if ($this->get_courseid() == SITEID) {
3763 return false;
3766 $fullpath = $this->task->get_taskbasepath();
3767 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3768 if (!file_exists($fullpath)) {
3769 return false;
3771 return true;
3774 protected function define_structure() {
3775 $paths = array();
3777 // Settings to use.
3778 $userinfo = $this->get_setting_value('userinfo');
3779 $history = $this->get_setting_value('grade_histories');
3781 if ($userinfo && $history) {
3782 $paths[] = new restore_path_element('grade_grade',
3783 '/grade_history/grade_grades/grade_grade');
3786 return $paths;
3789 protected function process_grade_grade($data) {
3790 global $DB;
3792 $data = (object) $data;
3793 $olduserid = $data->userid;
3794 unset($data->id);
3796 $data->userid = $this->get_mappingid('user', $data->userid, null);
3797 if (!empty($data->userid)) {
3798 // Do not apply the date offsets as this is history.
3799 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
3800 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
3801 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
3802 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
3803 $DB->insert_record('grade_grades_history', $data);
3804 } else {
3805 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
3806 $this->log($message, backup::LOG_DEBUG);
3813 * This structure steps restores one instance + positions of one block
3814 * Note: Positions corresponding to one existing context are restored
3815 * here, but all the ones having unknown contexts are sent to backup_ids
3816 * for a later chance to be restored at the end (final task)
3818 class restore_block_instance_structure_step extends restore_structure_step {
3820 protected function define_structure() {
3822 $paths = array();
3824 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
3825 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
3827 return $paths;
3830 public function process_block($data) {
3831 global $DB, $CFG;
3833 $data = (object)$data; // Handy
3834 $oldcontextid = $data->contextid;
3835 $oldid = $data->id;
3836 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
3838 // Look for the parent contextid
3839 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
3840 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
3843 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
3844 // If there is already one block of that type in the parent context
3845 // and the block is not multiple, stop processing
3846 // Use blockslib loader / method executor
3847 if (!$bi = block_instance($data->blockname)) {
3848 return false;
3851 if (!$bi->instance_allow_multiple()) {
3852 // The block cannot be added twice, so we will check if the same block is already being
3853 // displayed on the same page. For this, rather than mocking a page and using the block_manager
3854 // we use a similar query to the one in block_manager::load_blocks(), this will give us
3855 // a very good idea of the blocks already displayed in the context.
3856 $params = array(
3857 'blockname' => $data->blockname
3860 // Context matching test.
3861 $context = context::instance_by_id($data->parentcontextid);
3862 $contextsql = 'bi.parentcontextid = :contextid';
3863 $params['contextid'] = $context->id;
3865 $parentcontextids = $context->get_parent_context_ids();
3866 if ($parentcontextids) {
3867 list($parentcontextsql, $parentcontextparams) =
3868 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
3869 $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
3870 $params = array_merge($params, $parentcontextparams);
3873 // Page type pattern test.
3874 $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
3875 list($pagetypepatternsql, $pagetypepatternparams) =
3876 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
3877 $params = array_merge($params, $pagetypepatternparams);
3879 // Sub page pattern test.
3880 $subpagepatternsql = 'bi.subpagepattern IS NULL';
3881 if ($data->subpagepattern !== null) {
3882 $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
3883 $params['subpagepattern'] = $data->subpagepattern;
3886 $exists = $DB->record_exists_sql("SELECT bi.id
3887 FROM {block_instances} bi
3888 JOIN {block} b ON b.name = bi.blockname
3889 WHERE bi.blockname = :blockname
3890 AND $contextsql
3891 AND bi.pagetypepattern $pagetypepatternsql
3892 AND $subpagepatternsql", $params);
3893 if ($exists) {
3894 // There is at least one very similar block visible on the page where we
3895 // are trying to restore the block. In these circumstances the block API
3896 // would not allow the user to add another instance of the block, so we
3897 // apply the same rule here.
3898 return false;
3902 // If there is already one block of that type in the parent context
3903 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
3904 // stop processing
3905 $params = array(
3906 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
3907 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
3908 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
3909 if ($birecs = $DB->get_records('block_instances', $params)) {
3910 foreach($birecs as $birec) {
3911 if ($birec->configdata == $data->configdata) {
3912 return false;
3917 // Set task old contextid, blockid and blockname once we know them
3918 $this->task->set_old_contextid($oldcontextid);
3919 $this->task->set_old_blockid($oldid);
3920 $this->task->set_blockname($data->blockname);
3922 // Let's look for anything within configdata neededing processing
3923 // (nulls and uses of legacy file.php)
3924 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
3925 $configdata = (array)unserialize(base64_decode($data->configdata));
3926 foreach ($configdata as $attribute => $value) {
3927 if (in_array($attribute, $attrstotransform)) {
3928 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
3931 $data->configdata = base64_encode(serialize((object)$configdata));
3934 // Set timecreated, timemodified if not included (older backup).
3935 if (empty($data->timecreated)) {
3936 $data->timecreated = time();
3938 if (empty($data->timemodified)) {
3939 $data->timemodified = $data->timecreated;
3942 // Create the block instance
3943 $newitemid = $DB->insert_record('block_instances', $data);
3944 // Save the mapping (with restorefiles support)
3945 $this->set_mapping('block_instance', $oldid, $newitemid, true);
3946 // Create the block context
3947 $newcontextid = context_block::instance($newitemid)->id;
3948 // Save the block contexts mapping and sent it to task
3949 $this->set_mapping('context', $oldcontextid, $newcontextid);
3950 $this->task->set_contextid($newcontextid);
3951 $this->task->set_blockid($newitemid);
3953 // Restore block fileareas if declared
3954 $component = 'block_' . $this->task->get_blockname();
3955 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
3956 $this->add_related_files($component, $filearea, null);
3959 // Process block positions, creating them or accumulating for final step
3960 foreach($positions as $position) {
3961 $position = (object)$position;
3962 $position->blockinstanceid = $newitemid; // The instance is always the restored one
3963 // If position is for one already mapped (known) contextid
3964 // process it now, creating the position
3965 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
3966 $position->contextid = $newpositionctxid;
3967 // Create the block position
3968 $DB->insert_record('block_positions', $position);
3970 // The position belongs to an unknown context, send it to backup_ids
3971 // to process them as part of the final steps of restore. We send the
3972 // whole $position object there, hence use the low level method.
3973 } else {
3974 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
3981 * Structure step to restore common course_module information
3983 * This step will process the module.xml file for one activity, in order to restore
3984 * the corresponding information to the course_modules table, skipping various bits
3985 * of information based on CFG settings (groupings, completion...) in order to fullfill
3986 * all the reqs to be able to create the context to be used by all the rest of steps
3987 * in the activity restore task
3989 class restore_module_structure_step extends restore_structure_step {
3991 protected function define_structure() {
3992 global $CFG;
3994 $paths = array();
3996 $module = new restore_path_element('module', '/module');
3997 $paths[] = $module;
3998 if ($CFG->enableavailability) {
3999 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
4000 $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
4003 $paths[] = new restore_path_element('tag', '/module/tags/tag');
4005 // Apply for 'format' plugins optional paths at module level
4006 $this->add_plugin_structure('format', $module);
4008 // Apply for 'plagiarism' plugins optional paths at module level
4009 $this->add_plugin_structure('plagiarism', $module);
4011 // Apply for 'local' plugins optional paths at module level
4012 $this->add_plugin_structure('local', $module);
4014 // Apply for 'admin tool' plugins optional paths at module level.
4015 $this->add_plugin_structure('tool', $module);
4017 return $paths;
4020 protected function process_module($data) {
4021 global $CFG, $DB;
4023 $data = (object)$data;
4024 $oldid = $data->id;
4025 $this->task->set_old_moduleversion($data->version);
4027 $data->course = $this->task->get_courseid();
4028 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
4029 // Map section (first try by course_section mapping match. Useful in course and section restores)
4030 $data->section = $this->get_mappingid('course_section', $data->sectionid);
4031 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
4032 $params = array(
4033 'course' => $this->get_courseid(),
4034 'section' => $data->sectionnumber);
4035 $data->section = $DB->get_field('course_sections', 'id', $params);
4037 if (!$data->section) { // sectionnumber failed, try to get first section in course
4038 $params = array(
4039 'course' => $this->get_courseid());
4040 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
4042 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
4043 $sectionrec = array(
4044 'course' => $this->get_courseid(),
4045 'section' => 0,
4046 'timemodified' => time());
4047 $DB->insert_record('course_sections', $sectionrec); // section 0
4048 $sectionrec = array(
4049 'course' => $this->get_courseid(),
4050 'section' => 1,
4051 'timemodified' => time());
4052 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
4054 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
4055 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
4056 $data->idnumber = '';
4058 if (empty($CFG->enablecompletion)) { // completion
4059 $data->completion = 0;
4060 $data->completiongradeitemnumber = null;
4061 $data->completionview = 0;
4062 $data->completionexpected = 0;
4063 } else {
4064 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
4066 if (empty($CFG->enableavailability)) {
4067 $data->availability = null;
4069 // Backups that did not include showdescription, set it to default 0
4070 // (this is not totally necessary as it has a db default, but just to
4071 // be explicit).
4072 if (!isset($data->showdescription)) {
4073 $data->showdescription = 0;
4075 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
4077 if (empty($data->availability)) {
4078 // If there are legacy availablility data fields (and no new format data),
4079 // convert the old fields.
4080 $data->availability = \core_availability\info::convert_legacy_fields(
4081 $data, false);
4082 } else if (!empty($data->groupmembersonly)) {
4083 // There is current availability data, but it still has groupmembersonly
4084 // as well (2.7 backups), convert just that part.
4085 require_once($CFG->dirroot . '/lib/db/upgradelib.php');
4086 $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
4089 // course_module record ready, insert it
4090 $newitemid = $DB->insert_record('course_modules', $data);
4091 // save mapping
4092 $this->set_mapping('course_module', $oldid, $newitemid);
4093 // set the new course_module id in the task
4094 $this->task->set_moduleid($newitemid);
4095 // we can now create the context safely
4096 $ctxid = context_module::instance($newitemid)->id;
4097 // set the new context id in the task
4098 $this->task->set_contextid($ctxid);
4099 // update sequence field in course_section
4100 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
4101 $sequence .= ',' . $newitemid;
4102 } else {
4103 $sequence = $newitemid;
4106 $updatesection = new \stdClass();
4107 $updatesection->id = $data->section;
4108 $updatesection->sequence = $sequence;
4109 $updatesection->timemodified = time();
4110 $DB->update_record('course_sections', $updatesection);
4112 // If there is the legacy showavailability data, store this for later use.
4113 // (This data is not present when restoring 'new' backups.)
4114 if (isset($data->showavailability)) {
4115 // Cache the showavailability flag using the backup_ids data field.
4116 restore_dbops::set_backup_ids_record($this->get_restoreid(),
4117 'module_showavailability', $newitemid, 0, null,
4118 (object)array('showavailability' => $data->showavailability));
4123 * Fetch all the existing because tag_set() deletes them
4124 * so everything must be reinserted on each call.
4126 * @param stdClass $data Record data
4128 protected function process_tag($data) {
4129 global $CFG;
4131 $data = (object)$data;
4133 if (core_tag_tag::is_enabled('core', 'course_modules')) {
4134 $modcontext = context::instance_by_id($this->task->get_contextid());
4135 $instanceid = $this->task->get_moduleid();
4137 core_tag_tag::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname);
4142 * Process the legacy availability table record. This table does not exist
4143 * in Moodle 2.7+ but we still support restore.
4145 * @param stdClass $data Record data
4147 protected function process_availability($data) {
4148 $data = (object)$data;
4149 // Simply going to store the whole availability record now, we'll process
4150 // all them later in the final task (once all activities have been restored)
4151 // Let's call the low level one to be able to store the whole object
4152 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
4153 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
4157 * Process the legacy availability fields table record. This table does not
4158 * exist in Moodle 2.7+ but we still support restore.
4160 * @param stdClass $data Record data
4162 protected function process_availability_field($data) {
4163 global $DB;
4164 $data = (object)$data;
4165 // Mark it is as passed by default
4166 $passed = true;
4167 $customfieldid = null;
4169 // If a customfield has been used in order to pass we must be able to match an existing
4170 // customfield by name (data->customfield) and type (data->customfieldtype)
4171 if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
4172 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
4173 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
4174 $passed = false;
4175 } else if (!empty($data->customfield)) {
4176 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
4177 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
4178 $passed = ($customfieldid !== false);
4181 if ($passed) {
4182 // Create the object to insert into the database
4183 $availfield = new stdClass();
4184 $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
4185 $availfield->userfield = $data->userfield;
4186 $availfield->customfieldid = $customfieldid;
4187 $availfield->operator = $data->operator;
4188 $availfield->value = $data->value;
4190 // Get showavailability option.
4191 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4192 'module_showavailability', $availfield->coursemoduleid);
4193 if (!$showrec) {
4194 // Should not happen.
4195 throw new coding_exception('No matching showavailability record');
4197 $show = $showrec->info->showavailability;
4199 // The $availfieldobject is now in the format used in the old
4200 // system. Interpret this and convert to new system.
4201 $currentvalue = $DB->get_field('course_modules', 'availability',
4202 array('id' => $availfield->coursemoduleid), MUST_EXIST);
4203 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
4204 $currentvalue, $availfield, $show);
4205 $DB->set_field('course_modules', 'availability', $newvalue,
4206 array('id' => $availfield->coursemoduleid));
4210 * This method will be executed after the rest of the restore has been processed.
4212 * Update old tag instance itemid(s).
4214 protected function after_restore() {
4215 global $DB;
4217 $contextid = $this->task->get_contextid();
4218 $instanceid = $this->task->get_activityid();
4219 $olditemid = $this->task->get_old_activityid();
4221 $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
4226 * Structure step that will process the user activity completion
4227 * information if all these conditions are met:
4228 * - Target site has completion enabled ($CFG->enablecompletion)
4229 * - Activity includes completion info (file_exists)
4231 class restore_userscompletion_structure_step extends restore_structure_step {
4233 * To conditionally decide if this step must be executed
4234 * Note the "settings" conditions are evaluated in the
4235 * corresponding task. Here we check for other conditions
4236 * not being restore settings (files, site settings...)
4238 protected function execute_condition() {
4239 global $CFG;
4241 // Completion disabled in this site, don't execute
4242 if (empty($CFG->enablecompletion)) {
4243 return false;
4246 // No completion on the front page.
4247 if ($this->get_courseid() == SITEID) {
4248 return false;
4251 // No user completion info found, don't execute
4252 $fullpath = $this->task->get_taskbasepath();
4253 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4254 if (!file_exists($fullpath)) {
4255 return false;
4258 // Arrived here, execute the step
4259 return true;
4262 protected function define_structure() {
4264 $paths = array();
4266 $paths[] = new restore_path_element('completion', '/completions/completion');
4268 return $paths;
4271 protected function process_completion($data) {
4272 global $DB;
4274 $data = (object)$data;
4276 $data->coursemoduleid = $this->task->get_moduleid();
4277 $data->userid = $this->get_mappingid('user', $data->userid);
4279 // Find the existing record
4280 $existing = $DB->get_record('course_modules_completion', array(
4281 'coursemoduleid' => $data->coursemoduleid,
4282 'userid' => $data->userid), 'id, timemodified');
4283 // Check we didn't already insert one for this cmid and userid
4284 // (there aren't supposed to be duplicates in that field, but
4285 // it was possible until MDL-28021 was fixed).
4286 if ($existing) {
4287 // Update it to these new values, but only if the time is newer
4288 if ($existing->timemodified < $data->timemodified) {
4289 $data->id = $existing->id;
4290 $DB->update_record('course_modules_completion', $data);
4292 } else {
4293 // Normal entry where it doesn't exist already
4294 $DB->insert_record('course_modules_completion', $data);
4300 * Abstract structure step, parent of all the activity structure steps. Used to support
4301 * the main <activity ...> tag and process it.
4303 abstract class restore_activity_structure_step extends restore_structure_step {
4306 * Adds support for the 'activity' path that is common to all the activities
4307 * and will be processed globally here
4309 protected function prepare_activity_structure($paths) {
4311 $paths[] = new restore_path_element('activity', '/activity');
4313 return $paths;
4317 * Process the activity path, informing the task about various ids, needed later
4319 protected function process_activity($data) {
4320 $data = (object)$data;
4321 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
4322 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
4323 $this->task->set_old_activityid($data->id); // Save old activityid in task
4327 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
4328 * and will adjust the new activity id (the instance) in various places
4330 protected function apply_activity_instance($newitemid) {
4331 global $DB;
4333 $this->task->set_activityid($newitemid); // Save activity id in task
4334 // Apply the id to course_sections->instanceid
4335 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
4336 // Do the mapping for modulename, preparing it for files by oldcontext
4337 $modulename = $this->task->get_modulename();
4338 $oldid = $this->task->get_old_activityid();
4339 $this->set_mapping($modulename, $oldid, $newitemid, true);
4344 * Structure step in charge of creating/mapping all the qcats and qs
4345 * by parsing the questions.xml file and checking it against the
4346 * results calculated by {@link restore_process_categories_and_questions}
4347 * and stored in backup_ids_temp
4349 class restore_create_categories_and_questions extends restore_structure_step {
4351 /** @var array $cachecategory store a question category */
4352 protected $cachedcategory = null;
4354 protected function define_structure() {
4356 $category = new restore_path_element('question_category', '/question_categories/question_category');
4357 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
4358 $hint = new restore_path_element('question_hint',
4359 '/question_categories/question_category/questions/question/question_hints/question_hint');
4361 $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag');
4363 // Apply for 'qtype' plugins optional paths at question level
4364 $this->add_plugin_structure('qtype', $question);
4366 // Apply for 'local' plugins optional paths at question level
4367 $this->add_plugin_structure('local', $question);
4369 return array($category, $question, $hint, $tag);
4372 protected function process_question_category($data) {
4373 global $DB;
4375 $data = (object)$data;
4376 $oldid = $data->id;
4378 // Check we have one mapping for this category
4379 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
4380 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
4383 // Check we have to create the category (newitemid = 0)
4384 if ($mapping->newitemid) {
4385 return; // newitemid != 0, this category is going to be mapped. Nothing to do
4388 // Arrived here, newitemid = 0, we need to create the category
4389 // we'll do it at parentitemid context, but for CONTEXT_MODULE
4390 // categories, that will be created at CONTEXT_COURSE and moved
4391 // to module context later when the activity is created
4392 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
4393 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
4395 $data->contextid = $mapping->parentitemid;
4397 // Before 3.1, the 'stamp' field could be erroneously duplicated.
4398 // From 3.1 onwards, there's a unique index of (contextid, stamp).
4399 // If we encounter a duplicate in an old restore file, just generate a new stamp.
4400 // This is the same as what happens during an upgrade to 3.1+ anyway.
4401 if ($DB->record_exists('question_categories', ['stamp' => $data->stamp, 'contextid' => $data->contextid])) {
4402 $data->stamp = make_unique_id_code();
4405 // Let's create the question_category and save mapping
4406 $newitemid = $DB->insert_record('question_categories', $data);
4407 $this->set_mapping('question_category', $oldid, $newitemid);
4408 // Also annotate them as question_category_created, we need
4409 // that later when remapping parents
4410 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
4413 protected function process_question($data) {
4414 global $DB;
4416 $data = (object)$data;
4417 $oldid = $data->id;
4419 // Check we have one mapping for this question
4420 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
4421 return; // No mapping = this question doesn't need to be created/mapped
4424 // Get the mapped category (cannot use get_new_parentid() because not
4425 // all the categories have been created, so it is not always available
4426 // Instead we get the mapping for the question->parentitemid because
4427 // we have loaded qcatids there for all parsed questions
4428 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
4430 // In the past, there were some very sloppy values of penalty. Fix them.
4431 if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
4432 $data->penalty = 0.3333333;
4434 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
4435 $data->penalty = 0.6666667;
4437 if ($data->penalty >= 1) {
4438 $data->penalty = 1;
4441 $userid = $this->get_mappingid('user', $data->createdby);
4442 $data->createdby = $userid ? $userid : $this->task->get_userid();
4444 $userid = $this->get_mappingid('user', $data->modifiedby);
4445 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
4447 // With newitemid = 0, let's create the question
4448 if (!$questionmapping->newitemid) {
4449 $newitemid = $DB->insert_record('question', $data);
4450 $this->set_mapping('question', $oldid, $newitemid);
4451 // Also annotate them as question_created, we need
4452 // that later when remapping parents (keeping the old categoryid as parentid)
4453 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
4454 } else {
4455 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4456 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
4457 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
4460 // Note, we don't restore any question files yet
4461 // as far as the CONTEXT_MODULE categories still
4462 // haven't their contexts to be restored to
4463 // The {@link restore_create_question_files}, executed in the final step
4464 // step will be in charge of restoring all the question files
4467 protected function process_question_hint($data) {
4468 global $DB;
4470 $data = (object)$data;
4471 $oldid = $data->id;
4473 // Detect if the question is created or mapped
4474 $oldquestionid = $this->get_old_parentid('question');
4475 $newquestionid = $this->get_new_parentid('question');
4476 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
4478 // If the question has been created by restore, we need to create its question_answers too
4479 if ($questioncreated) {
4480 // Adjust some columns
4481 $data->questionid = $newquestionid;
4482 // Insert record
4483 $newitemid = $DB->insert_record('question_hints', $data);
4485 // The question existed, we need to map the existing question_hints
4486 } else {
4487 // Look in question_hints by hint text matching
4488 $sql = 'SELECT id
4489 FROM {question_hints}
4490 WHERE questionid = ?
4491 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
4492 $params = array($newquestionid, $data->hint);
4493 $newitemid = $DB->get_field_sql($sql, $params);
4495 // Not able to find the hint, let's try cleaning the hint text
4496 // of all the question's hints in DB as slower fallback. MDL-33863.
4497 if (!$newitemid) {
4498 $potentialhints = $DB->get_records('question_hints',
4499 array('questionid' => $newquestionid), '', 'id, hint');
4500 foreach ($potentialhints as $potentialhint) {
4501 // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
4502 $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
4503 $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
4504 if ($cleanhint === $data->hint) {
4505 $newitemid = $data->id;
4510 // If we haven't found the newitemid, something has gone really wrong, question in DB
4511 // is missing hints, exception
4512 if (!$newitemid) {
4513 $info = new stdClass();
4514 $info->filequestionid = $oldquestionid;
4515 $info->dbquestionid = $newquestionid;
4516 $info->hint = $data->hint;
4517 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
4520 // Create mapping (I'm not sure if this is really needed?)
4521 $this->set_mapping('question_hint', $oldid, $newitemid);
4524 protected function process_tag($data) {
4525 global $CFG, $DB;
4527 $data = (object)$data;
4528 $newquestion = $this->get_new_parentid('question');
4529 $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
4530 if (!$questioncreated) {
4531 // This question already exists in the question bank. Nothing for us to do.
4532 return;
4535 if (core_tag_tag::is_enabled('core_question', 'question')) {
4536 $tagname = $data->rawname;
4537 // Get the category, so we can then later get the context.
4538 $categoryid = $this->get_new_parentid('question_category');
4539 if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
4540 $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
4542 // Add the tag to the question.
4543 core_tag_tag::add_item_tag('core_question', 'question', $newquestion,
4544 context::instance_by_id($this->cachedcategory->contextid),
4545 $tagname);
4549 protected function after_execute() {
4550 global $DB;
4552 // First of all, recode all the created question_categories->parent fields
4553 $qcats = $DB->get_records('backup_ids_temp', array(
4554 'backupid' => $this->get_restoreid(),
4555 'itemname' => 'question_category_created'));
4556 foreach ($qcats as $qcat) {
4557 $newparent = 0;
4558 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
4559 // Get new parent (mapped or created, so we look in quesiton_category mappings)
4560 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
4561 'backupid' => $this->get_restoreid(),
4562 'itemname' => 'question_category',
4563 'itemid' => $dbcat->parent))) {
4564 // contextids must match always, as far as we always include complete qbanks, just check it
4565 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
4566 if ($dbcat->contextid == $newparentctxid) {
4567 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
4568 } else {
4569 $newparent = 0; // No ctx match for both cats, no parent relationship
4572 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
4573 if (!$newparent) {
4574 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
4578 // Now, recode all the created question->parent fields
4579 $qs = $DB->get_records('backup_ids_temp', array(
4580 'backupid' => $this->get_restoreid(),
4581 'itemname' => 'question_created'));
4582 foreach ($qs as $q) {
4583 $newparent = 0;
4584 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
4585 // Get new parent (mapped or created, so we look in question mappings)
4586 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
4587 'backupid' => $this->get_restoreid(),
4588 'itemname' => 'question',
4589 'itemid' => $dbq->parent))) {
4590 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
4594 // Note, we don't restore any question files yet
4595 // as far as the CONTEXT_MODULE categories still
4596 // haven't their contexts to be restored to
4597 // The {@link restore_create_question_files}, executed in the final step
4598 // step will be in charge of restoring all the question files
4603 * Execution step that will move all the CONTEXT_MODULE question categories
4604 * created at early stages of restore in course context (because modules weren't
4605 * created yet) to their target module (matching by old-new-contextid mapping)
4607 class restore_move_module_questions_categories extends restore_execution_step {
4609 protected function define_execution() {
4610 global $DB;
4612 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
4613 foreach ($contexts as $contextid => $contextlevel) {
4614 // Only if context mapping exists (i.e. the module has been restored)
4615 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
4616 // Update all the qcats having their parentitemid set to the original contextid
4617 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
4618 FROM {backup_ids_temp}
4619 WHERE backupid = ?
4620 AND itemname = 'question_category'
4621 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
4622 foreach ($modulecats as $modulecat) {
4623 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
4624 // And set new contextid also in question_category mapping (will be
4625 // used by {@link restore_create_question_files} later
4626 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
4634 * Execution step that will create all the question/answers/qtype-specific files for the restored
4635 * questions. It must be executed after {@link restore_move_module_questions_categories}
4636 * because only then each question is in its final category and only then the
4637 * contexts can be determined.
4639 class restore_create_question_files extends restore_execution_step {
4641 /** @var array Question-type specific component items cache. */
4642 private $qtypecomponentscache = array();
4645 * Preform the restore_create_question_files step.
4647 protected function define_execution() {
4648 global $DB;
4650 // Track progress, as this task can take a long time.
4651 $progress = $this->task->get_progress();
4652 $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
4654 // Parentitemids of question_createds in backup_ids_temp are the category it is in.
4655 // MUST use a recordset, as there is no unique key in the first (or any) column.
4656 $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
4657 FROM {backup_ids_temp} bi
4658 JOIN {question} q ON q.id = bi.newitemid
4659 WHERE bi.backupid = ?
4660 AND bi.itemname = 'question_created'
4661 ORDER BY categoryid ASC", array($this->get_restoreid()));
4663 $currentcatid = -1;
4664 foreach ($catqtypes as $categoryid => $row) {
4665 $qtype = $row->qtype;
4667 // Check if we are in a new category.
4668 if ($currentcatid !== $categoryid) {
4669 // Report progress for each category.
4670 $progress->progress();
4672 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4673 'question_category', $categoryid)) {
4674 // Something went really wrong, cannot find the question_category for the question_created records.
4675 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
4676 continue;
4679 // Calculate source and target contexts.
4680 $oldctxid = $qcatmapping->info->contextid;
4681 $newctxid = $qcatmapping->parentitemid;
4683 $this->send_common_files($oldctxid, $newctxid, $progress);
4684 $currentcatid = $categoryid;
4687 $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
4689 $catqtypes->close();
4690 $progress->end_progress();
4694 * Send the common question files to a new context.
4696 * @param int $oldctxid Old context id.
4697 * @param int $newctxid New context id.
4698 * @param \core\progress $progress Progress object to use.
4700 private function send_common_files($oldctxid, $newctxid, $progress) {
4701 // Add common question files (question and question_answer ones).
4702 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
4703 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4704 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
4705 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4706 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
4707 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
4708 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
4709 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
4710 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
4711 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
4712 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
4713 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4714 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
4715 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4716 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
4717 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4721 * Send the question type specific files to a new context.
4723 * @param text $qtype The qtype name to send.
4724 * @param int $oldctxid Old context id.
4725 * @param int $newctxid New context id.
4726 * @param \core\progress $progress Progress object to use.
4728 private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
4729 if (!isset($this->qtypecomponentscache[$qtype])) {
4730 $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
4732 $components = $this->qtypecomponentscache[$qtype];
4733 foreach ($components as $component => $fileareas) {
4734 foreach ($fileareas as $filearea => $mapping) {
4735 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
4736 $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
4743 * Try to restore aliases and references to external files.
4745 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
4746 * We expect that all regular (non-alias) files have already been restored. Make sure
4747 * there is no restore step executed after this one that would call send_files_to_pool() again.
4749 * You may notice we have hardcoded support for Server files, Legacy course files
4750 * and user Private files here at the moment. This could be eventually replaced with a set of
4751 * callbacks in the future if needed.
4753 * @copyright 2012 David Mudrak <david@moodle.com>
4754 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4756 class restore_process_file_aliases_queue extends restore_execution_step {
4758 /** @var array internal cache for {@link choose_repository()} */
4759 private $cachereposbyid = array();
4761 /** @var array internal cache for {@link choose_repository()} */
4762 private $cachereposbytype = array();
4765 * What to do when this step is executed.
4767 protected function define_execution() {
4768 global $DB;
4770 $this->log('processing file aliases queue', backup::LOG_DEBUG);
4772 $fs = get_file_storage();
4774 // Load the queue.
4775 $rs = $DB->get_recordset('backup_ids_temp',
4776 array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'),
4777 '', 'info');
4779 // Iterate over aliases in the queue.
4780 foreach ($rs as $record) {
4781 $info = backup_controller_dbops::decode_backup_temp_info($record->info);
4783 // Try to pick a repository instance that should serve the alias.
4784 $repository = $this->choose_repository($info);
4786 if (is_null($repository)) {
4787 $this->notify_failure($info, 'unable to find a matching repository instance');
4788 continue;
4791 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
4792 // Aliases to Server files and Legacy course files may refer to a file
4793 // contained in the backup file or to some existing file (if we are on the
4794 // same site).
4795 try {
4796 $reference = file_storage::unpack_reference($info->oldfile->reference);
4797 } catch (Exception $e) {
4798 $this->notify_failure($info, 'invalid reference field format');
4799 continue;
4802 // Let's see if the referred source file was also included in the backup.
4803 $candidates = $DB->get_recordset('backup_files_temp', array(
4804 'backupid' => $this->get_restoreid(),
4805 'contextid' => $reference['contextid'],
4806 'component' => $reference['component'],
4807 'filearea' => $reference['filearea'],
4808 'itemid' => $reference['itemid'],
4809 ), '', 'info, newcontextid, newitemid');
4811 $source = null;
4813 foreach ($candidates as $candidate) {
4814 $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
4815 if ($candidateinfo->filename === $reference['filename']
4816 and $candidateinfo->filepath === $reference['filepath']
4817 and !is_null($candidate->newcontextid)
4818 and !is_null($candidate->newitemid) ) {
4819 $source = $candidateinfo;
4820 $source->contextid = $candidate->newcontextid;
4821 $source->itemid = $candidate->newitemid;
4822 break;
4825 $candidates->close();
4827 if ($source) {
4828 // We have an alias that refers to another file also included in
4829 // the backup. Let us change the reference field so that it refers
4830 // to the restored copy of the original file.
4831 $reference = file_storage::pack_reference($source);
4833 // Send the new alias to the filepool.
4834 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4835 $this->notify_success($info);
4836 continue;
4838 } else {
4839 // This is a reference to some moodle file that was not contained in the backup
4840 // file. If we are restoring to the same site, keep the reference untouched
4841 // and restore the alias as is if the referenced file exists.
4842 if ($this->task->is_samesite()) {
4843 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
4844 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
4845 $reference = file_storage::pack_reference($reference);
4846 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4847 $this->notify_success($info);
4848 continue;
4849 } else {
4850 $this->notify_failure($info, 'referenced file not found');
4851 continue;
4854 // If we are at other site, we can't restore this alias.
4855 } else {
4856 $this->notify_failure($info, 'referenced file not included');
4857 continue;
4861 } else if ($info->oldfile->repositorytype === 'user') {
4862 if ($this->task->is_samesite()) {
4863 // For aliases to user Private files at the same site, we have a chance to check
4864 // if the referenced file still exists.
4865 try {
4866 $reference = file_storage::unpack_reference($info->oldfile->reference);
4867 } catch (Exception $e) {
4868 $this->notify_failure($info, 'invalid reference field format');
4869 continue;
4871 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
4872 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
4873 $reference = file_storage::pack_reference($reference);
4874 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4875 $this->notify_success($info);
4876 continue;
4877 } else {
4878 $this->notify_failure($info, 'referenced file not found');
4879 continue;
4882 // If we are at other site, we can't restore this alias.
4883 } else {
4884 $this->notify_failure($info, 'restoring at another site');
4885 continue;
4888 } else {
4889 // This is a reference to some external file such as in boxnet or dropbox.
4890 // If we are restoring to the same site, keep the reference untouched and
4891 // restore the alias as is.
4892 if ($this->task->is_samesite()) {
4893 $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
4894 $this->notify_success($info);
4895 continue;
4897 // If we are at other site, we can't restore this alias.
4898 } else {
4899 $this->notify_failure($info, 'restoring at another site');
4900 continue;
4904 $rs->close();
4908 * Choose the repository instance that should handle the alias.
4910 * At the same site, we can rely on repository instance id and we just
4911 * check it still exists. On other site, try to find matching Server files or
4912 * Legacy course files repository instance. Return null if no matching
4913 * repository instance can be found.
4915 * @param stdClass $info
4916 * @return repository|null
4918 private function choose_repository(stdClass $info) {
4919 global $DB, $CFG;
4920 require_once($CFG->dirroot.'/repository/lib.php');
4922 if ($this->task->is_samesite()) {
4923 // We can rely on repository instance id.
4925 if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
4926 return $this->cachereposbyid[$info->oldfile->repositoryid];
4929 $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
4931 try {
4932 $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
4933 return $this->cachereposbyid[$info->oldfile->repositoryid];
4934 } catch (Exception $e) {
4935 $this->cachereposbyid[$info->oldfile->repositoryid] = null;
4936 return null;
4939 } else {
4940 // We can rely on repository type only.
4942 if (empty($info->oldfile->repositorytype)) {
4943 return null;
4946 if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
4947 return $this->cachereposbytype[$info->oldfile->repositorytype];
4950 $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
4952 // Both Server files and Legacy course files repositories have a single
4953 // instance at the system context to use. Let us try to find it.
4954 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
4955 $sql = "SELECT ri.id
4956 FROM {repository} r
4957 JOIN {repository_instances} ri ON ri.typeid = r.id
4958 WHERE r.type = ? AND ri.contextid = ?";
4959 $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
4960 if (empty($ris)) {
4961 return null;
4963 $repoids = array_keys($ris);
4964 $repoid = reset($repoids);
4965 try {
4966 $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
4967 return $this->cachereposbytype[$info->oldfile->repositorytype];
4968 } catch (Exception $e) {
4969 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
4970 return null;
4974 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
4975 return null;
4980 * Let the user know that the given alias was successfully restored
4982 * @param stdClass $info
4984 private function notify_success(stdClass $info) {
4985 $filedesc = $this->describe_alias($info);
4986 $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
4990 * Let the user know that the given alias can't be restored
4992 * @param stdClass $info
4993 * @param string $reason detailed reason to be logged
4995 private function notify_failure(stdClass $info, $reason = '') {
4996 $filedesc = $this->describe_alias($info);
4997 if ($reason) {
4998 $reason = ' ('.$reason.')';
5000 $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
5001 $this->add_result_item('file_aliases_restore_failures', $filedesc);
5005 * Return a human readable description of the alias file
5007 * @param stdClass $info
5008 * @return string
5010 private function describe_alias(stdClass $info) {
5012 $filedesc = $this->expected_alias_location($info->newfile);
5014 if (!is_null($info->oldfile->source)) {
5015 $filedesc .= ' ('.$info->oldfile->source.')';
5018 return $filedesc;
5022 * Return the expected location of a file
5024 * Please note this may and may not work as a part of URL to pluginfile.php
5025 * (depends on how the given component/filearea deals with the itemid).
5027 * @param stdClass $filerecord
5028 * @return string
5030 private function expected_alias_location($filerecord) {
5032 $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
5033 if (!is_null($filerecord->itemid)) {
5034 $filedesc .= '/'.$filerecord->itemid;
5036 $filedesc .= $filerecord->filepath.$filerecord->filename;
5038 return $filedesc;
5042 * Append a value to the given resultset
5044 * @param string $name name of the result containing a list of values
5045 * @param mixed $value value to add as another item in that result
5047 private function add_result_item($name, $value) {
5049 $results = $this->task->get_results();
5051 if (isset($results[$name])) {
5052 if (!is_array($results[$name])) {
5053 throw new coding_exception('Unable to append a result item into a non-array structure.');
5055 $current = $results[$name];
5056 $current[] = $value;
5057 $this->task->add_result(array($name => $current));
5059 } else {
5060 $this->task->add_result(array($name => array($value)));
5067 * Abstract structure step, to be used by all the activities using core questions stuff
5068 * (like the quiz module), to support qtype plugins, states and sessions
5070 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
5071 /** @var array question_attempt->id to qtype. */
5072 protected $qtypes = array();
5073 /** @var array question_attempt->id to questionid. */
5074 protected $newquestionids = array();
5077 * Attach below $element (usually attempts) the needed restore_path_elements
5078 * to restore question_usages and all they contain.
5080 * If you use the $nameprefix parameter, then you will need to implement some
5081 * extra methods in your class, like
5083 * protected function process_{nameprefix}question_attempt($data) {
5084 * $this->restore_question_usage_worker($data, '{nameprefix}');
5086 * protected function process_{nameprefix}question_attempt($data) {
5087 * $this->restore_question_attempt_worker($data, '{nameprefix}');
5089 * protected function process_{nameprefix}question_attempt_step($data) {
5090 * $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5093 * @param restore_path_element $element the parent element that the usages are stored inside.
5094 * @param array $paths the paths array that is being built.
5095 * @param string $nameprefix should match the prefix passed to the corresponding
5096 * backup_questions_activity_structure_step::add_question_usages call.
5098 protected function add_question_usages($element, &$paths, $nameprefix = '') {
5099 // Check $element is restore_path_element
5100 if (! $element instanceof restore_path_element) {
5101 throw new restore_step_exception('element_must_be_restore_path_element', $element);
5104 // Check $paths is one array
5105 if (!is_array($paths)) {
5106 throw new restore_step_exception('paths_must_be_array', $paths);
5108 $paths[] = new restore_path_element($nameprefix . 'question_usage',
5109 $element->get_path() . "/{$nameprefix}question_usage");
5110 $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5111 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5112 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5113 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5114 true);
5115 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5116 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5120 * Process question_usages
5122 protected function process_question_usage($data) {
5123 $this->restore_question_usage_worker($data, '');
5127 * Process question_attempts
5129 protected function process_question_attempt($data) {
5130 $this->restore_question_attempt_worker($data, '');
5134 * Process question_attempt_steps
5136 protected function process_question_attempt_step($data) {
5137 $this->restore_question_attempt_step_worker($data, '');
5141 * This method does the acutal work for process_question_usage or
5142 * process_{nameprefix}_question_usage.
5143 * @param array $data the data from the XML file.
5144 * @param string $nameprefix the element name prefix.
5146 protected function restore_question_usage_worker($data, $nameprefix) {
5147 global $DB;
5149 // Clear our caches.
5150 $this->qtypes = array();
5151 $this->newquestionids = array();
5153 $data = (object)$data;
5154 $oldid = $data->id;
5156 $oldcontextid = $this->get_task()->get_old_contextid();
5157 $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
5159 // Everything ready, insert (no mapping needed)
5160 $newitemid = $DB->insert_record('question_usages', $data);
5162 $this->inform_new_usage_id($newitemid);
5164 $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
5168 * When process_question_usage creates the new usage, it calls this method
5169 * to let the activity link to the new usage. For example, the quiz uses
5170 * this method to set quiz_attempts.uniqueid to the new usage id.
5171 * @param integer $newusageid
5173 abstract protected function inform_new_usage_id($newusageid);
5176 * This method does the acutal work for process_question_attempt or
5177 * process_{nameprefix}_question_attempt.
5178 * @param array $data the data from the XML file.
5179 * @param string $nameprefix the element name prefix.
5181 protected function restore_question_attempt_worker($data, $nameprefix) {
5182 global $DB;
5184 $data = (object)$data;
5185 $oldid = $data->id;
5186 $question = $this->get_mapping('question', $data->questionid);
5188 $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
5189 $data->questionid = $question->newitemid;
5190 if (!property_exists($data, 'variant')) {
5191 $data->variant = 1;
5194 if (!property_exists($data, 'maxfraction')) {
5195 $data->maxfraction = 1;
5198 $newitemid = $DB->insert_record('question_attempts', $data);
5200 $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
5201 $this->qtypes[$newitemid] = $question->info->qtype;
5202 $this->newquestionids[$newitemid] = $data->questionid;
5206 * This method does the acutal work for process_question_attempt_step or
5207 * process_{nameprefix}_question_attempt_step.
5208 * @param array $data the data from the XML file.
5209 * @param string $nameprefix the element name prefix.
5211 protected function restore_question_attempt_step_worker($data, $nameprefix) {
5212 global $DB;
5214 $data = (object)$data;
5215 $oldid = $data->id;
5217 // Pull out the response data.
5218 $response = array();
5219 if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
5220 foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
5221 $response[$variable['name']] = $variable['value'];
5224 unset($data->response);
5226 $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
5227 $data->userid = $this->get_mappingid('user', $data->userid);
5229 // Everything ready, insert and create mapping (needed by question_sessions)
5230 $newitemid = $DB->insert_record('question_attempt_steps', $data);
5231 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
5233 // Now process the response data.
5234 $response = $this->questions_recode_response_data(
5235 $this->qtypes[$data->questionattemptid],
5236 $this->newquestionids[$data->questionattemptid],
5237 $data->sequencenumber, $response);
5239 foreach ($response as $name => $value) {
5240 $row = new stdClass();
5241 $row->attemptstepid = $newitemid;
5242 $row->name = $name;
5243 $row->value = $value;
5244 $DB->insert_record('question_attempt_step_data', $row, false);
5249 * Recode the respones data for a particular step of an attempt at at particular question.
5250 * @param string $qtype the question type.
5251 * @param int $newquestionid the question id.
5252 * @param int $sequencenumber the sequence number.
5253 * @param array $response the response data to recode.
5255 public function questions_recode_response_data(
5256 $qtype, $newquestionid, $sequencenumber, array $response) {
5257 $qtyperestorer = $this->get_qtype_restorer($qtype);
5258 if ($qtyperestorer) {
5259 $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
5261 return $response;
5265 * Given a list of question->ids, separated by commas, returns the
5266 * recoded list, with all the restore question mappings applied.
5267 * Note: Used by quiz->questions and quiz_attempts->layout
5268 * Note: 0 = page break (unconverted)
5270 protected function questions_recode_layout($layout) {
5271 // Extracts question id from sequence
5272 if ($questionids = explode(',', $layout)) {
5273 foreach ($questionids as $id => $questionid) {
5274 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
5275 $newquestionid = $this->get_mappingid('question', $questionid);
5276 $questionids[$id] = $newquestionid;
5280 return implode(',', $questionids);
5284 * Get the restore_qtype_plugin subclass for a specific question type.
5285 * @param string $qtype e.g. multichoice.
5286 * @return restore_qtype_plugin instance.
5288 protected function get_qtype_restorer($qtype) {
5289 // Build one static cache to store {@link restore_qtype_plugin}
5290 // while we are needing them, just to save zillions of instantiations
5291 // or using static stuff that will break our nice API
5292 static $qtypeplugins = array();
5294 if (!isset($qtypeplugins[$qtype])) {
5295 $classname = 'restore_qtype_' . $qtype . '_plugin';
5296 if (class_exists($classname)) {
5297 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
5298 } else {
5299 $qtypeplugins[$qtype] = null;
5302 return $qtypeplugins[$qtype];
5305 protected function after_execute() {
5306 parent::after_execute();
5308 // Restore any files belonging to responses.
5309 foreach (question_engine::get_all_response_file_areas() as $filearea) {
5310 $this->add_related_files('question', $filearea, 'question_attempt_step');
5315 * Attach below $element (usually attempts) the needed restore_path_elements
5316 * to restore question attempt data from Moodle 2.0.
5318 * When using this method, the parent element ($element) must be defined with
5319 * $grouped = true. Then, in that elements process method, you must call
5320 * {@link process_legacy_attempt_data()} with the groupded data. See, for
5321 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
5322 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
5323 * @param array $paths the paths array that is being built to describe the
5324 * structure.
5326 protected function add_legacy_question_attempt_data($element, &$paths) {
5327 global $CFG;
5328 require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
5330 // Check $element is restore_path_element
5331 if (!($element instanceof restore_path_element)) {
5332 throw new restore_step_exception('element_must_be_restore_path_element', $element);
5334 // Check $paths is one array
5335 if (!is_array($paths)) {
5336 throw new restore_step_exception('paths_must_be_array', $paths);
5339 $paths[] = new restore_path_element('question_state',
5340 $element->get_path() . '/states/state');
5341 $paths[] = new restore_path_element('question_session',
5342 $element->get_path() . '/sessions/session');
5345 protected function get_attempt_upgrader() {
5346 if (empty($this->attemptupgrader)) {
5347 $this->attemptupgrader = new question_engine_attempt_upgrader();
5348 $this->attemptupgrader->prepare_to_restore();
5350 return $this->attemptupgrader;
5354 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
5355 * @param object $data contains all the grouped attempt data to process.
5356 * @param pbject $quiz data about the activity the attempts belong to. Required
5357 * fields are (basically this only works for the quiz module):
5358 * oldquestions => list of question ids in this activity - using old ids.
5359 * preferredbehaviour => the behaviour to use for questionattempts.
5361 protected function process_legacy_quiz_attempt_data($data, $quiz) {
5362 global $DB;
5363 $upgrader = $this->get_attempt_upgrader();
5365 $data = (object)$data;
5367 $layout = explode(',', $data->layout);
5368 $newlayout = $layout;
5370 // Convert each old question_session into a question_attempt.
5371 $qas = array();
5372 foreach (explode(',', $quiz->oldquestions) as $questionid) {
5373 if ($questionid == 0) {
5374 continue;
5377 $newquestionid = $this->get_mappingid('question', $questionid);
5378 if (!$newquestionid) {
5379 throw new restore_step_exception('questionattemptreferstomissingquestion',
5380 $questionid, $questionid);
5383 $question = $upgrader->load_question($newquestionid, $quiz->id);
5385 foreach ($layout as $key => $qid) {
5386 if ($qid == $questionid) {
5387 $newlayout[$key] = $newquestionid;
5391 list($qsession, $qstates) = $this->find_question_session_and_states(
5392 $data, $questionid);
5394 if (empty($qsession) || empty($qstates)) {
5395 throw new restore_step_exception('questionattemptdatamissing',
5396 $questionid, $questionid);
5399 list($qsession, $qstates) = $this->recode_legacy_response_data(
5400 $question, $qsession, $qstates);
5402 $data->layout = implode(',', $newlayout);
5403 $qas[$newquestionid] = $upgrader->convert_question_attempt(
5404 $quiz, $data, $question, $qsession, $qstates);
5407 // Now create a new question_usage.
5408 $usage = new stdClass();
5409 $usage->component = 'mod_quiz';
5410 $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
5411 $usage->preferredbehaviour = $quiz->preferredbehaviour;
5412 $usage->id = $DB->insert_record('question_usages', $usage);
5414 $this->inform_new_usage_id($usage->id);
5416 $data->uniqueid = $usage->id;
5417 $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
5418 $this->questions_recode_layout($quiz->oldquestions));
5421 protected function find_question_session_and_states($data, $questionid) {
5422 $qsession = null;
5423 foreach ($data->sessions['session'] as $session) {
5424 if ($session['questionid'] == $questionid) {
5425 $qsession = (object) $session;
5426 break;
5430 $qstates = array();
5431 foreach ($data->states['state'] as $state) {
5432 if ($state['question'] == $questionid) {
5433 // It would be natural to use $state['seq_number'] as the array-key
5434 // here, but it seems that buggy behaviour in 2.0 and early can
5435 // mean that that is not unique, so we use id, which is guaranteed
5436 // to be unique.
5437 $qstates[$state['id']] = (object) $state;
5440 ksort($qstates);
5441 $qstates = array_values($qstates);
5443 return array($qsession, $qstates);
5447 * Recode any ids in the response data
5448 * @param object $question the question data
5449 * @param object $qsession the question sessions.
5450 * @param array $qstates the question states.
5452 protected function recode_legacy_response_data($question, $qsession, $qstates) {
5453 $qsession->questionid = $question->id;
5455 foreach ($qstates as &$state) {
5456 $state->question = $question->id;
5457 $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
5460 return array($qsession, $qstates);
5464 * Recode the legacy answer field.
5465 * @param object $state the state to recode the answer of.
5466 * @param string $qtype the question type.
5468 public function restore_recode_legacy_answer($state, $qtype) {
5469 $restorer = $this->get_qtype_restorer($qtype);
5470 if ($restorer) {
5471 return $restorer->recode_legacy_state_answer($state);
5472 } else {
5473 return $state->answer;
5479 * Restore completion defaults for each module type
5481 * @package core_backup
5482 * @copyright 2017 Marina Glancy
5483 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5485 class restore_completion_defaults_structure_step extends restore_structure_step {
5487 * To conditionally decide if this step must be executed.
5489 protected function execute_condition() {
5490 // No completion on the front page.
5491 if ($this->get_courseid() == SITEID) {
5492 return false;
5495 // No default completion info found, don't execute.
5496 $fullpath = $this->task->get_taskbasepath();
5497 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
5498 if (!file_exists($fullpath)) {
5499 return false;
5502 // Arrived here, execute the step.
5503 return true;
5507 * Function that will return the structure to be processed by this restore_step.
5509 * @return restore_path_element[]
5511 protected function define_structure() {
5512 return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
5516 * Processor for path element 'completion_defaults'
5518 * @param stdClass|array $data
5520 protected function process_completion_defaults($data) {
5521 global $DB;
5523 $data = (array)$data;
5524 $oldid = $data['id'];
5525 unset($data['id']);
5527 // Find the module by name since id may be different in another site.
5528 if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
5529 return;
5531 unset($data['modulename']);
5533 // Find the existing record.
5534 $newid = $DB->get_field('course_completion_defaults', 'id',
5535 ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
5536 if (!$newid) {
5537 $newid = $DB->insert_record('course_completion_defaults',
5538 ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
5539 } else {
5540 $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
5543 // Save id mapping for restoring associated events.
5544 $this->set_mapping('course_completion_defaults', $oldid, $newid);
5549 * Index course after restore.
5551 * @package core_backup
5552 * @copyright 2017 The Open University
5553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5555 class restore_course_search_index extends restore_execution_step {
5557 * When this step is executed, we add the course context to the queue for reindexing.
5559 protected function define_execution() {
5560 $context = \context_course::instance($this->task->get_courseid());
5561 \core_search\manager::request_index($context);
5566 * Index activity after restore (when not restoring whole course).
5568 * @package core_backup
5569 * @copyright 2017 The Open University
5570 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5572 class restore_activity_search_index extends restore_execution_step {
5574 * When this step is executed, we add the activity context to the queue for reindexing.
5576 protected function define_execution() {
5577 $context = \context::instance_by_id($this->task->get_contextid());
5578 \core_search\manager::request_index($context);
5583 * Index block after restore (when not restoring whole course).
5585 * @package core_backup
5586 * @copyright 2017 The Open University
5587 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5589 class restore_block_search_index extends restore_execution_step {
5591 * When this step is executed, we add the block context to the queue for reindexing.
5593 protected function define_execution() {
5594 // A block in the restore list may be skipped because a duplicate is detected.
5595 // In this case, there is no new blockid (or context) to get.
5596 if (!empty($this->task->get_blockid())) {
5597 $context = \context_block::instance($this->task->get_blockid());
5598 \core_search\manager::request_index($context);
5604 * Restore action events.
5606 * @package core_backup
5607 * @copyright 2017 onwards Ankit Agarwal
5608 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5610 class restore_calendar_action_events extends restore_execution_step {
5612 * What to do when this step is executed.
5614 protected function define_execution() {
5615 // We just queue the task here rather trying to recreate everything manually.
5616 // The task will automatically populate all data.
5617 $task = new \core\task\refresh_mod_calendar_events_task();
5618 $task->set_custom_data(array('courseid' => $this->get_courseid()));
5619 \core\task\manager::queue_adhoc_task($task, true);