MDL-58439 admin: Ignore guest logins for all admin pages
[moodle.git] / backup / moodle2 / restore_stepslib.php
blob683e90225bee5e520e45a6080d0706881459712d
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 // Ensure the module cache is current when recalculating grades.
489 rebuild_course_cache($this->get_courseid(), true);
491 // Restore marks items as needing update. Update everything now.
492 grade_regrade_final_grades($this->get_courseid());
496 * Freeze gradebook calculation if needed.
498 * This is similar to various upgrade scripts that check if the freeze is needed.
500 protected function gradebook_calculation_freeze() {
501 global $CFG;
502 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
503 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
504 $backupbuild = (int)$matches[1];
505 // The function floatval will return a float even if there is text mixed with the release number.
506 $backuprelease = floatval($this->get_task()->get_info()->backup_release);
508 // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
509 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) {
510 require_once($CFG->libdir . '/db/upgradelib.php');
511 upgrade_extra_credit_weightoverride($this->get_courseid());
513 // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
514 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) {
515 require_once($CFG->libdir . '/db/upgradelib.php');
516 upgrade_calculated_grade_items($this->get_courseid());
518 // Courses from before 3.1 (20160518) may have a letter boundary problem and should be checked for this issue.
519 // Backups from before and including 2.9 could have a build number that is greater than 20160518 and should
520 // be checked for this problem.
521 if (!$gradebookcalculationsfreeze && ($backupbuild < 20160518 || $backuprelease <= 2.9)) {
522 require_once($CFG->libdir . '/db/upgradelib.php');
523 upgrade_course_letter_boundary($this->get_courseid());
529 * Checks what should happen with the course grade setting minmaxtouse.
531 * This is related to the upgrade step at the time the setting was added.
533 * @see MDL-48618
534 * @return void
536 protected function check_minmaxtouse() {
537 global $CFG, $DB;
538 require_once($CFG->libdir . '/gradelib.php');
540 $userinfo = $this->task->get_setting_value('users');
541 $settingname = 'minmaxtouse';
542 $courseid = $this->get_courseid();
543 $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
544 $version28start = 2014111000.00;
545 $version28last = 2014111006.05;
546 $version29start = 2015051100.00;
547 $version29last = 2015060400.02;
549 $target = $this->get_task()->get_target();
550 if ($minmaxtouse === false &&
551 ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
552 // The setting was not found because this setting did not exist at the time the backup was made.
553 // And we are not restoring as merge, in which case we leave the course as it was.
554 $version = $this->get_task()->get_info()->moodle_version;
556 if ($version < $version28start) {
557 // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
558 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
559 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
562 } else if (($version >= $version28start && $version < $version28last) ||
563 ($version >= $version29start && $version < $version29last)) {
564 // They should be using grade_grade when the course has inconsistencies.
566 $sql = "SELECT gi.id
567 FROM {grade_items} gi
568 JOIN {grade_grades} gg
569 ON gg.itemid = gi.id
570 WHERE gi.courseid = ?
571 AND (gi.itemtype != ? AND gi.itemtype != ?)
572 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
574 // The course can only have inconsistencies when we restore the user info,
575 // we do not need to act on existing grades that were not restored as part of this backup.
576 if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
578 // Display the notice as we do during upgrade.
579 set_config('show_min_max_grades_changed_' . $courseid, 1);
581 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
582 // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
583 // If they are using the site-wide grade_grade setting, we only want to notice them.
584 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
588 } else {
589 // This should never happen because from now on minmaxtouse is always saved in backups.
595 * Rewrite step definition to handle the legacy freeze attribute.
597 * In previous backups the calculations_freeze property was stored as an attribute of the
598 * top level node <gradebook>. The backup API, however, do not process grandparent nodes.
599 * It only processes definitive children, and their parent attributes.
601 * We had:
603 * <gradebook calculations_freeze="20160511">
604 * <grade_categories>
605 * <grade_category id="10">
606 * <depth>1</depth>
607 * ...
608 * </grade_category>
609 * </grade_categories>
610 * ...
611 * </gradebook>
613 * And this method will convert it to:
615 * <gradebook >
616 * <attributes>
617 * <calculations_freeze>20160511</calculations_freeze>
618 * </attributes>
619 * <grade_categories>
620 * <grade_category id="10">
621 * <depth>1</depth>
622 * ...
623 * </grade_category>
624 * </grade_categories>
625 * ...
626 * </gradebook>
628 * Note that we cannot just load the XML file in memory as it could potentially be huge.
629 * We can also completely ignore if the node <attributes> is already in the backup
630 * file as it never existed before.
632 * @param string $filepath The absolute path to the XML file.
633 * @return void
635 protected function rewrite_step_backup_file_for_legacy_freeze($filepath) {
636 $foundnode = false;
637 $newfile = make_request_directory(true) . DIRECTORY_SEPARATOR . 'file.xml';
638 $fr = fopen($filepath, 'r');
639 $fw = fopen($newfile, 'w');
640 if ($fr && $fw) {
641 while (($line = fgets($fr, 4096)) !== false) {
642 if (!$foundnode && strpos($line, '<gradebook ') === 0) {
643 $foundnode = true;
644 $matches = array();
645 $pattern = '@calculations_freeze=.([0-9]+).@';
646 if (preg_match($pattern, $line, $matches)) {
647 $freeze = $matches[1];
648 $line = preg_replace($pattern, '', $line);
649 $line .= " <attributes>\n <calculations_freeze>$freeze</calculations_freeze>\n </attributes>\n";
652 fputs($fw, $line);
654 if (!feof($fr)) {
655 throw new restore_step_exception('Error while attempting to rewrite the gradebook step file.');
657 fclose($fr);
658 fclose($fw);
659 if (!rename($newfile, $filepath)) {
660 throw new restore_step_exception('Error while attempting to rename the gradebook step file.');
662 } else {
663 if ($fr) {
664 fclose($fr);
666 if ($fw) {
667 fclose($fw);
675 * Step in charge of restoring the grade history of a course.
677 * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
678 * we do not want to restore the history if the gradebook and its content has not been
679 * restored. At least for now.
681 class restore_grade_history_structure_step extends restore_structure_step {
683 protected function execute_condition() {
684 global $CFG, $DB;
686 if ($this->get_courseid() == SITEID) {
687 return false;
690 // No gradebook info found, don't execute.
691 $fullpath = $this->task->get_taskbasepath();
692 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
693 if (!file_exists($fullpath)) {
694 return false;
697 // Some module present in backup file isn't available to restore in this site, don't execute.
698 if ($this->task->is_missing_modules()) {
699 return false;
702 // Some activity has been excluded to be restored, don't execute.
703 if ($this->task->is_excluding_activities()) {
704 return false;
707 // There should only be one grade category (the 1 associated with the course itself).
708 $category = new stdclass();
709 $category->courseid = $this->get_courseid();
710 $catcount = $DB->count_records('grade_categories', (array)$category);
711 if ($catcount > 1) {
712 return false;
715 // Arrived here, execute the step.
716 return true;
719 protected function define_structure() {
720 $paths = array();
722 // Settings to use.
723 $userinfo = $this->get_setting_value('users');
724 $history = $this->get_setting_value('grade_histories');
726 if ($userinfo && $history) {
727 $paths[] = new restore_path_element('grade_grade',
728 '/grade_history/grade_grades/grade_grade');
731 return $paths;
734 protected function process_grade_grade($data) {
735 global $DB;
737 $data = (object)($data);
738 $olduserid = $data->userid;
739 unset($data->id);
741 $data->userid = $this->get_mappingid('user', $data->userid, null);
742 if (!empty($data->userid)) {
743 // Do not apply the date offsets as this is history.
744 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
745 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
746 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
747 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
748 $DB->insert_record('grade_grades_history', $data);
749 } else {
750 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
751 $this->log($message, backup::LOG_DEBUG);
758 * decode all the interlinks present in restored content
759 * relying 100% in the restore_decode_processor that handles
760 * both the contents to modify and the rules to be applied
762 class restore_decode_interlinks extends restore_execution_step {
764 protected function define_execution() {
765 // Get the decoder (from the plan)
766 $decoder = $this->task->get_decoder();
767 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
768 // And launch it, everything will be processed
769 $decoder->execute();
774 * first, ensure that we have no gaps in section numbers
775 * and then, rebuid the course cache
777 class restore_rebuild_course_cache extends restore_execution_step {
779 protected function define_execution() {
780 global $DB;
782 // Although there is some sort of auto-recovery of missing sections
783 // present in course/formats... here we check that all the sections
784 // from 0 to MAX(section->section) exist, creating them if necessary
785 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
786 // Iterate over all sections
787 for ($i = 0; $i <= $maxsection; $i++) {
788 // If the section $i doesn't exist, create it
789 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
790 $sectionrec = array(
791 'course' => $this->get_courseid(),
792 'section' => $i,
793 'timemodified' => time());
794 $DB->insert_record('course_sections', $sectionrec); // missing section created
798 // Rebuild cache now that all sections are in place
799 rebuild_course_cache($this->get_courseid());
800 cache_helper::purge_by_event('changesincourse');
801 cache_helper::purge_by_event('changesincoursecat');
806 * Review all the tasks having one after_restore method
807 * executing it to perform some final adjustments of information
808 * not available when the task was executed.
810 class restore_execute_after_restore extends restore_execution_step {
812 protected function define_execution() {
814 // Simply call to the execute_after_restore() method of the task
815 // that always is the restore_final_task
816 $this->task->launch_execute_after_restore();
822 * Review all the (pending) block positions in backup_ids, matching by
823 * contextid, creating positions as needed. This is executed by the
824 * final task, once all the contexts have been created
826 class restore_review_pending_block_positions extends restore_execution_step {
828 protected function define_execution() {
829 global $DB;
831 // Get all the block_position objects pending to match
832 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
833 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
834 // Process block positions, creating them or accumulating for final step
835 foreach($rs as $posrec) {
836 // Get the complete position object out of the info field.
837 $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
838 // If position is for one already mapped (known) contextid
839 // process it now, creating the position, else nothing to
840 // do, position finally discarded
841 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
842 $position->contextid = $newctx->newitemid;
843 // Create the block position
844 $DB->insert_record('block_positions', $position);
847 $rs->close();
853 * Updates the availability data for course modules and sections.
855 * Runs after the restore of all course modules, sections, and grade items has
856 * completed. This is necessary in order to update IDs that have changed during
857 * restore.
859 * @package core_backup
860 * @copyright 2014 The Open University
861 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
863 class restore_update_availability extends restore_execution_step {
865 protected function define_execution() {
866 global $CFG, $DB;
868 // Note: This code runs even if availability is disabled when restoring.
869 // That will ensure that if you later turn availability on for the site,
870 // there will be no incorrect IDs. (It doesn't take long if the restored
871 // data does not contain any availability information.)
873 // Get modinfo with all data after resetting cache.
874 rebuild_course_cache($this->get_courseid(), true);
875 $modinfo = get_fast_modinfo($this->get_courseid());
877 // Get the date offset for this restore.
878 $dateoffset = $this->apply_date_offset(1) - 1;
880 // Update all sections that were restored.
881 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
882 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
883 $sectionsbyid = null;
884 foreach ($rs as $rec) {
885 if (is_null($sectionsbyid)) {
886 $sectionsbyid = array();
887 foreach ($modinfo->get_section_info_all() as $section) {
888 $sectionsbyid[$section->id] = $section;
891 if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
892 // If the section was not fully restored for some reason
893 // (e.g. due to an earlier error), skip it.
894 $this->get_logger()->process('Section not fully restored: id ' .
895 $rec->newitemid, backup::LOG_WARNING);
896 continue;
898 $section = $sectionsbyid[$rec->newitemid];
899 if (!is_null($section->availability)) {
900 $info = new \core_availability\info_section($section);
901 $info->update_after_restore($this->get_restoreid(),
902 $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
905 $rs->close();
907 // Update all modules that were restored.
908 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
909 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
910 foreach ($rs as $rec) {
911 if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
912 // If the module was not fully restored for some reason
913 // (e.g. due to an earlier error), skip it.
914 $this->get_logger()->process('Module not fully restored: id ' .
915 $rec->newitemid, backup::LOG_WARNING);
916 continue;
918 $cm = $modinfo->get_cm($rec->newitemid);
919 if (!is_null($cm->availability)) {
920 $info = new \core_availability\info_module($cm);
921 $info->update_after_restore($this->get_restoreid(),
922 $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
925 $rs->close();
931 * Process legacy module availability records in backup_ids.
933 * Matches course modules and grade item id once all them have been already restored.
934 * Only if all matchings are satisfied the availability condition will be created.
935 * At the same time, it is required for the site to have that functionality enabled.
937 * This step is included only to handle legacy backups (2.6 and before). It does not
938 * do anything for newer backups.
940 * @copyright 2014 The Open University
941 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
943 class restore_process_course_modules_availability extends restore_execution_step {
945 protected function define_execution() {
946 global $CFG, $DB;
948 // Site hasn't availability enabled
949 if (empty($CFG->enableavailability)) {
950 return;
953 // Do both modules and sections.
954 foreach (array('module', 'section') as $table) {
955 // Get all the availability objects to process.
956 $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
957 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
958 // Process availabilities, creating them if everything matches ok.
959 foreach ($rs as $availrec) {
960 $allmatchesok = true;
961 // Get the complete legacy availability object.
962 $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
964 // Note: This code used to update IDs, but that is now handled by the
965 // current code (after restore) instead of this legacy code.
967 // Get showavailability option.
968 $thingid = ($table === 'module') ? $availability->coursemoduleid :
969 $availability->coursesectionid;
970 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
971 $table . '_showavailability', $thingid);
972 if (!$showrec) {
973 // Should not happen.
974 throw new coding_exception('No matching showavailability record');
976 $show = $showrec->info->showavailability;
978 // The $availability object is now in the format used in the old
979 // system. Interpret this and convert to new system.
980 $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
981 array('id' => $thingid), MUST_EXIST);
982 $newvalue = \core_availability\info::add_legacy_availability_condition(
983 $currentvalue, $availability, $show);
984 $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
985 array('id' => $thingid));
987 $rs->close();
994 * Execution step that, *conditionally* (if there isn't preloaded information)
995 * will load the inforef files for all the included course/section/activity tasks
996 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
998 class restore_load_included_inforef_records extends restore_execution_step {
1000 protected function define_execution() {
1002 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1003 return;
1006 // Get all the included tasks
1007 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
1008 $progress = $this->task->get_progress();
1009 $progress->start_progress($this->get_name(), count($tasks));
1010 foreach ($tasks as $task) {
1011 // Load the inforef.xml file if exists
1012 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
1013 if (file_exists($inforefpath)) {
1014 // Load each inforef file to temp_ids.
1015 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
1018 $progress->end_progress();
1023 * Execution step that will load all the needed files into backup_files_temp
1024 * - info: contains the whole original object (times, names...)
1025 * (all them being original ids as loaded from xml)
1027 class restore_load_included_files extends restore_structure_step {
1029 protected function define_structure() {
1031 $file = new restore_path_element('file', '/files/file');
1033 return array($file);
1037 * Process one <file> element from files.xml
1039 * @param array $data the element data
1041 public function process_file($data) {
1043 $data = (object)$data; // handy
1045 // load it if needed:
1046 // - it it is one of the annotated inforef files (course/section/activity/block)
1047 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
1048 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
1049 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
1050 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
1051 $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
1052 $data->component == 'grouping' || $data->component == 'grade' ||
1053 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
1054 if ($isfileref || $iscomponent) {
1055 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
1061 * Execution step that, *conditionally* (if there isn't preloaded information),
1062 * will load all the needed roles to backup_temp_ids. They will be stored with
1063 * "role" itemname. Also it will perform one automatic mapping to roles existing
1064 * in the target site, based in permissions of the user performing the restore,
1065 * archetypes and other bits. At the end, each original role will have its associated
1066 * target role or 0 if it's going to be skipped. Note we wrap everything over one
1067 * restore_dbops method, as far as the same stuff is going to be also executed
1068 * by restore prechecks
1070 class restore_load_and_map_roles extends restore_execution_step {
1072 protected function define_execution() {
1073 if ($this->task->get_preloaded_information()) { // if info is already preloaded
1074 return;
1077 $file = $this->get_basepath() . '/roles.xml';
1078 // Load needed toles to temp_ids
1079 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
1081 // Process roles, mapping/skipping. Any error throws exception
1082 // Note we pass controller's info because it can contain role mapping information
1083 // about manual mappings performed by UI
1084 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);
1089 * Execution step that, *conditionally* (if there isn't preloaded information
1090 * and users have been selected in settings, will load all the needed users
1091 * to backup_temp_ids. They will be stored with "user" itemname and with
1092 * their original contextid as paremitemid
1094 class restore_load_included_users extends restore_execution_step {
1096 protected function define_execution() {
1098 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1099 return;
1101 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1102 return;
1104 $file = $this->get_basepath() . '/users.xml';
1105 // Load needed users to temp_ids.
1106 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
1111 * Execution step that, *conditionally* (if there isn't preloaded information
1112 * and users have been selected in settings, will process all the needed users
1113 * in order to decide and perform any action with them (create / map / error)
1114 * Note: Any error will cause exception, as far as this is the same processing
1115 * than the one into restore prechecks (that should have stopped process earlier)
1117 class restore_process_included_users extends restore_execution_step {
1119 protected function define_execution() {
1121 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1122 return;
1124 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1125 return;
1127 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
1128 $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
1133 * Execution step that will create all the needed users as calculated
1134 * by @restore_process_included_users (those having newiteind = 0)
1136 class restore_create_included_users extends restore_execution_step {
1138 protected function define_execution() {
1140 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
1141 $this->task->get_userid(), $this->task->get_progress());
1146 * Structure step that will create all the needed groups and groupings
1147 * by loading them from the groups.xml file performing the required matches.
1148 * Note group members only will be added if restoring user info
1150 class restore_groups_structure_step extends restore_structure_step {
1152 protected function define_structure() {
1154 $paths = array(); // Add paths here
1156 // Do not include group/groupings information if not requested.
1157 $groupinfo = $this->get_setting_value('groups');
1158 if ($groupinfo) {
1159 $paths[] = new restore_path_element('group', '/groups/group');
1160 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
1161 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
1163 return $paths;
1166 // Processing functions go here
1167 public function process_group($data) {
1168 global $DB;
1170 $data = (object)$data; // handy
1171 $data->courseid = $this->get_courseid();
1173 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1174 // another a group in the same course
1175 $context = context_course::instance($data->courseid);
1176 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1177 if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
1178 unset($data->idnumber);
1180 } else {
1181 unset($data->idnumber);
1184 $oldid = $data->id; // need this saved for later
1186 $restorefiles = false; // Only if we end creating the group
1188 // Search if the group already exists (by name & description) in the target course
1189 $description_clause = '';
1190 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1191 if (!empty($data->description)) {
1192 $description_clause = ' AND ' .
1193 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1194 $params['description'] = $data->description;
1196 if (!$groupdb = $DB->get_record_sql("SELECT *
1197 FROM {groups}
1198 WHERE courseid = :courseid
1199 AND name = :grname $description_clause", $params)) {
1200 // group doesn't exist, create
1201 $newitemid = $DB->insert_record('groups', $data);
1202 $restorefiles = true; // We'll restore the files
1203 } else {
1204 // group exists, use it
1205 $newitemid = $groupdb->id;
1207 // Save the id mapping
1208 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
1209 // Invalidate the course group data cache just in case.
1210 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1213 public function process_grouping($data) {
1214 global $DB;
1216 $data = (object)$data; // handy
1217 $data->courseid = $this->get_courseid();
1219 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1220 // another a grouping in the same course
1221 $context = context_course::instance($data->courseid);
1222 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1223 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
1224 unset($data->idnumber);
1226 } else {
1227 unset($data->idnumber);
1230 $oldid = $data->id; // need this saved for later
1231 $restorefiles = false; // Only if we end creating the grouping
1233 // Search if the grouping already exists (by name & description) in the target course
1234 $description_clause = '';
1235 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1236 if (!empty($data->description)) {
1237 $description_clause = ' AND ' .
1238 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1239 $params['description'] = $data->description;
1241 if (!$groupingdb = $DB->get_record_sql("SELECT *
1242 FROM {groupings}
1243 WHERE courseid = :courseid
1244 AND name = :grname $description_clause", $params)) {
1245 // grouping doesn't exist, create
1246 $newitemid = $DB->insert_record('groupings', $data);
1247 $restorefiles = true; // We'll restore the files
1248 } else {
1249 // grouping exists, use it
1250 $newitemid = $groupingdb->id;
1252 // Save the id mapping
1253 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1254 // Invalidate the course group data cache just in case.
1255 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1258 public function process_grouping_group($data) {
1259 global $CFG;
1261 require_once($CFG->dirroot.'/group/lib.php');
1263 $data = (object)$data;
1264 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
1267 protected function after_execute() {
1268 // Add group related files, matching with "group" mappings
1269 $this->add_related_files('group', 'icon', 'group');
1270 $this->add_related_files('group', 'description', 'group');
1271 // Add grouping related files, matching with "grouping" mappings
1272 $this->add_related_files('grouping', 'description', 'grouping');
1273 // Invalidate the course group data.
1274 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1280 * Structure step that will create all the needed group memberships
1281 * by loading them from the groups.xml file performing the required matches.
1283 class restore_groups_members_structure_step extends restore_structure_step {
1285 protected $plugins = null;
1287 protected function define_structure() {
1289 $paths = array(); // Add paths here
1291 if ($this->get_setting_value('groups') && $this->get_setting_value('users')) {
1292 $paths[] = new restore_path_element('group', '/groups/group');
1293 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1296 return $paths;
1299 public function process_group($data) {
1300 $data = (object)$data; // handy
1302 // HACK ALERT!
1303 // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1304 // Let's fake internal state to make $this->get_new_parentid('group') work.
1306 $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1309 public function process_member($data) {
1310 global $DB, $CFG;
1311 require_once("$CFG->dirroot/group/lib.php");
1313 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1315 $data = (object)$data; // handy
1317 // get parent group->id
1318 $data->groupid = $this->get_new_parentid('group');
1320 // map user newitemid and insert if not member already
1321 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1322 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1323 // Check the component, if any, exists.
1324 if (empty($data->component)) {
1325 groups_add_member($data->groupid, $data->userid);
1327 } else if ((strpos($data->component, 'enrol_') === 0)) {
1328 // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1329 // it is possible that enrolment was restored using different plugin type.
1330 if (!isset($this->plugins)) {
1331 $this->plugins = enrol_get_plugins(true);
1333 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1334 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1335 if (isset($this->plugins[$instance->enrol])) {
1336 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1341 } else {
1342 $dir = core_component::get_component_directory($data->component);
1343 if ($dir and is_dir($dir)) {
1344 if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1345 return;
1348 // Bad luck, plugin could not restore the data, let's add normal membership.
1349 groups_add_member($data->groupid, $data->userid);
1350 $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1351 $this->log($message, backup::LOG_WARNING);
1359 * Structure step that will create all the needed scales
1360 * by loading them from the scales.xml
1362 class restore_scales_structure_step extends restore_structure_step {
1364 protected function define_structure() {
1366 $paths = array(); // Add paths here
1367 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1368 return $paths;
1371 protected function process_scale($data) {
1372 global $DB;
1374 $data = (object)$data;
1376 $restorefiles = false; // Only if we end creating the group
1378 $oldid = $data->id; // need this saved for later
1380 // Look for scale (by 'scale' both in standard (course=0) and current course
1381 // with priority to standard scales (ORDER clause)
1382 // scale is not course unique, use get_record_sql to suppress warning
1383 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1384 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
1385 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1386 if (!$scadb = $DB->get_record_sql("SELECT *
1387 FROM {scale}
1388 WHERE courseid IN (0, :courseid)
1389 AND $compare_scale_clause
1390 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1391 // Remap the user if possible, defaut to user performing the restore if not
1392 $userid = $this->get_mappingid('user', $data->userid);
1393 $data->userid = $userid ? $userid : $this->task->get_userid();
1394 // Remap the course if course scale
1395 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1396 // If global scale (course=0), check the user has perms to create it
1397 // falling to course scale if not
1398 $systemctx = context_system::instance();
1399 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1400 $data->courseid = $this->get_courseid();
1402 // scale doesn't exist, create
1403 $newitemid = $DB->insert_record('scale', $data);
1404 $restorefiles = true; // We'll restore the files
1405 } else {
1406 // scale exists, use it
1407 $newitemid = $scadb->id;
1409 // Save the id mapping (with files support at system context)
1410 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1413 protected function after_execute() {
1414 // Add scales related files, matching with "scale" mappings
1415 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1421 * Structure step that will create all the needed outocomes
1422 * by loading them from the outcomes.xml
1424 class restore_outcomes_structure_step extends restore_structure_step {
1426 protected function define_structure() {
1428 $paths = array(); // Add paths here
1429 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1430 return $paths;
1433 protected function process_outcome($data) {
1434 global $DB;
1436 $data = (object)$data;
1438 $restorefiles = false; // Only if we end creating the group
1440 $oldid = $data->id; // need this saved for later
1442 // Look for outcome (by shortname both in standard (courseid=null) and current course
1443 // with priority to standard outcomes (ORDER clause)
1444 // outcome is not course unique, use get_record_sql to suppress warning
1445 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1446 if (!$outdb = $DB->get_record_sql('SELECT *
1447 FROM {grade_outcomes}
1448 WHERE shortname = :shortname
1449 AND (courseid = :courseid OR courseid IS NULL)
1450 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1451 // Remap the user
1452 $userid = $this->get_mappingid('user', $data->usermodified);
1453 $data->usermodified = $userid ? $userid : $this->task->get_userid();
1454 // Remap the scale
1455 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1456 // Remap the course if course outcome
1457 $data->courseid = $data->courseid ? $this->get_courseid() : null;
1458 // If global outcome (course=null), check the user has perms to create it
1459 // falling to course outcome if not
1460 $systemctx = context_system::instance();
1461 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1462 $data->courseid = $this->get_courseid();
1464 // outcome doesn't exist, create
1465 $newitemid = $DB->insert_record('grade_outcomes', $data);
1466 $restorefiles = true; // We'll restore the files
1467 } else {
1468 // scale exists, use it
1469 $newitemid = $outdb->id;
1471 // Set the corresponding grade_outcomes_courses record
1472 $outcourserec = new stdclass();
1473 $outcourserec->courseid = $this->get_courseid();
1474 $outcourserec->outcomeid = $newitemid;
1475 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1476 $DB->insert_record('grade_outcomes_courses', $outcourserec);
1478 // Save the id mapping (with files support at system context)
1479 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1482 protected function after_execute() {
1483 // Add outcomes related files, matching with "outcome" mappings
1484 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1489 * Execution step that, *conditionally* (if there isn't preloaded information
1490 * will load all the question categories and questions (header info only)
1491 * to backup_temp_ids. They will be stored with "question_category" and
1492 * "question" itemnames and with their original contextid and question category
1493 * id as paremitemids
1495 class restore_load_categories_and_questions extends restore_execution_step {
1497 protected function define_execution() {
1499 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1500 return;
1502 $file = $this->get_basepath() . '/questions.xml';
1503 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1508 * Execution step that, *conditionally* (if there isn't preloaded information)
1509 * will process all the needed categories and questions
1510 * in order to decide and perform any action with them (create / map / error)
1511 * Note: Any error will cause exception, as far as this is the same processing
1512 * than the one into restore prechecks (that should have stopped process earlier)
1514 class restore_process_categories_and_questions extends restore_execution_step {
1516 protected function define_execution() {
1518 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1519 return;
1521 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1526 * Structure step that will read the section.xml creating/updating sections
1527 * as needed, rebuilding course cache and other friends
1529 class restore_section_structure_step extends restore_structure_step {
1530 /** @var array Cache: Array of id => course format */
1531 private static $courseformats = array();
1534 * Resets a static cache of course formats. Required for unit testing.
1536 public static function reset_caches() {
1537 self::$courseformats = array();
1540 protected function define_structure() {
1541 global $CFG;
1543 $paths = array();
1545 $section = new restore_path_element('section', '/section');
1546 $paths[] = $section;
1547 if ($CFG->enableavailability) {
1548 $paths[] = new restore_path_element('availability', '/section/availability');
1549 $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1551 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1553 // Apply for 'format' plugins optional paths at section level
1554 $this->add_plugin_structure('format', $section);
1556 // Apply for 'local' plugins optional paths at section level
1557 $this->add_plugin_structure('local', $section);
1559 return $paths;
1562 public function process_section($data) {
1563 global $CFG, $DB;
1564 $data = (object)$data;
1565 $oldid = $data->id; // We'll need this later
1567 $restorefiles = false;
1569 // Look for the section
1570 $section = new stdclass();
1571 $section->course = $this->get_courseid();
1572 $section->section = $data->number;
1573 $section->timemodified = $data->timemodified ?? 0;
1574 // Section doesn't exist, create it with all the info from backup
1575 if (!$secrec = $DB->get_record('course_sections', ['course' => $this->get_courseid(), 'section' => $data->number])) {
1576 $section->name = $data->name;
1577 $section->summary = $data->summary;
1578 $section->summaryformat = $data->summaryformat;
1579 $section->sequence = '';
1580 $section->visible = $data->visible;
1581 if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1582 $section->availability = null;
1583 } else {
1584 $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1585 // Include legacy [<2.7] availability data if provided.
1586 if (is_null($section->availability)) {
1587 $section->availability = \core_availability\info::convert_legacy_fields(
1588 $data, true);
1591 $newitemid = $DB->insert_record('course_sections', $section);
1592 $section->id = $newitemid;
1594 core\event\course_section_created::create_from_section($section)->trigger();
1596 $restorefiles = true;
1598 // Section exists, update non-empty information
1599 } else {
1600 $section->id = $secrec->id;
1601 if ((string)$secrec->name === '') {
1602 $section->name = $data->name;
1604 if (empty($secrec->summary)) {
1605 $section->summary = $data->summary;
1606 $section->summaryformat = $data->summaryformat;
1607 $restorefiles = true;
1610 // Don't update availability (I didn't see a useful way to define
1611 // whether existing or new one should take precedence).
1613 $DB->update_record('course_sections', $section);
1614 $newitemid = $secrec->id;
1616 // Trigger an event for course section update.
1617 $event = \core\event\course_section_updated::create(
1618 array(
1619 'objectid' => $section->id,
1620 'courseid' => $section->course,
1621 'context' => context_course::instance($section->course),
1622 'other' => array('sectionnum' => $section->section)
1625 $event->trigger();
1628 // Annotate the section mapping, with restorefiles option if needed
1629 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1631 // set the new course_section id in the task
1632 $this->task->set_sectionid($newitemid);
1634 // If there is the legacy showavailability data, store this for later use.
1635 // (This data is not present when restoring 'new' backups.)
1636 if (isset($data->showavailability)) {
1637 // Cache the showavailability flag using the backup_ids data field.
1638 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1639 'section_showavailability', $newitemid, 0, null,
1640 (object)array('showavailability' => $data->showavailability));
1643 // Commented out. We never modify course->numsections as far as that is used
1644 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1645 // Note: We keep the code here, to know about and because of the possibility of making this
1646 // optional based on some setting/attribute in the future
1647 // If needed, adjust course->numsections
1648 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1649 // if ($numsections < $section->section) {
1650 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1651 // }
1656 * Process the legacy availability table record. This table does not exist
1657 * in Moodle 2.7+ but we still support restore.
1659 * @param stdClass $data Record data
1661 public function process_availability($data) {
1662 $data = (object)$data;
1663 // Simply going to store the whole availability record now, we'll process
1664 // all them later in the final task (once all activities have been restored)
1665 // Let's call the low level one to be able to store the whole object.
1666 $data->coursesectionid = $this->task->get_sectionid();
1667 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1668 'section_availability', $data->id, 0, null, $data);
1672 * Process the legacy availability fields table record. This table does not
1673 * exist in Moodle 2.7+ but we still support restore.
1675 * @param stdClass $data Record data
1677 public function process_availability_field($data) {
1678 global $DB;
1679 $data = (object)$data;
1680 // Mark it is as passed by default
1681 $passed = true;
1682 $customfieldid = null;
1684 // If a customfield has been used in order to pass we must be able to match an existing
1685 // customfield by name (data->customfield) and type (data->customfieldtype)
1686 if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1687 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1688 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1689 $passed = false;
1690 } else if (!is_null($data->customfield)) {
1691 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1692 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1693 $passed = ($customfieldid !== false);
1696 if ($passed) {
1697 // Create the object to insert into the database
1698 $availfield = new stdClass();
1699 $availfield->coursesectionid = $this->task->get_sectionid();
1700 $availfield->userfield = $data->userfield;
1701 $availfield->customfieldid = $customfieldid;
1702 $availfield->operator = $data->operator;
1703 $availfield->value = $data->value;
1705 // Get showavailability option.
1706 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1707 'section_showavailability', $availfield->coursesectionid);
1708 if (!$showrec) {
1709 // Should not happen.
1710 throw new coding_exception('No matching showavailability record');
1712 $show = $showrec->info->showavailability;
1714 // The $availfield object is now in the format used in the old
1715 // system. Interpret this and convert to new system.
1716 $currentvalue = $DB->get_field('course_sections', 'availability',
1717 array('id' => $availfield->coursesectionid), MUST_EXIST);
1718 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1719 $currentvalue, $availfield, $show);
1721 $section = new stdClass();
1722 $section->id = $availfield->coursesectionid;
1723 $section->availability = $newvalue;
1724 $section->timemodified = time();
1725 $DB->update_record('course_sections', $section);
1729 public function process_course_format_options($data) {
1730 global $DB;
1731 $courseid = $this->get_courseid();
1732 if (!array_key_exists($courseid, self::$courseformats)) {
1733 // It is safe to have a static cache of course formats because format can not be changed after this point.
1734 self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1736 $data = (array)$data;
1737 if (self::$courseformats[$courseid] === $data['format']) {
1738 // Import section format options only if both courses (the one that was backed up
1739 // and the one we are restoring into) have same formats.
1740 $params = array(
1741 'courseid' => $this->get_courseid(),
1742 'sectionid' => $this->task->get_sectionid(),
1743 'format' => $data['format'],
1744 'name' => $data['name']
1746 if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1747 // Do not overwrite existing information.
1748 $newid = $record->id;
1749 } else {
1750 $params['value'] = $data['value'];
1751 $newid = $DB->insert_record('course_format_options', $params);
1753 $this->set_mapping('course_format_options', $data['id'], $newid);
1757 protected function after_execute() {
1758 // Add section related files, with 'course_section' itemid to match
1759 $this->add_related_files('course', 'section', 'course_section');
1764 * Structure step that will read the course.xml file, loading it and performing
1765 * various actions depending of the site/restore settings. Note that target
1766 * course always exist before arriving here so this step will be updating
1767 * the course record (never inserting)
1769 class restore_course_structure_step extends restore_structure_step {
1771 * @var bool this gets set to true by {@link process_course()} if we are
1772 * restoring an old coures that used the legacy 'module security' feature.
1773 * If so, we have to do more work in {@link after_execute()}.
1775 protected $legacyrestrictmodules = false;
1778 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1779 * array with array keys the module names ('forum', 'quiz', etc.). These are
1780 * the modules that are allowed according to the data in the backup file.
1781 * In {@link after_execute()} we then have to prevent adding of all the other
1782 * types of activity.
1784 protected $legacyallowedmodules = array();
1786 protected function define_structure() {
1788 $course = new restore_path_element('course', '/course');
1789 $category = new restore_path_element('category', '/course/category');
1790 $tag = new restore_path_element('tag', '/course/tags/tag');
1791 $customfield = new restore_path_element('customfield', '/course/customfields/customfield');
1792 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1794 // Apply for 'format' plugins optional paths at course level
1795 $this->add_plugin_structure('format', $course);
1797 // Apply for 'theme' plugins optional paths at course level
1798 $this->add_plugin_structure('theme', $course);
1800 // Apply for 'report' plugins optional paths at course level
1801 $this->add_plugin_structure('report', $course);
1803 // Apply for 'course report' plugins optional paths at course level
1804 $this->add_plugin_structure('coursereport', $course);
1806 // Apply for plagiarism plugins optional paths at course level
1807 $this->add_plugin_structure('plagiarism', $course);
1809 // Apply for local plugins optional paths at course level
1810 $this->add_plugin_structure('local', $course);
1812 // Apply for admin tool plugins optional paths at course level.
1813 $this->add_plugin_structure('tool', $course);
1815 return array($course, $category, $tag, $customfield, $allowed_module);
1819 * Processing functions go here
1821 * @global moodledatabase $DB
1822 * @param stdClass $data
1824 public function process_course($data) {
1825 global $CFG, $DB;
1826 $context = context::instance_by_id($this->task->get_contextid());
1827 $userid = $this->task->get_userid();
1828 $target = $this->get_task()->get_target();
1829 $isnewcourse = $target == backup::TARGET_NEW_COURSE;
1831 // When restoring to a new course we can set all the things except for the ID number.
1832 $canchangeidnumber = $isnewcourse || has_capability('moodle/course:changeidnumber', $context, $userid);
1833 $canchangesummary = $isnewcourse || has_capability('moodle/course:changesummary', $context, $userid);
1834 $canforcelanguage = has_capability('moodle/course:setforcedlanguage', $context, $userid);
1836 $data = (object)$data;
1837 $data->id = $this->get_courseid();
1839 // Calculate final course names, to avoid dupes.
1840 $fullname = $this->get_setting_value('course_fullname');
1841 $shortname = $this->get_setting_value('course_shortname');
1842 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names($this->get_courseid(),
1843 $fullname === false ? $data->fullname : $fullname,
1844 $shortname === false ? $data->shortname : $shortname);
1845 // Do not modify the course names at all when merging and user selected to keep the names (or prohibited by cap).
1846 if (!$isnewcourse && $fullname === false) {
1847 unset($data->fullname);
1849 if (!$isnewcourse && $shortname === false) {
1850 unset($data->shortname);
1853 // Unset summary if user can't change it.
1854 if (!$canchangesummary) {
1855 unset($data->summary);
1856 unset($data->summaryformat);
1859 // Unset lang if user can't change it.
1860 if (!$canforcelanguage) {
1861 unset($data->lang);
1864 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1865 // another course on this site.
1866 if (!empty($data->idnumber) && $canchangeidnumber && $this->task->is_samesite()
1867 && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1868 // Do not reset idnumber.
1870 } else if (!$isnewcourse) {
1871 // Prevent override when restoring as merge.
1872 unset($data->idnumber);
1874 } else {
1875 $data->idnumber = '';
1878 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1879 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1880 if (empty($data->hiddensections)) {
1881 $data->hiddensections = 0;
1884 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1885 // then we will need to process restricted modules after execution.
1886 $this->legacyrestrictmodules = !empty($data->restrictmodules);
1888 $data->startdate= $this->apply_date_offset($data->startdate);
1889 if (isset($data->enddate)) {
1890 $data->enddate = $this->apply_date_offset($data->enddate);
1893 if ($data->defaultgroupingid) {
1894 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1896 if (empty($CFG->enablecompletion)) {
1897 $data->enablecompletion = 0;
1898 $data->completionstartonenrol = 0;
1899 $data->completionnotify = 0;
1901 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1902 if (isset($data->lang) && !array_key_exists($data->lang, $languages)) {
1903 $data->lang = '';
1906 $themes = get_list_of_themes(); // Get themes for quick search later
1907 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1908 $data->theme = '';
1911 // Check if this is an old SCORM course format.
1912 if ($data->format == 'scorm') {
1913 $data->format = 'singleactivity';
1914 $data->activitytype = 'scorm';
1917 // Course record ready, update it
1918 $DB->update_record('course', $data);
1920 course_get_format($data)->update_course_format_options($data);
1922 // Role name aliases
1923 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1926 public function process_category($data) {
1927 // Nothing to do with the category. UI sets it before restore starts
1930 public function process_tag($data) {
1931 global $CFG, $DB;
1933 $data = (object)$data;
1935 core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
1936 context_course::instance($this->get_courseid()), $data->rawname);
1940 * Process custom fields
1942 * @param array $data
1944 public function process_customfield($data) {
1945 $handler = core_course\customfield\course_handler::create();
1946 $handler->restore_instance_data_from_backup($this->task, $data);
1949 public function process_allowed_module($data) {
1950 $data = (object)$data;
1952 // Backwards compatiblity support for the data that used to be in the
1953 // course_allowed_modules table.
1954 if ($this->legacyrestrictmodules) {
1955 $this->legacyallowedmodules[$data->modulename] = 1;
1959 protected function after_execute() {
1960 global $DB;
1962 // Add course related files, without itemid to match
1963 $this->add_related_files('course', 'summary', null);
1964 $this->add_related_files('course', 'overviewfiles', null);
1966 // Deal with legacy allowed modules.
1967 if ($this->legacyrestrictmodules) {
1968 $context = context_course::instance($this->get_courseid());
1970 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1971 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1972 foreach ($managerroleids as $roleid) {
1973 unset($roleids[$roleid]);
1976 foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1977 if (isset($this->legacyallowedmodules[$modname])) {
1978 // Module is allowed, no worries.
1979 continue;
1982 $capability = 'mod/' . $modname . ':addinstance';
1984 if (!get_capability_info($capability)) {
1985 $this->log("Capability '{$capability}' was not found!", backup::LOG_WARNING);
1986 continue;
1989 foreach ($roleids as $roleid) {
1990 assign_capability($capability, CAP_PREVENT, $roleid, $context);
1998 * Execution step that will migrate legacy files if present.
2000 class restore_course_legacy_files_step extends restore_execution_step {
2001 public function define_execution() {
2002 global $DB;
2004 // Do a check for legacy files and skip if there are none.
2005 $sql = 'SELECT count(*)
2006 FROM {backup_files_temp}
2007 WHERE backupid = ?
2008 AND contextid = ?
2009 AND component = ?
2010 AND filearea = ?';
2011 $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
2013 if ($DB->count_records_sql($sql, $params)) {
2014 $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
2015 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
2016 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
2022 * Structure step that will read the roles.xml file (at course/activity/block levels)
2023 * containing all the role_assignments and overrides for that context. If corresponding to
2024 * one mapped role, they will be applied to target context. Will observe the role_assignments
2025 * setting to decide if ras are restored.
2027 * Note: this needs to be executed after all users are enrolled.
2029 class restore_ras_and_caps_structure_step extends restore_structure_step {
2030 protected $plugins = null;
2032 protected function define_structure() {
2034 $paths = array();
2036 // Observe the role_assignments setting
2037 if ($this->get_setting_value('role_assignments')) {
2038 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
2040 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
2042 return $paths;
2046 * Assign roles
2048 * This has to be called after enrolments processing.
2050 * @param mixed $data
2051 * @return void
2053 public function process_assignment($data) {
2054 global $DB;
2056 $data = (object)$data;
2058 // Check roleid, userid are one of the mapped ones
2059 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
2060 return;
2062 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
2063 return;
2065 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
2066 // Only assign roles to not deleted users
2067 return;
2069 if (!$contextid = $this->task->get_contextid()) {
2070 return;
2073 if (empty($data->component)) {
2074 // assign standard manual roles
2075 // TODO: role_assign() needs one userid param to be able to specify our restore userid
2076 role_assign($newroleid, $newuserid, $contextid);
2078 } else if ((strpos($data->component, 'enrol_') === 0)) {
2079 // Deal with enrolment roles - ignore the component and just find out the instance via new id,
2080 // it is possible that enrolment was restored using different plugin type.
2081 if (!isset($this->plugins)) {
2082 $this->plugins = enrol_get_plugins(true);
2084 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
2085 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2086 if (isset($this->plugins[$instance->enrol])) {
2087 $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
2092 } else {
2093 $data->roleid = $newroleid;
2094 $data->userid = $newuserid;
2095 $data->contextid = $contextid;
2096 $dir = core_component::get_component_directory($data->component);
2097 if ($dir and is_dir($dir)) {
2098 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
2099 return;
2102 // Bad luck, plugin could not restore the data, let's add normal membership.
2103 role_assign($data->roleid, $data->userid, $data->contextid);
2104 $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
2105 $this->log($message, backup::LOG_WARNING);
2109 public function process_override($data) {
2110 $data = (object)$data;
2112 // Check roleid is one of the mapped ones
2113 $newroleid = $this->get_mappingid('role', $data->roleid);
2114 // If newroleid and context are valid assign it via API (it handles dupes and so on)
2115 if ($newroleid && $this->task->get_contextid()) {
2116 if (!get_capability_info($data->capability)) {
2117 $this->log("Capability '{$data->capability}' was not found!", backup::LOG_WARNING);
2118 } else {
2119 // TODO: assign_capability() needs one userid param to be able to specify our restore userid.
2120 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
2127 * If no instances yet add default enrol methods the same way as when creating new course in UI.
2129 class restore_default_enrolments_step extends restore_execution_step {
2131 public function define_execution() {
2132 global $DB;
2134 // No enrolments in front page.
2135 if ($this->get_courseid() == SITEID) {
2136 return;
2139 $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
2141 if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
2142 // Something already added instances, do not add default instances.
2143 $plugins = enrol_get_plugins(true);
2144 foreach ($plugins as $plugin) {
2145 $plugin->restore_sync_course($course);
2148 } else {
2149 // Looks like a newly created course.
2150 enrol_course_updated(true, $course, null);
2156 * This structure steps restores the enrol plugins and their underlying
2157 * enrolments, performing all the mappings and/or movements required
2159 class restore_enrolments_structure_step extends restore_structure_step {
2160 protected $enrolsynced = false;
2161 protected $plugins = null;
2162 protected $originalstatus = array();
2165 * Conditionally decide if this step should be executed.
2167 * This function checks the following parameter:
2169 * 1. the course/enrolments.xml file exists
2171 * @return bool true is safe to execute, false otherwise
2173 protected function execute_condition() {
2175 if ($this->get_courseid() == SITEID) {
2176 return false;
2179 // Check it is included in the backup
2180 $fullpath = $this->task->get_taskbasepath();
2181 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2182 if (!file_exists($fullpath)) {
2183 // Not found, can't restore enrolments info
2184 return false;
2187 return true;
2190 protected function define_structure() {
2192 $userinfo = $this->get_setting_value('users');
2194 $paths = [];
2195 $paths[] = $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2196 if ($userinfo) {
2197 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2199 // Attach local plugin stucture to enrol element.
2200 $this->add_plugin_structure('enrol', $enrol);
2202 return $paths;
2206 * Create enrolment instances.
2208 * This has to be called after creation of roles
2209 * and before adding of role assignments.
2211 * @param mixed $data
2212 * @return void
2214 public function process_enrol($data) {
2215 global $DB;
2217 $data = (object)$data;
2218 $oldid = $data->id; // We'll need this later.
2219 unset($data->id);
2221 $this->originalstatus[$oldid] = $data->status;
2223 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2224 $this->set_mapping('enrol', $oldid, 0);
2225 return;
2228 if (!isset($this->plugins)) {
2229 $this->plugins = enrol_get_plugins(true);
2232 if (!$this->enrolsynced) {
2233 // Make sure that all plugin may create instances and enrolments automatically
2234 // before the first instance restore - this is suitable especially for plugins
2235 // that synchronise data automatically using course->idnumber or by course categories.
2236 foreach ($this->plugins as $plugin) {
2237 $plugin->restore_sync_course($courserec);
2239 $this->enrolsynced = true;
2242 // Map standard fields - plugin has to process custom fields manually.
2243 $data->roleid = $this->get_mappingid('role', $data->roleid);
2244 $data->courseid = $courserec->id;
2246 if (!$this->get_setting_value('users') && $this->get_setting_value('enrolments') == backup::ENROL_WITHUSERS) {
2247 $converttomanual = true;
2248 } else {
2249 $converttomanual = ($this->get_setting_value('enrolments') == backup::ENROL_NEVER);
2252 if ($converttomanual) {
2253 // Restore enrolments as manual enrolments.
2254 unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2255 if (!enrol_is_enabled('manual')) {
2256 $this->set_mapping('enrol', $oldid, 0);
2257 return;
2259 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2260 $instance = reset($instances);
2261 $this->set_mapping('enrol', $oldid, $instance->id);
2262 } else {
2263 if ($data->enrol === 'manual') {
2264 $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2265 } else {
2266 $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2268 $this->set_mapping('enrol', $oldid, $instanceid);
2271 } else {
2272 if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2273 $this->set_mapping('enrol', $oldid, 0);
2274 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, consider restoring without enrolment methods";
2275 $this->log($message, backup::LOG_WARNING);
2276 return;
2278 if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2279 // Let's keep the sortorder in old backups.
2280 } else {
2281 // Prevent problems with colliding sortorders in old backups,
2282 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2283 unset($data->sortorder);
2285 // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2286 $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2291 * Create user enrolments.
2293 * This has to be called after creation of enrolment instances
2294 * and before adding of role assignments.
2296 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2298 * @param mixed $data
2299 * @return void
2301 public function process_enrolment($data) {
2302 global $DB;
2304 if (!isset($this->plugins)) {
2305 $this->plugins = enrol_get_plugins(true);
2308 $data = (object)$data;
2310 // Process only if parent instance have been mapped.
2311 if ($enrolid = $this->get_new_parentid('enrol')) {
2312 $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2313 $oldenrolid = $this->get_old_parentid('enrol');
2314 if (isset($this->originalstatus[$oldenrolid])) {
2315 $oldinstancestatus = $this->originalstatus[$oldenrolid];
2317 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2318 // And only if user is a mapped one.
2319 if ($userid = $this->get_mappingid('user', $data->userid)) {
2320 if (isset($this->plugins[$instance->enrol])) {
2321 $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2331 * Make sure the user restoring the course can actually access it.
2333 class restore_fix_restorer_access_step extends restore_execution_step {
2334 protected function define_execution() {
2335 global $CFG, $DB;
2337 if (!$userid = $this->task->get_userid()) {
2338 return;
2341 if (empty($CFG->restorernewroleid)) {
2342 // Bad luck, no fallback role for restorers specified
2343 return;
2346 $courseid = $this->get_courseid();
2347 $context = context_course::instance($courseid);
2349 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2350 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2351 return;
2354 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2355 role_assign($CFG->restorernewroleid, $userid, $context);
2357 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2358 // Extra role is enough, yay!
2359 return;
2362 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2363 // hopefully admin selected suitable $CFG->restorernewroleid ...
2364 if (!enrol_is_enabled('manual')) {
2365 return;
2367 if (!$enrol = enrol_get_plugin('manual')) {
2368 return;
2370 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2371 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2372 $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2373 $enrol->add_instance($course, $fields);
2376 enrol_try_internal_enrol($courseid, $userid);
2382 * This structure steps restores the filters and their configs
2384 class restore_filters_structure_step extends restore_structure_step {
2386 protected function define_structure() {
2388 $paths = array();
2390 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2391 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2393 return $paths;
2396 public function process_active($data) {
2398 $data = (object)$data;
2400 if (strpos($data->filter, 'filter/') === 0) {
2401 $data->filter = substr($data->filter, 7);
2403 } else if (strpos($data->filter, '/') !== false) {
2404 // Unsupported old filter.
2405 return;
2408 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2409 return;
2411 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2414 public function process_config($data) {
2416 $data = (object)$data;
2418 if (strpos($data->filter, 'filter/') === 0) {
2419 $data->filter = substr($data->filter, 7);
2421 } else if (strpos($data->filter, '/') !== false) {
2422 // Unsupported old filter.
2423 return;
2426 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2427 return;
2429 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2435 * This structure steps restores the comments
2436 * Note: Cannot use the comments API because defaults to USER->id.
2437 * That should change allowing to pass $userid
2439 class restore_comments_structure_step extends restore_structure_step {
2441 protected function define_structure() {
2443 $paths = array();
2445 $paths[] = new restore_path_element('comment', '/comments/comment');
2447 return $paths;
2450 public function process_comment($data) {
2451 global $DB;
2453 $data = (object)$data;
2455 // First of all, if the comment has some itemid, ask to the task what to map
2456 $mapping = false;
2457 if ($data->itemid) {
2458 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2459 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2461 // Only restore the comment if has no mapping OR we have found the matching mapping
2462 if (!$mapping || $data->itemid) {
2463 // Only if user mapping and context
2464 $data->userid = $this->get_mappingid('user', $data->userid);
2465 if ($data->userid && $this->task->get_contextid()) {
2466 $data->contextid = $this->task->get_contextid();
2467 // Only if there is another comment with same context/user/timecreated
2468 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2469 if (!$DB->record_exists('comments', $params)) {
2470 $DB->insert_record('comments', $data);
2478 * This structure steps restores the badges and their configs
2480 class restore_badges_structure_step extends restore_structure_step {
2483 * Conditionally decide if this step should be executed.
2485 * This function checks the following parameters:
2487 * 1. Badges and course badges are enabled on the site.
2488 * 2. The course/badges.xml file exists.
2489 * 3. All modules are restorable.
2490 * 4. All modules are marked for restore.
2492 * @return bool True is safe to execute, false otherwise
2494 protected function execute_condition() {
2495 global $CFG;
2497 // First check is badges and course level badges are enabled on this site.
2498 if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2499 // Disabled, don't restore course badges.
2500 return false;
2503 // Check if badges.xml is included in the backup.
2504 $fullpath = $this->task->get_taskbasepath();
2505 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2506 if (!file_exists($fullpath)) {
2507 // Not found, can't restore course badges.
2508 return false;
2511 // Check we are able to restore all backed up modules.
2512 if ($this->task->is_missing_modules()) {
2513 return false;
2516 // Finally check all modules within the backup are being restored.
2517 if ($this->task->is_excluding_activities()) {
2518 return false;
2521 return true;
2524 protected function define_structure() {
2525 $paths = array();
2526 $paths[] = new restore_path_element('badge', '/badges/badge');
2527 $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2528 $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2529 $paths[] = new restore_path_element('endorsement', '/badges/badge/endorsement');
2530 $paths[] = new restore_path_element('alignment', '/badges/badge/alignments/alignment');
2531 $paths[] = new restore_path_element('relatedbadge', '/badges/badge/relatedbadges/relatedbadge');
2532 $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2534 return $paths;
2537 public function process_badge($data) {
2538 global $DB, $CFG;
2540 require_once($CFG->libdir . '/badgeslib.php');
2542 $data = (object)$data;
2543 $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2544 if (empty($data->usercreated)) {
2545 $data->usercreated = $this->task->get_userid();
2547 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2548 if (empty($data->usermodified)) {
2549 $data->usermodified = $this->task->get_userid();
2552 // We'll restore the badge image.
2553 $restorefiles = true;
2555 $courseid = $this->get_courseid();
2557 $params = array(
2558 'name' => $data->name,
2559 'description' => $data->description,
2560 'timecreated' => $data->timecreated,
2561 'timemodified' => $data->timemodified,
2562 'usercreated' => $data->usercreated,
2563 'usermodified' => $data->usermodified,
2564 'issuername' => $data->issuername,
2565 'issuerurl' => $data->issuerurl,
2566 'issuercontact' => $data->issuercontact,
2567 'expiredate' => $this->apply_date_offset($data->expiredate),
2568 'expireperiod' => $data->expireperiod,
2569 'type' => BADGE_TYPE_COURSE,
2570 'courseid' => $courseid,
2571 'message' => $data->message,
2572 'messagesubject' => $data->messagesubject,
2573 'attachment' => $data->attachment,
2574 'notification' => $data->notification,
2575 'status' => BADGE_STATUS_INACTIVE,
2576 'nextcron' => $data->nextcron,
2577 'version' => $data->version,
2578 'language' => $data->language,
2579 'imageauthorname' => $data->imageauthorname,
2580 'imageauthoremail' => $data->imageauthoremail,
2581 'imageauthorurl' => $data->imageauthorurl,
2582 'imagecaption' => $data->imagecaption
2585 $newid = $DB->insert_record('badge', $params);
2586 $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2590 * Create an endorsement for a badge.
2592 * @param mixed $data
2593 * @return void
2595 public function process_endorsement($data) {
2596 global $DB;
2598 $data = (object)$data;
2600 $params = [
2601 'badgeid' => $this->get_new_parentid('badge'),
2602 'issuername' => $data->issuername,
2603 'issuerurl' => $data->issuerurl,
2604 'issueremail' => $data->issueremail,
2605 'claimid' => $data->claimid,
2606 'claimcomment' => $data->claimcomment,
2607 'dateissued' => $this->apply_date_offset($data->dateissued)
2609 $newid = $DB->insert_record('badge_endorsement', $params);
2610 $this->set_mapping('endorsement', $data->id, $newid);
2614 * Link to related badges for a badge. This relies on post processing in after_execute().
2616 * @param mixed $data
2617 * @return void
2619 public function process_relatedbadge($data) {
2620 global $DB;
2622 $data = (object)$data;
2623 $relatedbadgeid = $data->relatedbadgeid;
2625 if ($relatedbadgeid) {
2626 // Only backup and restore related badges if they are contained in the backup file.
2627 $params = array(
2628 'badgeid' => $this->get_new_parentid('badge'),
2629 'relatedbadgeid' => $relatedbadgeid
2631 $newid = $DB->insert_record('badge_related', $params);
2636 * Link to an alignment for a badge.
2638 * @param mixed $data
2639 * @return void
2641 public function process_alignment($data) {
2642 global $DB;
2644 $data = (object)$data;
2645 $params = array(
2646 'badgeid' => $this->get_new_parentid('badge'),
2647 'targetname' => $data->targetname,
2648 'targeturl' => $data->targeturl,
2649 'targetdescription' => $data->targetdescription,
2650 'targetframework' => $data->targetframework,
2651 'targetcode' => $data->targetcode
2653 $newid = $DB->insert_record('badge_alignment', $params);
2654 $this->set_mapping('alignment', $data->id, $newid);
2657 public function process_criterion($data) {
2658 global $DB;
2660 $data = (object)$data;
2662 $params = array(
2663 'badgeid' => $this->get_new_parentid('badge'),
2664 'criteriatype' => $data->criteriatype,
2665 'method' => $data->method,
2666 'description' => isset($data->description) ? $data->description : '',
2667 'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0,
2670 $newid = $DB->insert_record('badge_criteria', $params);
2671 $this->set_mapping('criterion', $data->id, $newid);
2674 public function process_parameter($data) {
2675 global $DB, $CFG;
2677 require_once($CFG->libdir . '/badgeslib.php');
2679 $data = (object)$data;
2680 $criteriaid = $this->get_new_parentid('criterion');
2682 // Parameter array that will go to database.
2683 $params = array();
2684 $params['critid'] = $criteriaid;
2686 $oldparam = explode('_', $data->name);
2688 if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2689 $module = $this->get_mappingid('course_module', $oldparam[1]);
2690 $params['name'] = $oldparam[0] . '_' . $module;
2691 $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2692 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2693 $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2694 $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2695 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2696 $role = $this->get_mappingid('role', $data->value);
2697 if (!empty($role)) {
2698 $params['name'] = 'role_' . $role;
2699 $params['value'] = $role;
2700 } else {
2701 return;
2703 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COMPETENCY) {
2704 $competencyid = $this->get_mappingid('competency', $data->value);
2705 if (!empty($competencyid)) {
2706 $params['name'] = 'competency_' . $competencyid;
2707 $params['value'] = $competencyid;
2708 } else {
2709 return;
2713 if (!$DB->record_exists('badge_criteria_param', $params)) {
2714 $DB->insert_record('badge_criteria_param', $params);
2718 public function process_manual_award($data) {
2719 global $DB;
2721 $data = (object)$data;
2722 $role = $this->get_mappingid('role', $data->issuerrole);
2724 if (!empty($role)) {
2725 $award = array(
2726 'badgeid' => $this->get_new_parentid('badge'),
2727 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2728 'issuerid' => $this->get_mappingid('user', $data->issuerid),
2729 'issuerrole' => $role,
2730 'datemet' => $this->apply_date_offset($data->datemet)
2733 // Skip the manual award if recipient or issuer can not be mapped to.
2734 if (empty($award['recipientid']) || empty($award['issuerid'])) {
2735 return;
2738 $DB->insert_record('badge_manual_award', $award);
2742 protected function after_execute() {
2743 global $DB;
2744 // Add related files.
2745 $this->add_related_files('badges', 'badgeimage', 'badge');
2747 $badgeid = $this->get_new_parentid('badge');
2748 // Remap any related badges.
2749 // We do this in the DB directly because this is backup/restore it is not valid to call into
2750 // the component API.
2751 $params = array('badgeid' => $badgeid);
2752 $query = "SELECT DISTINCT br.id, br.badgeid, br.relatedbadgeid
2753 FROM {badge_related} br
2754 WHERE (br.badgeid = :badgeid)";
2755 $relatedbadges = $DB->get_records_sql($query, $params);
2756 $newrelatedids = [];
2757 foreach ($relatedbadges as $relatedbadge) {
2758 $relatedid = $this->get_mappingid('badge', $relatedbadge->relatedbadgeid);
2759 $params['relatedbadgeid'] = $relatedbadge->relatedbadgeid;
2760 $DB->delete_records_select('badge_related', '(badgeid = :badgeid AND relatedbadgeid = :relatedbadgeid)', $params);
2761 if ($relatedid) {
2762 $newrelatedids[] = $relatedid;
2765 if (!empty($newrelatedids)) {
2766 $relatedbadges = [];
2767 foreach ($newrelatedids as $relatedid) {
2768 $relatedbadge = new stdClass();
2769 $relatedbadge->badgeid = $badgeid;
2770 $relatedbadge->relatedbadgeid = $relatedid;
2771 $relatedbadges[] = $relatedbadge;
2773 $DB->insert_records('badge_related', $relatedbadges);
2779 * This structure steps restores the calendar events
2781 class restore_calendarevents_structure_step extends restore_structure_step {
2783 protected function define_structure() {
2785 $paths = array();
2787 $paths[] = new restore_path_element('calendarevents', '/events/event');
2789 return $paths;
2792 public function process_calendarevents($data) {
2793 global $DB, $SITE, $USER;
2795 $data = (object)$data;
2796 $oldid = $data->id;
2797 $restorefiles = true; // We'll restore the files
2799 // If this is a new action event, it will automatically be populated by the adhoc task.
2800 // Nothing to do here.
2801 if (isset($data->type) && $data->type == CALENDAR_EVENT_TYPE_ACTION) {
2802 return;
2805 // User overrides for activities are identified by having a courseid of zero with
2806 // both a modulename and instance value set.
2807 $isuseroverride = !$data->courseid && $data->modulename && $data->instance;
2809 // If we don't want to include user data and this record is a user override event
2810 // for an activity then we should not create it. (Only activity events can be user override events - which must have this
2811 // setting).
2812 if ($isuseroverride && $this->task->setting_exists('userinfo') && !$this->task->get_setting_value('userinfo')) {
2813 return;
2816 // Find the userid and the groupid associated with the event.
2817 $data->userid = $this->get_mappingid('user', $data->userid);
2818 if ($data->userid === false) {
2819 // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2820 // Use the current user ID for these events.
2821 $data->userid = $USER->id;
2823 if (!empty($data->groupid)) {
2824 $data->groupid = $this->get_mappingid('group', $data->groupid);
2825 if ($data->groupid === false) {
2826 return;
2829 // Handle events with empty eventtype //MDL-32827
2830 if(empty($data->eventtype)) {
2831 if ($data->courseid == $SITE->id) { // Site event
2832 $data->eventtype = "site";
2833 } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2834 // Course assingment event
2835 $data->eventtype = "due";
2836 } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event
2837 $data->eventtype = "course";
2838 } else if ($data->groupid) { // Group event
2839 $data->eventtype = "group";
2840 } else if ($data->userid) { // User event
2841 $data->eventtype = "user";
2842 } else {
2843 return;
2847 $params = array(
2848 'name' => $data->name,
2849 'description' => $data->description,
2850 'format' => $data->format,
2851 // User overrides in activities use a course id of zero. All other event types
2852 // must use the mapped course id.
2853 'courseid' => $data->courseid ? $this->get_courseid() : 0,
2854 'groupid' => $data->groupid,
2855 'userid' => $data->userid,
2856 'repeatid' => $this->get_mappingid('event', $data->repeatid),
2857 'modulename' => $data->modulename,
2858 'type' => isset($data->type) ? $data->type : 0,
2859 'eventtype' => $data->eventtype,
2860 'timestart' => $this->apply_date_offset($data->timestart),
2861 'timeduration' => $data->timeduration,
2862 'timesort' => isset($data->timesort) ? $this->apply_date_offset($data->timesort) : null,
2863 'visible' => $data->visible,
2864 'uuid' => $data->uuid,
2865 'sequence' => $data->sequence,
2866 'timemodified' => $data->timemodified,
2867 'priority' => isset($data->priority) ? $data->priority : null,
2868 'location' => isset($data->location) ? $data->location : null);
2869 if ($this->name == 'activity_calendar') {
2870 $params['instance'] = $this->task->get_activityid();
2871 } else {
2872 $params['instance'] = 0;
2874 $sql = "SELECT id
2875 FROM {event}
2876 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2877 AND courseid = ?
2878 AND modulename = ?
2879 AND instance = ?
2880 AND timestart = ?
2881 AND timeduration = ?
2882 AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2883 $arg = array ($params['name'], $params['courseid'], $params['modulename'], $params['instance'], $params['timestart'], $params['timeduration'], $params['description']);
2884 $result = $DB->record_exists_sql($sql, $arg);
2885 if (empty($result)) {
2886 $newitemid = $DB->insert_record('event', $params);
2887 $this->set_mapping('event', $oldid, $newitemid);
2888 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2890 // With repeating events, each event has the repeatid pointed at the first occurrence.
2891 // Since the repeatid will be empty when the first occurrence is restored,
2892 // Get the repeatid from the second occurrence of the repeating event and use that to update the first occurrence.
2893 // Then keep a list of repeatids so we only perform this update once.
2894 static $repeatids = array();
2895 if (!empty($params['repeatid']) && !in_array($params['repeatid'], $repeatids)) {
2896 // This entry is repeated so the repeatid field must be set.
2897 $DB->set_field('event', 'repeatid', $params['repeatid'], array('id' => $params['repeatid']));
2898 $repeatids[] = $params['repeatid'];
2902 protected function after_execute() {
2903 // Add related files
2904 $this->add_related_files('calendar', 'event_description', 'event_description');
2908 class restore_course_completion_structure_step extends restore_structure_step {
2911 * Conditionally decide if this step should be executed.
2913 * This function checks parameters that are not immediate settings to ensure
2914 * that the enviroment is suitable for the restore of course completion info.
2916 * This function checks the following four parameters:
2918 * 1. Course completion is enabled on the site
2919 * 2. The backup includes course completion information
2920 * 3. All modules are restorable
2921 * 4. All modules are marked for restore.
2922 * 5. No completion criteria already exist for the course.
2924 * @return bool True is safe to execute, false otherwise
2926 protected function execute_condition() {
2927 global $CFG, $DB;
2929 // First check course completion is enabled on this site
2930 if (empty($CFG->enablecompletion)) {
2931 // Disabled, don't restore course completion
2932 return false;
2935 // No course completion on the front page.
2936 if ($this->get_courseid() == SITEID) {
2937 return false;
2940 // Check it is included in the backup
2941 $fullpath = $this->task->get_taskbasepath();
2942 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2943 if (!file_exists($fullpath)) {
2944 // Not found, can't restore course completion
2945 return false;
2948 // Check we are able to restore all backed up modules
2949 if ($this->task->is_missing_modules()) {
2950 return false;
2953 // Check all modules within the backup are being restored.
2954 if ($this->task->is_excluding_activities()) {
2955 return false;
2958 // Check that no completion criteria is already set for the course.
2959 if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
2960 return false;
2963 return true;
2967 * Define the course completion structure
2969 * @return array Array of restore_path_element
2971 protected function define_structure() {
2973 // To know if we are including user completion info
2974 $userinfo = $this->get_setting_value('userscompletion');
2976 $paths = array();
2977 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2978 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2980 if ($userinfo) {
2981 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2982 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2985 return $paths;
2990 * Process course completion criteria
2992 * @global moodle_database $DB
2993 * @param stdClass $data
2995 public function process_course_completion_criteria($data) {
2996 global $DB;
2998 $data = (object)$data;
2999 $data->course = $this->get_courseid();
3001 // Apply the date offset to the time end field
3002 $data->timeend = $this->apply_date_offset($data->timeend);
3004 // Map the role from the criteria
3005 if (isset($data->role) && $data->role != '') {
3006 // Newer backups should include roleshortname, which makes this much easier.
3007 if (!empty($data->roleshortname)) {
3008 $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
3009 if (!$roleinstanceid) {
3010 $this->log(
3011 'Could not match the role shortname in course_completion_criteria, so skipping',
3012 backup::LOG_DEBUG
3014 return;
3016 $data->role = $roleinstanceid;
3017 } else {
3018 $data->role = $this->get_mappingid('role', $data->role);
3021 // Check we have an id, otherwise it causes all sorts of bugs.
3022 if (!$data->role) {
3023 $this->log(
3024 'Could not match role in course_completion_criteria, so skipping',
3025 backup::LOG_DEBUG
3027 return;
3031 // If the completion criteria is for a module we need to map the module instance
3032 // to the new module id.
3033 if (!empty($data->moduleinstance) && !empty($data->module)) {
3034 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
3035 if (empty($data->moduleinstance)) {
3036 $this->log(
3037 'Could not match the module instance in course_completion_criteria, so skipping',
3038 backup::LOG_DEBUG
3040 return;
3042 } else {
3043 $data->module = null;
3044 $data->moduleinstance = null;
3047 // We backup the course shortname rather than the ID so that we can match back to the course
3048 if (!empty($data->courseinstanceshortname)) {
3049 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
3050 if (!$courseinstanceid) {
3051 $this->log(
3052 'Could not match the course instance in course_completion_criteria, so skipping',
3053 backup::LOG_DEBUG
3055 return;
3057 } else {
3058 $courseinstanceid = null;
3060 $data->courseinstance = $courseinstanceid;
3062 $params = array(
3063 'course' => $data->course,
3064 'criteriatype' => $data->criteriatype,
3065 'enrolperiod' => $data->enrolperiod,
3066 'courseinstance' => $data->courseinstance,
3067 'module' => $data->module,
3068 'moduleinstance' => $data->moduleinstance,
3069 'timeend' => $data->timeend,
3070 'gradepass' => $data->gradepass,
3071 'role' => $data->role
3073 $newid = $DB->insert_record('course_completion_criteria', $params);
3074 $this->set_mapping('course_completion_criteria', $data->id, $newid);
3078 * Processes course compltion criteria complete records
3080 * @global moodle_database $DB
3081 * @param stdClass $data
3083 public function process_course_completion_crit_compl($data) {
3084 global $DB;
3086 $data = (object)$data;
3088 // This may be empty if criteria could not be restored
3089 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
3091 $data->course = $this->get_courseid();
3092 $data->userid = $this->get_mappingid('user', $data->userid);
3094 if (!empty($data->criteriaid) && !empty($data->userid)) {
3095 $params = array(
3096 'userid' => $data->userid,
3097 'course' => $data->course,
3098 'criteriaid' => $data->criteriaid,
3099 'timecompleted' => $data->timecompleted
3101 if (isset($data->gradefinal)) {
3102 $params['gradefinal'] = $data->gradefinal;
3104 if (isset($data->unenroled)) {
3105 $params['unenroled'] = $data->unenroled;
3107 $DB->insert_record('course_completion_crit_compl', $params);
3112 * Process course completions
3114 * @global moodle_database $DB
3115 * @param stdClass $data
3117 public function process_course_completions($data) {
3118 global $DB;
3120 $data = (object)$data;
3122 $data->course = $this->get_courseid();
3123 $data->userid = $this->get_mappingid('user', $data->userid);
3125 if (!empty($data->userid)) {
3126 $params = array(
3127 'userid' => $data->userid,
3128 'course' => $data->course,
3129 'timeenrolled' => $data->timeenrolled,
3130 'timestarted' => $data->timestarted,
3131 'timecompleted' => $data->timecompleted,
3132 'reaggregate' => $data->reaggregate
3135 $existing = $DB->get_record('course_completions', array(
3136 'userid' => $data->userid,
3137 'course' => $data->course
3140 // MDL-46651 - If cron writes out a new record before we get to it
3141 // then we should replace it with the Truth data from the backup.
3142 // This may be obsolete after MDL-48518 is resolved
3143 if ($existing) {
3144 $params['id'] = $existing->id;
3145 $DB->update_record('course_completions', $params);
3146 } else {
3147 $DB->insert_record('course_completions', $params);
3153 * Process course completion aggregate methods
3155 * @global moodle_database $DB
3156 * @param stdClass $data
3158 public function process_course_completion_aggr_methd($data) {
3159 global $DB;
3161 $data = (object)$data;
3163 $data->course = $this->get_courseid();
3165 // Only create the course_completion_aggr_methd records if
3166 // the target course has not them defined. MDL-28180
3167 if (!$DB->record_exists('course_completion_aggr_methd', array(
3168 'course' => $data->course,
3169 'criteriatype' => $data->criteriatype))) {
3170 $params = array(
3171 'course' => $data->course,
3172 'criteriatype' => $data->criteriatype,
3173 'method' => $data->method,
3174 'value' => $data->value,
3176 $DB->insert_record('course_completion_aggr_methd', $params);
3183 * This structure step restores course logs (cmid = 0), delegating
3184 * the hard work to the corresponding {@link restore_logs_processor} passing the
3185 * collection of {@link restore_log_rule} rules to be observed as they are defined
3186 * by the task. Note this is only executed based in the 'logs' setting.
3188 * NOTE: This is executed by final task, to have all the activities already restored
3190 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
3191 * records are. There are others like 'calendar' and 'upload' that will be handled
3192 * later.
3194 * NOTE: All the missing actions (not able to be restored) are sent to logs for
3195 * debugging purposes
3197 class restore_course_logs_structure_step extends restore_structure_step {
3200 * Conditionally decide if this step should be executed.
3202 * This function checks the following parameter:
3204 * 1. the course/logs.xml file exists
3206 * @return bool true is safe to execute, false otherwise
3208 protected function execute_condition() {
3210 // Check it is included in the backup
3211 $fullpath = $this->task->get_taskbasepath();
3212 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3213 if (!file_exists($fullpath)) {
3214 // Not found, can't restore course logs
3215 return false;
3218 return true;
3221 protected function define_structure() {
3223 $paths = array();
3225 // Simple, one plain level of information contains them
3226 $paths[] = new restore_path_element('log', '/logs/log');
3228 return $paths;
3231 protected function process_log($data) {
3232 global $DB;
3234 $data = (object)($data);
3236 // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3238 $data->userid = $this->get_mappingid('user', $data->userid);
3239 $data->course = $this->get_courseid();
3240 $data->cmid = 0;
3242 // For any reason user wasn't remapped ok, stop processing this
3243 if (empty($data->userid)) {
3244 return;
3247 // Everything ready, let's delegate to the restore_logs_processor
3249 // Set some fixed values that will save tons of DB requests
3250 $values = array(
3251 'course' => $this->get_courseid());
3252 // Get instance and process log record
3253 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3255 // If we have data, insert it, else something went wrong in the restore_logs_processor
3256 if ($data) {
3257 if (empty($data->url)) {
3258 $data->url = '';
3260 if (empty($data->info)) {
3261 $data->info = '';
3263 // Store the data in the legacy log table if we are still using it.
3264 $manager = get_log_manager();
3265 if (method_exists($manager, 'legacy_add_to_log')) {
3266 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3267 $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3274 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
3275 * sharing its same structure but modifying the way records are handled
3277 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
3279 protected function process_log($data) {
3280 global $DB;
3282 $data = (object)($data);
3284 // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3286 $data->userid = $this->get_mappingid('user', $data->userid);
3287 $data->course = $this->get_courseid();
3288 $data->cmid = $this->task->get_moduleid();
3290 // For any reason user wasn't remapped ok, stop processing this
3291 if (empty($data->userid)) {
3292 return;
3295 // Everything ready, let's delegate to the restore_logs_processor
3297 // Set some fixed values that will save tons of DB requests
3298 $values = array(
3299 'course' => $this->get_courseid(),
3300 'course_module' => $this->task->get_moduleid(),
3301 $this->task->get_modulename() => $this->task->get_activityid());
3302 // Get instance and process log record
3303 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3305 // If we have data, insert it, else something went wrong in the restore_logs_processor
3306 if ($data) {
3307 if (empty($data->url)) {
3308 $data->url = '';
3310 if (empty($data->info)) {
3311 $data->info = '';
3313 // Store the data in the legacy log table if we are still using it.
3314 $manager = get_log_manager();
3315 if (method_exists($manager, 'legacy_add_to_log')) {
3316 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3317 $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3324 * Structure step in charge of restoring the logstores.xml file for the course logs.
3326 * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3327 * it, for logs belonging to the course level.
3329 class restore_course_logstores_structure_step extends restore_structure_step {
3332 * Conditionally decide if this step should be executed.
3334 * This function checks the following parameter:
3336 * 1. the logstores.xml file exists
3338 * @return bool true is safe to execute, false otherwise
3340 protected function execute_condition() {
3342 // Check it is included in the backup.
3343 $fullpath = $this->task->get_taskbasepath();
3344 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3345 if (!file_exists($fullpath)) {
3346 // Not found, can't restore logstores.xml information.
3347 return false;
3350 return true;
3354 * Return the elements to be processed on restore of logstores.
3356 * @return restore_path_element[] array of elements to be processed on restore.
3358 protected function define_structure() {
3360 $paths = array();
3362 $logstore = new restore_path_element('logstore', '/logstores/logstore');
3363 $paths[] = $logstore;
3365 // Add logstore subplugin support to the 'logstore' element.
3366 $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3368 return array($logstore);
3372 * Process the 'logstore' element,
3374 * Note: This is empty by definition in backup, because stores do not share any
3375 * data between them, so there is nothing to process here.
3377 * @param array $data element data
3379 protected function process_logstore($data) {
3380 return;
3385 * Structure step in charge of restoring the logstores.xml file for the activity logs.
3387 * Note: Activity structure is completely equivalent to the course one, so just extend it.
3389 class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3393 * Restore course competencies structure step.
3395 class restore_course_competencies_structure_step extends restore_structure_step {
3398 * Returns the structure.
3400 * @return array
3402 protected function define_structure() {
3403 $userinfo = $this->get_setting_value('users');
3404 $paths = array(
3405 new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3406 new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3408 if ($userinfo) {
3409 $paths[] = new restore_path_element('user_competency_course',
3410 '/course_competencies/user_competencies/user_competency');
3412 return $paths;
3416 * Process a course competency settings.
3418 * @param array $data The data.
3420 public function process_course_competency_settings($data) {
3421 global $DB;
3422 $data = (object) $data;
3424 // We do not restore the course settings during merge.
3425 $target = $this->get_task()->get_target();
3426 if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) {
3427 return;
3430 $courseid = $this->task->get_courseid();
3431 $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3432 array('courseid' => $courseid));
3434 // Strangely the course settings already exist, let's just leave them as is then.
3435 if ($exists) {
3436 $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING);
3437 return;
3440 $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3441 $settings = new \core_competency\course_competency_settings(0, $data);
3442 $settings->create();
3446 * Process a course competency.
3448 * @param array $data The data.
3450 public function process_course_competency($data) {
3451 $data = (object) $data;
3453 // Mapping the competency by ID numbers.
3454 $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3455 if (!$framework) {
3456 return;
3458 $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3459 'competencyframeworkid' => $framework->get('id')));
3460 if (!$competency) {
3461 return;
3463 $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get('id'));
3465 $params = array(
3466 'competencyid' => $competency->get('id'),
3467 'courseid' => $this->task->get_courseid()
3469 $query = 'competencyid = :competencyid AND courseid = :courseid';
3470 $existing = \core_competency\course_competency::record_exists_select($query, $params);
3472 if (!$existing) {
3473 // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3474 $record = (object) $params;
3475 $record->ruleoutcome = $data->ruleoutcome;
3476 $coursecompetency = new \core_competency\course_competency(0, $record);
3477 $coursecompetency->create();
3482 * Process the user competency course.
3484 * @param array $data The data.
3486 public function process_user_competency_course($data) {
3487 global $USER, $DB;
3488 $data = (object) $data;
3490 $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid);
3491 if (!$data->competencyid) {
3492 // This is strange, the competency does not belong to the course.
3493 return;
3494 } else if ($data->grade === null) {
3495 // We do not need to do anything when there is no grade.
3496 return;
3499 $data->userid = $this->get_mappingid('user', $data->userid);
3500 $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
3502 // The method add_evidence also sets the course rating.
3503 \core_competency\api::add_evidence($data->userid,
3504 $data->competencyid,
3505 $this->task->get_contextid(),
3506 \core_competency\evidence::ACTION_OVERRIDE,
3507 'evidence_courserestored',
3508 'core_competency',
3509 $shortname,
3510 false,
3511 null,
3512 $data->grade,
3513 $USER->id);
3517 * Execute conditions.
3519 * @return bool
3521 protected function execute_condition() {
3523 // Do not execute if competencies are not included.
3524 if (!$this->get_setting_value('competencies')) {
3525 return false;
3528 // Do not execute if the competencies XML file is not found.
3529 $fullpath = $this->task->get_taskbasepath();
3530 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3531 if (!file_exists($fullpath)) {
3532 return false;
3535 return true;
3540 * Restore activity competencies structure step.
3542 class restore_activity_competencies_structure_step extends restore_structure_step {
3545 * Defines the structure.
3547 * @return array
3549 protected function define_structure() {
3550 $paths = array(
3551 new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3553 return $paths;
3557 * Process a course module competency.
3559 * @param array $data The data.
3561 public function process_course_module_competency($data) {
3562 $data = (object) $data;
3564 // Mapping the competency by ID numbers.
3565 $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3566 if (!$framework) {
3567 return;
3569 $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3570 'competencyframeworkid' => $framework->get('id')));
3571 if (!$competency) {
3572 return;
3575 $params = array(
3576 'competencyid' => $competency->get('id'),
3577 'cmid' => $this->task->get_moduleid()
3579 $query = 'competencyid = :competencyid AND cmid = :cmid';
3580 $existing = \core_competency\course_module_competency::record_exists_select($query, $params);
3582 if (!$existing) {
3583 // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3584 $record = (object) $params;
3585 $record->ruleoutcome = $data->ruleoutcome;
3586 $coursemodulecompetency = new \core_competency\course_module_competency(0, $record);
3587 $coursemodulecompetency->create();
3592 * Execute conditions.
3594 * @return bool
3596 protected function execute_condition() {
3598 // Do not execute if competencies are not included.
3599 if (!$this->get_setting_value('competencies')) {
3600 return false;
3603 // Do not execute if the competencies XML file is not found.
3604 $fullpath = $this->task->get_taskbasepath();
3605 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3606 if (!file_exists($fullpath)) {
3607 return false;
3610 return true;
3615 * Defines the restore step for advanced grading methods attached to the activity module
3617 class restore_activity_grading_structure_step extends restore_structure_step {
3620 * This step is executed only if the grading file is present
3622 protected function execute_condition() {
3624 if ($this->get_courseid() == SITEID) {
3625 return false;
3628 $fullpath = $this->task->get_taskbasepath();
3629 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3630 if (!file_exists($fullpath)) {
3631 return false;
3634 return true;
3639 * Declares paths in the grading.xml file we are interested in
3641 protected function define_structure() {
3643 $paths = array();
3644 $userinfo = $this->get_setting_value('userinfo');
3646 $area = new restore_path_element('grading_area', '/areas/area');
3647 $paths[] = $area;
3648 // attach local plugin stucture to $area element
3649 $this->add_plugin_structure('local', $area);
3651 $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
3652 $paths[] = $definition;
3653 $this->add_plugin_structure('gradingform', $definition);
3654 // attach local plugin stucture to $definition element
3655 $this->add_plugin_structure('local', $definition);
3658 if ($userinfo) {
3659 $instance = new restore_path_element('grading_instance',
3660 '/areas/area/definitions/definition/instances/instance');
3661 $paths[] = $instance;
3662 $this->add_plugin_structure('gradingform', $instance);
3663 // attach local plugin stucture to $intance element
3664 $this->add_plugin_structure('local', $instance);
3667 return $paths;
3671 * Processes one grading area element
3673 * @param array $data element data
3675 protected function process_grading_area($data) {
3676 global $DB;
3678 $task = $this->get_task();
3679 $data = (object)$data;
3680 $oldid = $data->id;
3681 $data->component = 'mod_'.$task->get_modulename();
3682 $data->contextid = $task->get_contextid();
3684 $newid = $DB->insert_record('grading_areas', $data);
3685 $this->set_mapping('grading_area', $oldid, $newid);
3689 * Processes one grading definition element
3691 * @param array $data element data
3693 protected function process_grading_definition($data) {
3694 global $DB;
3696 $task = $this->get_task();
3697 $data = (object)$data;
3698 $oldid = $data->id;
3699 $data->areaid = $this->get_new_parentid('grading_area');
3700 $data->copiedfromid = null;
3701 $data->timecreated = time();
3702 $data->usercreated = $task->get_userid();
3703 $data->timemodified = $data->timecreated;
3704 $data->usermodified = $data->usercreated;
3706 $newid = $DB->insert_record('grading_definitions', $data);
3707 $this->set_mapping('grading_definition', $oldid, $newid, true);
3711 * Processes one grading form instance element
3713 * @param array $data element data
3715 protected function process_grading_instance($data) {
3716 global $DB;
3718 $data = (object)$data;
3720 // new form definition id
3721 $newformid = $this->get_new_parentid('grading_definition');
3723 // get the name of the area we are restoring to
3724 $sql = "SELECT ga.areaname
3725 FROM {grading_definitions} gd
3726 JOIN {grading_areas} ga ON gd.areaid = ga.id
3727 WHERE gd.id = ?";
3728 $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
3730 // get the mapped itemid - the activity module is expected to define the mappings
3731 // for each gradable area
3732 $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
3734 $oldid = $data->id;
3735 $data->definitionid = $newformid;
3736 $data->raterid = $this->get_mappingid('user', $data->raterid);
3737 $data->itemid = $newitemid;
3739 $newid = $DB->insert_record('grading_instances', $data);
3740 $this->set_mapping('grading_instance', $oldid, $newid);
3744 * Final operations when the database records are inserted
3746 protected function after_execute() {
3747 // Add files embedded into the definition description
3748 $this->add_related_files('grading', 'description', 'grading_definition');
3754 * This structure step restores the grade items associated with one activity
3755 * All the grade items are made child of the "course" grade item but the original
3756 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3757 * the complete gradebook (categories and calculations), that information is
3758 * available there
3760 class restore_activity_grades_structure_step extends restore_structure_step {
3763 * No grades in front page.
3764 * @return bool
3766 protected function execute_condition() {
3767 return ($this->get_courseid() != SITEID);
3770 protected function define_structure() {
3772 $paths = array();
3773 $userinfo = $this->get_setting_value('userinfo');
3775 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3776 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3777 if ($userinfo) {
3778 $paths[] = new restore_path_element('grade_grade',
3779 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
3781 return $paths;
3784 protected function process_grade_item($data) {
3785 global $DB;
3787 $data = (object)($data);
3788 $oldid = $data->id; // We'll need these later
3789 $oldparentid = $data->categoryid;
3790 $courseid = $this->get_courseid();
3792 $idnumber = null;
3793 if (!empty($data->idnumber)) {
3794 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
3795 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
3796 // so the best is to keep the ones already in the gradebook
3797 // Potential problem: duplicates if same items are restored more than once. :-(
3798 // This needs to be fixed in some way (outcomes & activities with multiple items)
3799 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
3800 // In any case, verify always for uniqueness
3801 $sql = "SELECT cm.id
3802 FROM {course_modules} cm
3803 WHERE cm.course = :courseid AND
3804 cm.idnumber = :idnumber AND
3805 cm.id <> :cmid";
3806 $params = array(
3807 'courseid' => $courseid,
3808 'idnumber' => $data->idnumber,
3809 'cmid' => $this->task->get_moduleid()
3811 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
3812 $idnumber = $data->idnumber;
3816 if (!empty($data->categoryid)) {
3817 // If the grade category id of the grade item being restored belongs to this course
3818 // then it is a fair assumption that this is the correct grade category for the activity
3819 // and we should leave it in place, if not then unset it.
3820 // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
3821 $conditions = array('id' => $data->categoryid, 'courseid' => $courseid);
3822 if (!$this->task->is_samesite() || !$DB->record_exists('grade_categories', $conditions)) {
3823 unset($data->categoryid);
3827 unset($data->id);
3828 $data->courseid = $this->get_courseid();
3829 $data->iteminstance = $this->task->get_activityid();
3830 $data->idnumber = $idnumber;
3831 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
3832 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
3834 $gradeitem = new grade_item($data, false);
3835 $gradeitem->insert('restore');
3837 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
3838 $gradeitem->sortorder = $data->sortorder;
3839 $gradeitem->update('restore');
3841 // Set mapping, saving the original category id into parentitemid
3842 // gradebook restore (final task) will need it to reorganise items
3843 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
3846 protected function process_grade_grade($data) {
3847 global $CFG;
3849 require_once($CFG->libdir . '/grade/constants.php');
3851 $data = (object)($data);
3852 $olduserid = $data->userid;
3853 $oldid = $data->id;
3854 unset($data->id);
3856 $data->itemid = $this->get_new_parentid('grade_item');
3858 $data->userid = $this->get_mappingid('user', $data->userid, null);
3859 if (!empty($data->userid)) {
3860 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
3861 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
3863 $grade = new grade_grade($data, false);
3864 $grade->insert('restore');
3866 $this->set_mapping('grade_grades', $oldid, $grade->id, true);
3868 $this->add_related_files(
3869 GRADE_FILE_COMPONENT,
3870 GRADE_FEEDBACK_FILEAREA,
3871 'grade_grades',
3872 null,
3873 $oldid
3875 } else {
3876 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
3881 * process activity grade_letters. Note that, while these are possible,
3882 * because grade_letters are contextid based, in practice, only course
3883 * context letters can be defined. So we keep here this method knowing
3884 * it won't be executed ever. gradebook restore will restore course letters.
3886 protected function process_grade_letter($data) {
3887 global $DB;
3889 $data['contextid'] = $this->task->get_contextid();
3890 $gradeletter = (object)$data;
3892 // Check if it exists before adding it
3893 unset($data['id']);
3894 if (!$DB->record_exists('grade_letters', $data)) {
3895 $newitemid = $DB->insert_record('grade_letters', $gradeletter);
3897 // no need to save any grade_letter mapping
3900 public function after_restore() {
3901 // Fix grade item's sortorder after restore, as it might have duplicates.
3902 $courseid = $this->get_task()->get_courseid();
3903 grade_item::fix_duplicate_sortorder($courseid);
3908 * Step in charge of restoring the grade history of an activity.
3910 * This step is added to the task regardless of the setting 'grade_histories'.
3911 * The reason is to allow for a more flexible step in case the logic needs to be
3912 * split accross different settings to control the history of items and/or grades.
3914 class restore_activity_grade_history_structure_step extends restore_structure_step {
3917 * This step is executed only if the grade history file is present.
3919 protected function execute_condition() {
3921 if ($this->get_courseid() == SITEID) {
3922 return false;
3925 $fullpath = $this->task->get_taskbasepath();
3926 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3927 if (!file_exists($fullpath)) {
3928 return false;
3930 return true;
3933 protected function define_structure() {
3934 $paths = array();
3936 // Settings to use.
3937 $userinfo = $this->get_setting_value('userinfo');
3938 $history = $this->get_setting_value('grade_histories');
3940 if ($userinfo && $history) {
3941 $paths[] = new restore_path_element('grade_grade',
3942 '/grade_history/grade_grades/grade_grade');
3945 return $paths;
3948 protected function process_grade_grade($data) {
3949 global $CFG, $DB;
3951 require_once($CFG->libdir . '/grade/constants.php');
3953 $data = (object) $data;
3954 $oldhistoryid = $data->id;
3955 $olduserid = $data->userid;
3956 unset($data->id);
3958 $data->userid = $this->get_mappingid('user', $data->userid, null);
3959 if (!empty($data->userid)) {
3960 // Do not apply the date offsets as this is history.
3961 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
3962 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
3963 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
3964 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
3966 $newhistoryid = $DB->insert_record('grade_grades_history', $data);
3968 $this->set_mapping('grade_grades_history', $oldhistoryid, $newhistoryid, true);
3970 $this->add_related_files(
3971 GRADE_FILE_COMPONENT,
3972 GRADE_HISTORY_FEEDBACK_FILEAREA,
3973 'grade_grades_history',
3974 null,
3975 $oldhistoryid
3977 } else {
3978 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
3979 $this->log($message, backup::LOG_DEBUG);
3985 * This structure steps restores one instance + positions of one block
3986 * Note: Positions corresponding to one existing context are restored
3987 * here, but all the ones having unknown contexts are sent to backup_ids
3988 * for a later chance to be restored at the end (final task)
3990 class restore_block_instance_structure_step extends restore_structure_step {
3992 protected function define_structure() {
3994 $paths = array();
3996 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
3997 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
3999 return $paths;
4002 public function process_block($data) {
4003 global $DB, $CFG;
4005 $data = (object)$data; // Handy
4006 $oldcontextid = $data->contextid;
4007 $oldid = $data->id;
4008 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
4010 // Look for the parent contextid
4011 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
4012 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
4015 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
4016 // If there is already one block of that type in the parent context
4017 // and the block is not multiple, stop processing
4018 // Use blockslib loader / method executor
4019 if (!$bi = block_instance($data->blockname)) {
4020 return false;
4023 if (!$bi->instance_allow_multiple()) {
4024 // The block cannot be added twice, so we will check if the same block is already being
4025 // displayed on the same page. For this, rather than mocking a page and using the block_manager
4026 // we use a similar query to the one in block_manager::load_blocks(), this will give us
4027 // a very good idea of the blocks already displayed in the context.
4028 $params = array(
4029 'blockname' => $data->blockname
4032 // Context matching test.
4033 $context = context::instance_by_id($data->parentcontextid);
4034 $contextsql = 'bi.parentcontextid = :contextid';
4035 $params['contextid'] = $context->id;
4037 $parentcontextids = $context->get_parent_context_ids();
4038 if ($parentcontextids) {
4039 list($parentcontextsql, $parentcontextparams) =
4040 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
4041 $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
4042 $params = array_merge($params, $parentcontextparams);
4045 // Page type pattern test.
4046 $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
4047 list($pagetypepatternsql, $pagetypepatternparams) =
4048 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
4049 $params = array_merge($params, $pagetypepatternparams);
4051 // Sub page pattern test.
4052 $subpagepatternsql = 'bi.subpagepattern IS NULL';
4053 if ($data->subpagepattern !== null) {
4054 $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
4055 $params['subpagepattern'] = $data->subpagepattern;
4058 $exists = $DB->record_exists_sql("SELECT bi.id
4059 FROM {block_instances} bi
4060 JOIN {block} b ON b.name = bi.blockname
4061 WHERE bi.blockname = :blockname
4062 AND $contextsql
4063 AND bi.pagetypepattern $pagetypepatternsql
4064 AND $subpagepatternsql", $params);
4065 if ($exists) {
4066 // There is at least one very similar block visible on the page where we
4067 // are trying to restore the block. In these circumstances the block API
4068 // would not allow the user to add another instance of the block, so we
4069 // apply the same rule here.
4070 return false;
4074 // If there is already one block of that type in the parent context
4075 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
4076 // stop processing
4077 $params = array(
4078 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
4079 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
4080 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
4081 if ($birecs = $DB->get_records('block_instances', $params)) {
4082 foreach($birecs as $birec) {
4083 if ($birec->configdata == $data->configdata) {
4084 return false;
4089 // Set task old contextid, blockid and blockname once we know them
4090 $this->task->set_old_contextid($oldcontextid);
4091 $this->task->set_old_blockid($oldid);
4092 $this->task->set_blockname($data->blockname);
4094 // Let's look for anything within configdata neededing processing
4095 // (nulls and uses of legacy file.php)
4096 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
4097 $configdata = (array)unserialize(base64_decode($data->configdata));
4098 foreach ($configdata as $attribute => $value) {
4099 if (in_array($attribute, $attrstotransform)) {
4100 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
4103 $data->configdata = base64_encode(serialize((object)$configdata));
4106 // Set timecreated, timemodified if not included (older backup).
4107 if (empty($data->timecreated)) {
4108 $data->timecreated = time();
4110 if (empty($data->timemodified)) {
4111 $data->timemodified = $data->timecreated;
4114 // Create the block instance
4115 $newitemid = $DB->insert_record('block_instances', $data);
4116 // Save the mapping (with restorefiles support)
4117 $this->set_mapping('block_instance', $oldid, $newitemid, true);
4118 // Create the block context
4119 $newcontextid = context_block::instance($newitemid)->id;
4120 // Save the block contexts mapping and sent it to task
4121 $this->set_mapping('context', $oldcontextid, $newcontextid);
4122 $this->task->set_contextid($newcontextid);
4123 $this->task->set_blockid($newitemid);
4125 // Restore block fileareas if declared
4126 $component = 'block_' . $this->task->get_blockname();
4127 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
4128 $this->add_related_files($component, $filearea, null);
4131 // Process block positions, creating them or accumulating for final step
4132 foreach($positions as $position) {
4133 $position = (object)$position;
4134 $position->blockinstanceid = $newitemid; // The instance is always the restored one
4135 // If position is for one already mapped (known) contextid
4136 // process it now, creating the position
4137 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
4138 $position->contextid = $newpositionctxid;
4139 // Create the block position
4140 $DB->insert_record('block_positions', $position);
4142 // The position belongs to an unknown context, send it to backup_ids
4143 // to process them as part of the final steps of restore. We send the
4144 // whole $position object there, hence use the low level method.
4145 } else {
4146 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
4153 * Structure step to restore common course_module information
4155 * This step will process the module.xml file for one activity, in order to restore
4156 * the corresponding information to the course_modules table, skipping various bits
4157 * of information based on CFG settings (groupings, completion...) in order to fullfill
4158 * all the reqs to be able to create the context to be used by all the rest of steps
4159 * in the activity restore task
4161 class restore_module_structure_step extends restore_structure_step {
4163 protected function define_structure() {
4164 global $CFG;
4166 $paths = array();
4168 $module = new restore_path_element('module', '/module');
4169 $paths[] = $module;
4170 if ($CFG->enableavailability) {
4171 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
4172 $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
4175 $paths[] = new restore_path_element('tag', '/module/tags/tag');
4177 // Apply for 'format' plugins optional paths at module level
4178 $this->add_plugin_structure('format', $module);
4180 // Apply for 'plagiarism' plugins optional paths at module level
4181 $this->add_plugin_structure('plagiarism', $module);
4183 // Apply for 'local' plugins optional paths at module level
4184 $this->add_plugin_structure('local', $module);
4186 // Apply for 'admin tool' plugins optional paths at module level.
4187 $this->add_plugin_structure('tool', $module);
4189 return $paths;
4192 protected function process_module($data) {
4193 global $CFG, $DB;
4195 $data = (object)$data;
4196 $oldid = $data->id;
4197 $this->task->set_old_moduleversion($data->version);
4199 $data->course = $this->task->get_courseid();
4200 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
4201 // Map section (first try by course_section mapping match. Useful in course and section restores)
4202 $data->section = $this->get_mappingid('course_section', $data->sectionid);
4203 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
4204 $params = array(
4205 'course' => $this->get_courseid(),
4206 'section' => $data->sectionnumber);
4207 $data->section = $DB->get_field('course_sections', 'id', $params);
4209 if (!$data->section) { // sectionnumber failed, try to get first section in course
4210 $params = array(
4211 'course' => $this->get_courseid());
4212 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
4214 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
4215 $sectionrec = array(
4216 'course' => $this->get_courseid(),
4217 'section' => 0,
4218 'timemodified' => time());
4219 $DB->insert_record('course_sections', $sectionrec); // section 0
4220 $sectionrec = array(
4221 'course' => $this->get_courseid(),
4222 'section' => 1,
4223 'timemodified' => time());
4224 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
4226 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
4227 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
4228 $data->idnumber = '';
4230 if (empty($CFG->enablecompletion)) { // completion
4231 $data->completion = 0;
4232 $data->completiongradeitemnumber = null;
4233 $data->completionview = 0;
4234 $data->completionexpected = 0;
4235 } else {
4236 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
4238 if (empty($CFG->enableavailability)) {
4239 $data->availability = null;
4241 // Backups that did not include showdescription, set it to default 0
4242 // (this is not totally necessary as it has a db default, but just to
4243 // be explicit).
4244 if (!isset($data->showdescription)) {
4245 $data->showdescription = 0;
4247 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
4249 if (empty($data->availability)) {
4250 // If there are legacy availablility data fields (and no new format data),
4251 // convert the old fields.
4252 $data->availability = \core_availability\info::convert_legacy_fields(
4253 $data, false);
4254 } else if (!empty($data->groupmembersonly)) {
4255 // There is current availability data, but it still has groupmembersonly
4256 // as well (2.7 backups), convert just that part.
4257 require_once($CFG->dirroot . '/lib/db/upgradelib.php');
4258 $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
4261 // course_module record ready, insert it
4262 $newitemid = $DB->insert_record('course_modules', $data);
4263 // save mapping
4264 $this->set_mapping('course_module', $oldid, $newitemid);
4265 // set the new course_module id in the task
4266 $this->task->set_moduleid($newitemid);
4267 // we can now create the context safely
4268 $ctxid = context_module::instance($newitemid)->id;
4269 // set the new context id in the task
4270 $this->task->set_contextid($ctxid);
4271 // update sequence field in course_section
4272 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
4273 $sequence .= ',' . $newitemid;
4274 } else {
4275 $sequence = $newitemid;
4278 $updatesection = new \stdClass();
4279 $updatesection->id = $data->section;
4280 $updatesection->sequence = $sequence;
4281 $updatesection->timemodified = time();
4282 $DB->update_record('course_sections', $updatesection);
4284 // If there is the legacy showavailability data, store this for later use.
4285 // (This data is not present when restoring 'new' backups.)
4286 if (isset($data->showavailability)) {
4287 // Cache the showavailability flag using the backup_ids data field.
4288 restore_dbops::set_backup_ids_record($this->get_restoreid(),
4289 'module_showavailability', $newitemid, 0, null,
4290 (object)array('showavailability' => $data->showavailability));
4295 * Fetch all the existing because tag_set() deletes them
4296 * so everything must be reinserted on each call.
4298 * @param stdClass $data Record data
4300 protected function process_tag($data) {
4301 global $CFG;
4303 $data = (object)$data;
4305 if (core_tag_tag::is_enabled('core', 'course_modules')) {
4306 $modcontext = context::instance_by_id($this->task->get_contextid());
4307 $instanceid = $this->task->get_moduleid();
4309 core_tag_tag::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname);
4314 * Process the legacy availability table record. This table does not exist
4315 * in Moodle 2.7+ but we still support restore.
4317 * @param stdClass $data Record data
4319 protected function process_availability($data) {
4320 $data = (object)$data;
4321 // Simply going to store the whole availability record now, we'll process
4322 // all them later in the final task (once all activities have been restored)
4323 // Let's call the low level one to be able to store the whole object
4324 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
4325 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
4329 * Process the legacy availability fields table record. This table does not
4330 * exist in Moodle 2.7+ but we still support restore.
4332 * @param stdClass $data Record data
4334 protected function process_availability_field($data) {
4335 global $DB;
4336 $data = (object)$data;
4337 // Mark it is as passed by default
4338 $passed = true;
4339 $customfieldid = null;
4341 // If a customfield has been used in order to pass we must be able to match an existing
4342 // customfield by name (data->customfield) and type (data->customfieldtype)
4343 if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
4344 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
4345 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
4346 $passed = false;
4347 } else if (!empty($data->customfield)) {
4348 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
4349 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
4350 $passed = ($customfieldid !== false);
4353 if ($passed) {
4354 // Create the object to insert into the database
4355 $availfield = new stdClass();
4356 $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
4357 $availfield->userfield = $data->userfield;
4358 $availfield->customfieldid = $customfieldid;
4359 $availfield->operator = $data->operator;
4360 $availfield->value = $data->value;
4362 // Get showavailability option.
4363 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4364 'module_showavailability', $availfield->coursemoduleid);
4365 if (!$showrec) {
4366 // Should not happen.
4367 throw new coding_exception('No matching showavailability record');
4369 $show = $showrec->info->showavailability;
4371 // The $availfieldobject is now in the format used in the old
4372 // system. Interpret this and convert to new system.
4373 $currentvalue = $DB->get_field('course_modules', 'availability',
4374 array('id' => $availfield->coursemoduleid), MUST_EXIST);
4375 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
4376 $currentvalue, $availfield, $show);
4377 $DB->set_field('course_modules', 'availability', $newvalue,
4378 array('id' => $availfield->coursemoduleid));
4382 * This method will be executed after the rest of the restore has been processed.
4384 * Update old tag instance itemid(s).
4386 protected function after_restore() {
4387 global $DB;
4389 $contextid = $this->task->get_contextid();
4390 $instanceid = $this->task->get_activityid();
4391 $olditemid = $this->task->get_old_activityid();
4393 $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
4398 * Structure step that will process the user activity completion
4399 * information if all these conditions are met:
4400 * - Target site has completion enabled ($CFG->enablecompletion)
4401 * - Activity includes completion info (file_exists)
4403 class restore_userscompletion_structure_step extends restore_structure_step {
4405 * To conditionally decide if this step must be executed
4406 * Note the "settings" conditions are evaluated in the
4407 * corresponding task. Here we check for other conditions
4408 * not being restore settings (files, site settings...)
4410 protected function execute_condition() {
4411 global $CFG;
4413 // Completion disabled in this site, don't execute
4414 if (empty($CFG->enablecompletion)) {
4415 return false;
4418 // No completion on the front page.
4419 if ($this->get_courseid() == SITEID) {
4420 return false;
4423 // No user completion info found, don't execute
4424 $fullpath = $this->task->get_taskbasepath();
4425 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4426 if (!file_exists($fullpath)) {
4427 return false;
4430 // Arrived here, execute the step
4431 return true;
4434 protected function define_structure() {
4436 $paths = array();
4438 $paths[] = new restore_path_element('completion', '/completions/completion');
4440 return $paths;
4443 protected function process_completion($data) {
4444 global $DB;
4446 $data = (object)$data;
4448 $data->coursemoduleid = $this->task->get_moduleid();
4449 $data->userid = $this->get_mappingid('user', $data->userid);
4451 // Find the existing record
4452 $existing = $DB->get_record('course_modules_completion', array(
4453 'coursemoduleid' => $data->coursemoduleid,
4454 'userid' => $data->userid), 'id, timemodified');
4455 // Check we didn't already insert one for this cmid and userid
4456 // (there aren't supposed to be duplicates in that field, but
4457 // it was possible until MDL-28021 was fixed).
4458 if ($existing) {
4459 // Update it to these new values, but only if the time is newer
4460 if ($existing->timemodified < $data->timemodified) {
4461 $data->id = $existing->id;
4462 $DB->update_record('course_modules_completion', $data);
4464 } else {
4465 // Normal entry where it doesn't exist already
4466 $DB->insert_record('course_modules_completion', $data);
4472 * Abstract structure step, parent of all the activity structure steps. Used to support
4473 * the main <activity ...> tag and process it.
4475 abstract class restore_activity_structure_step extends restore_structure_step {
4478 * Adds support for the 'activity' path that is common to all the activities
4479 * and will be processed globally here
4481 protected function prepare_activity_structure($paths) {
4483 $paths[] = new restore_path_element('activity', '/activity');
4485 return $paths;
4489 * Process the activity path, informing the task about various ids, needed later
4491 protected function process_activity($data) {
4492 $data = (object)$data;
4493 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
4494 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
4495 $this->task->set_old_activityid($data->id); // Save old activityid in task
4499 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
4500 * and will adjust the new activity id (the instance) in various places
4502 protected function apply_activity_instance($newitemid) {
4503 global $DB;
4505 $this->task->set_activityid($newitemid); // Save activity id in task
4506 // Apply the id to course_sections->instanceid
4507 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
4508 // Do the mapping for modulename, preparing it for files by oldcontext
4509 $modulename = $this->task->get_modulename();
4510 $oldid = $this->task->get_old_activityid();
4511 $this->set_mapping($modulename, $oldid, $newitemid, true);
4516 * Structure step in charge of creating/mapping all the qcats and qs
4517 * by parsing the questions.xml file and checking it against the
4518 * results calculated by {@link restore_process_categories_and_questions}
4519 * and stored in backup_ids_temp
4521 class restore_create_categories_and_questions extends restore_structure_step {
4523 /** @var array $cachecategory store a question category */
4524 protected $cachedcategory = null;
4526 protected function define_structure() {
4528 $category = new restore_path_element('question_category', '/question_categories/question_category');
4529 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
4530 $hint = new restore_path_element('question_hint',
4531 '/question_categories/question_category/questions/question/question_hints/question_hint');
4533 $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag');
4535 // Apply for 'qtype' plugins optional paths at question level
4536 $this->add_plugin_structure('qtype', $question);
4538 // Apply for 'local' plugins optional paths at question level
4539 $this->add_plugin_structure('local', $question);
4541 return array($category, $question, $hint, $tag);
4544 protected function process_question_category($data) {
4545 global $DB;
4547 $data = (object)$data;
4548 $oldid = $data->id;
4550 // Check we have one mapping for this category
4551 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
4552 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
4555 // Check we have to create the category (newitemid = 0)
4556 if ($mapping->newitemid) {
4557 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4558 // children elements of the 'question_category' one.
4559 $this->set_mapping('question_category', $oldid, $mapping->newitemid);
4560 return; // newitemid != 0, this category is going to be mapped. Nothing to do
4563 // Arrived here, newitemid = 0, we need to create the category
4564 // we'll do it at parentitemid context, but for CONTEXT_MODULE
4565 // categories, that will be created at CONTEXT_COURSE and moved
4566 // to module context later when the activity is created
4567 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
4568 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
4570 $data->contextid = $mapping->parentitemid;
4572 // Before 3.5, question categories could be created at top level.
4573 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
4574 $backuprelease = floatval($this->get_task()->get_info()->backup_release);
4575 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
4576 $backupbuild = (int)$matches[1];
4577 $before35 = false;
4578 if ($backuprelease < 3.5 || $backupbuild < 20180205) {
4579 $before35 = true;
4581 if (empty($mapping->info->parent) && $before35) {
4582 $top = question_get_top_category($data->contextid, true);
4583 $data->parent = $top->id;
4586 if (empty($data->parent)) {
4587 if (!$top = question_get_top_category($data->contextid)) {
4588 $top = question_get_top_category($data->contextid, true);
4589 $this->set_mapping('question_category_created', $oldid, $top->id, false, null, $data->contextid);
4591 $this->set_mapping('question_category', $oldid, $top->id);
4592 } else {
4594 // Before 3.1, the 'stamp' field could be erroneously duplicated.
4595 // From 3.1 onwards, there's a unique index of (contextid, stamp).
4596 // If we encounter a duplicate in an old restore file, just generate a new stamp.
4597 // This is the same as what happens during an upgrade to 3.1+ anyway.
4598 if ($DB->record_exists('question_categories', ['stamp' => $data->stamp, 'contextid' => $data->contextid])) {
4599 $data->stamp = make_unique_id_code();
4602 // The idnumber if it exists also needs to be unique within a context or reset it to null.
4603 if (!empty($data->idnumber) && $DB->record_exists('question_categories',
4604 ['idnumber' => $data->idnumber, 'contextid' => $data->contextid])) {
4605 unset($data->idnumber);
4608 // Let's create the question_category and save mapping.
4609 $newitemid = $DB->insert_record('question_categories', $data);
4610 $this->set_mapping('question_category', $oldid, $newitemid);
4611 // Also annotate them as question_category_created, we need
4612 // that later when remapping parents.
4613 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
4617 protected function process_question($data) {
4618 global $DB;
4620 $data = (object)$data;
4621 $oldid = $data->id;
4623 // Check we have one mapping for this question
4624 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
4625 return; // No mapping = this question doesn't need to be created/mapped
4628 // Get the mapped category (cannot use get_new_parentid() because not
4629 // all the categories have been created, so it is not always available
4630 // Instead we get the mapping for the question->parentitemid because
4631 // we have loaded qcatids there for all parsed questions
4632 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
4634 // In the past, there were some very sloppy values of penalty. Fix them.
4635 if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
4636 $data->penalty = 0.3333333;
4638 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
4639 $data->penalty = 0.6666667;
4641 if ($data->penalty >= 1) {
4642 $data->penalty = 1;
4645 $userid = $this->get_mappingid('user', $data->createdby);
4646 $data->createdby = $userid ? $userid : $this->task->get_userid();
4648 $userid = $this->get_mappingid('user', $data->modifiedby);
4649 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
4651 // With newitemid = 0, let's create the question
4652 if (!$questionmapping->newitemid) {
4654 // The idnumber if it exists also needs to be unique within a category or reset it to null.
4655 if (!empty($data->idnumber) && $DB->record_exists('question',
4656 ['idnumber' => $data->idnumber, 'category' => $data->category])) {
4657 unset($data->idnumber);
4660 if ($data->qtype === 'random') {
4661 // Ensure that this newly created question is considered by
4662 // \qtype_random\task\remove_unused_questions.
4663 $data->hidden = 0;
4666 $newitemid = $DB->insert_record('question', $data);
4667 $this->set_mapping('question', $oldid, $newitemid);
4668 // Also annotate them as question_created, we need
4669 // that later when remapping parents (keeping the old categoryid as parentid)
4670 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
4671 } else {
4672 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4673 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
4674 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
4677 // Note, we don't restore any question files yet
4678 // as far as the CONTEXT_MODULE categories still
4679 // haven't their contexts to be restored to
4680 // The {@link restore_create_question_files}, executed in the final step
4681 // step will be in charge of restoring all the question files
4684 protected function process_question_hint($data) {
4685 global $DB;
4687 $data = (object)$data;
4688 $oldid = $data->id;
4690 // Detect if the question is created or mapped
4691 $oldquestionid = $this->get_old_parentid('question');
4692 $newquestionid = $this->get_new_parentid('question');
4693 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
4695 // If the question has been created by restore, we need to create its question_answers too
4696 if ($questioncreated) {
4697 // Adjust some columns
4698 $data->questionid = $newquestionid;
4699 // Insert record
4700 $newitemid = $DB->insert_record('question_hints', $data);
4702 // The question existed, we need to map the existing question_hints
4703 } else {
4704 // Look in question_hints by hint text matching
4705 $sql = 'SELECT id
4706 FROM {question_hints}
4707 WHERE questionid = ?
4708 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
4709 $params = array($newquestionid, $data->hint);
4710 $newitemid = $DB->get_field_sql($sql, $params);
4712 // Not able to find the hint, let's try cleaning the hint text
4713 // of all the question's hints in DB as slower fallback. MDL-33863.
4714 if (!$newitemid) {
4715 $potentialhints = $DB->get_records('question_hints',
4716 array('questionid' => $newquestionid), '', 'id, hint');
4717 foreach ($potentialhints as $potentialhint) {
4718 // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
4719 $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
4720 $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
4721 if ($cleanhint === $data->hint) {
4722 $newitemid = $data->id;
4727 // If we haven't found the newitemid, something has gone really wrong, question in DB
4728 // is missing hints, exception
4729 if (!$newitemid) {
4730 $info = new stdClass();
4731 $info->filequestionid = $oldquestionid;
4732 $info->dbquestionid = $newquestionid;
4733 $info->hint = $data->hint;
4734 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
4737 // Create mapping (I'm not sure if this is really needed?)
4738 $this->set_mapping('question_hint', $oldid, $newitemid);
4741 protected function process_tag($data) {
4742 global $DB;
4744 $data = (object)$data;
4745 $newquestion = $this->get_new_parentid('question');
4746 $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
4747 if (!$questioncreated) {
4748 // This question already exists in the question bank. Nothing for us to do.
4749 return;
4752 if (core_tag_tag::is_enabled('core_question', 'question')) {
4753 $tagname = $data->rawname;
4754 if (!empty($data->contextid) && $newcontextid = $this->get_mappingid('context', $data->contextid)) {
4755 $tagcontextid = $newcontextid;
4756 } else {
4757 // Get the category, so we can then later get the context.
4758 $categoryid = $this->get_new_parentid('question_category');
4759 if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
4760 $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
4762 $tagcontextid = $this->cachedcategory->contextid;
4764 // Add the tag to the question.
4765 core_tag_tag::add_item_tag('core_question', 'question', $newquestion,
4766 context::instance_by_id($tagcontextid),
4767 $tagname);
4771 protected function after_execute() {
4772 global $DB;
4774 // First of all, recode all the created question_categories->parent fields
4775 $qcats = $DB->get_records('backup_ids_temp', array(
4776 'backupid' => $this->get_restoreid(),
4777 'itemname' => 'question_category_created'));
4778 foreach ($qcats as $qcat) {
4779 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
4780 // Get new parent (mapped or created, so we look in quesiton_category mappings)
4781 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
4782 'backupid' => $this->get_restoreid(),
4783 'itemname' => 'question_category',
4784 'itemid' => $dbcat->parent))) {
4785 // contextids must match always, as far as we always include complete qbanks, just check it
4786 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
4787 if ($dbcat->contextid == $newparentctxid) {
4788 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
4789 } else {
4790 $newparent = 0; // No ctx match for both cats, no parent relationship
4793 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
4794 if (!$newparent && $dbcat->parent) {
4795 $topcat = question_get_top_category($dbcat->contextid, true);
4796 if ($dbcat->parent != $topcat->id) {
4797 $DB->set_field('question_categories', 'parent', $topcat->id, array('id' => $dbcat->id));
4802 // Now, recode all the created question->parent fields
4803 $qs = $DB->get_records('backup_ids_temp', array(
4804 'backupid' => $this->get_restoreid(),
4805 'itemname' => 'question_created'));
4806 foreach ($qs as $q) {
4807 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
4808 // Get new parent (mapped or created, so we look in question mappings)
4809 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
4810 'backupid' => $this->get_restoreid(),
4811 'itemname' => 'question',
4812 'itemid' => $dbq->parent))) {
4813 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
4817 // Note, we don't restore any question files yet
4818 // as far as the CONTEXT_MODULE categories still
4819 // haven't their contexts to be restored to
4820 // The {@link restore_create_question_files}, executed in the final step
4821 // step will be in charge of restoring all the question files
4826 * Execution step that will move all the CONTEXT_MODULE question categories
4827 * created at early stages of restore in course context (because modules weren't
4828 * created yet) to their target module (matching by old-new-contextid mapping)
4830 class restore_move_module_questions_categories extends restore_execution_step {
4832 protected function define_execution() {
4833 global $DB;
4835 $backuprelease = floatval($this->task->get_info()->backup_release);
4836 preg_match('/(\d{8})/', $this->task->get_info()->moodle_release, $matches);
4837 $backupbuild = (int)$matches[1];
4838 $after35 = false;
4839 if ($backuprelease >= 3.5 && $backupbuild > 20180205) {
4840 $after35 = true;
4843 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
4844 foreach ($contexts as $contextid => $contextlevel) {
4845 // Only if context mapping exists (i.e. the module has been restored)
4846 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
4847 // Update all the qcats having their parentitemid set to the original contextid
4848 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid, info
4849 FROM {backup_ids_temp}
4850 WHERE backupid = ?
4851 AND itemname = 'question_category'
4852 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
4853 $top = question_get_top_category($newcontext->newitemid, true);
4854 $oldtopid = 0;
4855 foreach ($modulecats as $modulecat) {
4856 // Before 3.5, question categories could be created at top level.
4857 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
4858 $info = backup_controller_dbops::decode_backup_temp_info($modulecat->info);
4859 if ($after35 && empty($info->parent)) {
4860 $oldtopid = $modulecat->newitemid;
4861 $modulecat->newitemid = $top->id;
4862 } else {
4863 $cat = new stdClass();
4864 $cat->id = $modulecat->newitemid;
4865 $cat->contextid = $newcontext->newitemid;
4866 if (empty($info->parent)) {
4867 $cat->parent = $top->id;
4869 $DB->update_record('question_categories', $cat);
4872 // And set new contextid (and maybe update newitemid) also in question_category mapping (will be
4873 // used by {@link restore_create_question_files} later.
4874 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid,
4875 $modulecat->newitemid, $newcontext->newitemid);
4878 // Now set the parent id for the question categories that were in the top category in the course context
4879 // and have been moved now.
4880 if ($oldtopid) {
4881 $DB->set_field('question_categories', 'parent', $top->id,
4882 array('contextid' => $newcontext->newitemid, 'parent' => $oldtopid));
4890 * Execution step that will create all the question/answers/qtype-specific files for the restored
4891 * questions. It must be executed after {@link restore_move_module_questions_categories}
4892 * because only then each question is in its final category and only then the
4893 * contexts can be determined.
4895 class restore_create_question_files extends restore_execution_step {
4897 /** @var array Question-type specific component items cache. */
4898 private $qtypecomponentscache = array();
4901 * Preform the restore_create_question_files step.
4903 protected function define_execution() {
4904 global $DB;
4906 // Track progress, as this task can take a long time.
4907 $progress = $this->task->get_progress();
4908 $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
4910 // Parentitemids of question_createds in backup_ids_temp are the category it is in.
4911 // MUST use a recordset, as there is no unique key in the first (or any) column.
4912 $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
4913 FROM {backup_ids_temp} bi
4914 JOIN {question} q ON q.id = bi.newitemid
4915 WHERE bi.backupid = ?
4916 AND bi.itemname = 'question_created'
4917 ORDER BY categoryid ASC", array($this->get_restoreid()));
4919 $currentcatid = -1;
4920 foreach ($catqtypes as $categoryid => $row) {
4921 $qtype = $row->qtype;
4923 // Check if we are in a new category.
4924 if ($currentcatid !== $categoryid) {
4925 // Report progress for each category.
4926 $progress->progress();
4928 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4929 'question_category', $categoryid)) {
4930 // Something went really wrong, cannot find the question_category for the question_created records.
4931 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
4932 continue;
4935 // Calculate source and target contexts.
4936 $oldctxid = $qcatmapping->info->contextid;
4937 $newctxid = $qcatmapping->parentitemid;
4939 $this->send_common_files($oldctxid, $newctxid, $progress);
4940 $currentcatid = $categoryid;
4943 $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
4945 $catqtypes->close();
4946 $progress->end_progress();
4950 * Send the common question files to a new context.
4952 * @param int $oldctxid Old context id.
4953 * @param int $newctxid New context id.
4954 * @param \core\progress $progress Progress object to use.
4956 private function send_common_files($oldctxid, $newctxid, $progress) {
4957 // Add common question files (question and question_answer ones).
4958 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
4959 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4960 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
4961 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4962 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
4963 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
4964 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
4965 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
4966 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
4967 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
4968 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
4969 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4970 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
4971 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4972 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
4973 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4977 * Send the question type specific files to a new context.
4979 * @param text $qtype The qtype name to send.
4980 * @param int $oldctxid Old context id.
4981 * @param int $newctxid New context id.
4982 * @param \core\progress $progress Progress object to use.
4984 private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
4985 if (!isset($this->qtypecomponentscache[$qtype])) {
4986 $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
4988 $components = $this->qtypecomponentscache[$qtype];
4989 foreach ($components as $component => $fileareas) {
4990 foreach ($fileareas as $filearea => $mapping) {
4991 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
4992 $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
4999 * Try to restore aliases and references to external files.
5001 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
5002 * We expect that all regular (non-alias) files have already been restored. Make sure
5003 * there is no restore step executed after this one that would call send_files_to_pool() again.
5005 * You may notice we have hardcoded support for Server files, Legacy course files
5006 * and user Private files here at the moment. This could be eventually replaced with a set of
5007 * callbacks in the future if needed.
5009 * @copyright 2012 David Mudrak <david@moodle.com>
5010 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5012 class restore_process_file_aliases_queue extends restore_execution_step {
5014 /** @var array internal cache for {@link choose_repository()} */
5015 private $cachereposbyid = array();
5017 /** @var array internal cache for {@link choose_repository()} */
5018 private $cachereposbytype = array();
5021 * What to do when this step is executed.
5023 protected function define_execution() {
5024 global $DB;
5026 $this->log('processing file aliases queue', backup::LOG_DEBUG);
5028 $fs = get_file_storage();
5030 // Load the queue.
5031 $rs = $DB->get_recordset('backup_ids_temp',
5032 array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'),
5033 '', 'info');
5035 // Iterate over aliases in the queue.
5036 foreach ($rs as $record) {
5037 $info = backup_controller_dbops::decode_backup_temp_info($record->info);
5039 // Try to pick a repository instance that should serve the alias.
5040 $repository = $this->choose_repository($info);
5042 if (is_null($repository)) {
5043 $this->notify_failure($info, 'unable to find a matching repository instance');
5044 continue;
5047 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
5048 // Aliases to Server files and Legacy course files may refer to a file
5049 // contained in the backup file or to some existing file (if we are on the
5050 // same site).
5051 try {
5052 $reference = file_storage::unpack_reference($info->oldfile->reference);
5053 } catch (Exception $e) {
5054 $this->notify_failure($info, 'invalid reference field format');
5055 continue;
5058 // Let's see if the referred source file was also included in the backup.
5059 $candidates = $DB->get_recordset('backup_files_temp', array(
5060 'backupid' => $this->get_restoreid(),
5061 'contextid' => $reference['contextid'],
5062 'component' => $reference['component'],
5063 'filearea' => $reference['filearea'],
5064 'itemid' => $reference['itemid'],
5065 ), '', 'info, newcontextid, newitemid');
5067 $source = null;
5069 foreach ($candidates as $candidate) {
5070 $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
5071 if ($candidateinfo->filename === $reference['filename']
5072 and $candidateinfo->filepath === $reference['filepath']
5073 and !is_null($candidate->newcontextid)
5074 and !is_null($candidate->newitemid) ) {
5075 $source = $candidateinfo;
5076 $source->contextid = $candidate->newcontextid;
5077 $source->itemid = $candidate->newitemid;
5078 break;
5081 $candidates->close();
5083 if ($source) {
5084 // We have an alias that refers to another file also included in
5085 // the backup. Let us change the reference field so that it refers
5086 // to the restored copy of the original file.
5087 $reference = file_storage::pack_reference($source);
5089 // Send the new alias to the filepool.
5090 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5091 $this->notify_success($info);
5092 continue;
5094 } else {
5095 // This is a reference to some moodle file that was not contained in the backup
5096 // file. If we are restoring to the same site, keep the reference untouched
5097 // and restore the alias as is if the referenced file exists.
5098 if ($this->task->is_samesite()) {
5099 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5100 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5101 $reference = file_storage::pack_reference($reference);
5102 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5103 $this->notify_success($info);
5104 continue;
5105 } else {
5106 $this->notify_failure($info, 'referenced file not found');
5107 continue;
5110 // If we are at other site, we can't restore this alias.
5111 } else {
5112 $this->notify_failure($info, 'referenced file not included');
5113 continue;
5117 } else if ($info->oldfile->repositorytype === 'user') {
5118 if ($this->task->is_samesite()) {
5119 // For aliases to user Private files at the same site, we have a chance to check
5120 // if the referenced file still exists.
5121 try {
5122 $reference = file_storage::unpack_reference($info->oldfile->reference);
5123 } catch (Exception $e) {
5124 $this->notify_failure($info, 'invalid reference field format');
5125 continue;
5127 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5128 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5129 $reference = file_storage::pack_reference($reference);
5130 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5131 $this->notify_success($info);
5132 continue;
5133 } else {
5134 $this->notify_failure($info, 'referenced file not found');
5135 continue;
5138 // If we are at other site, we can't restore this alias.
5139 } else {
5140 $this->notify_failure($info, 'restoring at another site');
5141 continue;
5144 } else {
5145 // This is a reference to some external file such as in boxnet or dropbox.
5146 // If we are restoring to the same site, keep the reference untouched and
5147 // restore the alias as is.
5148 if ($this->task->is_samesite()) {
5149 $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
5150 $this->notify_success($info);
5151 continue;
5153 // If we are at other site, we can't restore this alias.
5154 } else {
5155 $this->notify_failure($info, 'restoring at another site');
5156 continue;
5160 $rs->close();
5164 * Choose the repository instance that should handle the alias.
5166 * At the same site, we can rely on repository instance id and we just
5167 * check it still exists. On other site, try to find matching Server files or
5168 * Legacy course files repository instance. Return null if no matching
5169 * repository instance can be found.
5171 * @param stdClass $info
5172 * @return repository|null
5174 private function choose_repository(stdClass $info) {
5175 global $DB, $CFG;
5176 require_once($CFG->dirroot.'/repository/lib.php');
5178 if ($this->task->is_samesite()) {
5179 // We can rely on repository instance id.
5181 if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
5182 return $this->cachereposbyid[$info->oldfile->repositoryid];
5185 $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
5187 try {
5188 $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
5189 return $this->cachereposbyid[$info->oldfile->repositoryid];
5190 } catch (Exception $e) {
5191 $this->cachereposbyid[$info->oldfile->repositoryid] = null;
5192 return null;
5195 } else {
5196 // We can rely on repository type only.
5198 if (empty($info->oldfile->repositorytype)) {
5199 return null;
5202 if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
5203 return $this->cachereposbytype[$info->oldfile->repositorytype];
5206 $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
5208 // Both Server files and Legacy course files repositories have a single
5209 // instance at the system context to use. Let us try to find it.
5210 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
5211 $sql = "SELECT ri.id
5212 FROM {repository} r
5213 JOIN {repository_instances} ri ON ri.typeid = r.id
5214 WHERE r.type = ? AND ri.contextid = ?";
5215 $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
5216 if (empty($ris)) {
5217 return null;
5219 $repoids = array_keys($ris);
5220 $repoid = reset($repoids);
5221 try {
5222 $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
5223 return $this->cachereposbytype[$info->oldfile->repositorytype];
5224 } catch (Exception $e) {
5225 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5226 return null;
5230 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5231 return null;
5236 * Let the user know that the given alias was successfully restored
5238 * @param stdClass $info
5240 private function notify_success(stdClass $info) {
5241 $filedesc = $this->describe_alias($info);
5242 $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
5246 * Let the user know that the given alias can't be restored
5248 * @param stdClass $info
5249 * @param string $reason detailed reason to be logged
5251 private function notify_failure(stdClass $info, $reason = '') {
5252 $filedesc = $this->describe_alias($info);
5253 if ($reason) {
5254 $reason = ' ('.$reason.')';
5256 $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
5257 $this->add_result_item('file_aliases_restore_failures', $filedesc);
5261 * Return a human readable description of the alias file
5263 * @param stdClass $info
5264 * @return string
5266 private function describe_alias(stdClass $info) {
5268 $filedesc = $this->expected_alias_location($info->newfile);
5270 if (!is_null($info->oldfile->source)) {
5271 $filedesc .= ' ('.$info->oldfile->source.')';
5274 return $filedesc;
5278 * Return the expected location of a file
5280 * Please note this may and may not work as a part of URL to pluginfile.php
5281 * (depends on how the given component/filearea deals with the itemid).
5283 * @param stdClass $filerecord
5284 * @return string
5286 private function expected_alias_location($filerecord) {
5288 $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
5289 if (!is_null($filerecord->itemid)) {
5290 $filedesc .= '/'.$filerecord->itemid;
5292 $filedesc .= $filerecord->filepath.$filerecord->filename;
5294 return $filedesc;
5298 * Append a value to the given resultset
5300 * @param string $name name of the result containing a list of values
5301 * @param mixed $value value to add as another item in that result
5303 private function add_result_item($name, $value) {
5305 $results = $this->task->get_results();
5307 if (isset($results[$name])) {
5308 if (!is_array($results[$name])) {
5309 throw new coding_exception('Unable to append a result item into a non-array structure.');
5311 $current = $results[$name];
5312 $current[] = $value;
5313 $this->task->add_result(array($name => $current));
5315 } else {
5316 $this->task->add_result(array($name => array($value)));
5323 * Abstract structure step, to be used by all the activities using core questions stuff
5324 * (like the quiz module), to support qtype plugins, states and sessions
5326 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
5327 /** @var array question_attempt->id to qtype. */
5328 protected $qtypes = array();
5329 /** @var array question_attempt->id to questionid. */
5330 protected $newquestionids = array();
5333 * Attach below $element (usually attempts) the needed restore_path_elements
5334 * to restore question_usages and all they contain.
5336 * If you use the $nameprefix parameter, then you will need to implement some
5337 * extra methods in your class, like
5339 * protected function process_{nameprefix}question_attempt($data) {
5340 * $this->restore_question_usage_worker($data, '{nameprefix}');
5342 * protected function process_{nameprefix}question_attempt($data) {
5343 * $this->restore_question_attempt_worker($data, '{nameprefix}');
5345 * protected function process_{nameprefix}question_attempt_step($data) {
5346 * $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5349 * @param restore_path_element $element the parent element that the usages are stored inside.
5350 * @param array $paths the paths array that is being built.
5351 * @param string $nameprefix should match the prefix passed to the corresponding
5352 * backup_questions_activity_structure_step::add_question_usages call.
5354 protected function add_question_usages($element, &$paths, $nameprefix = '') {
5355 // Check $element is restore_path_element
5356 if (! $element instanceof restore_path_element) {
5357 throw new restore_step_exception('element_must_be_restore_path_element', $element);
5360 // Check $paths is one array
5361 if (!is_array($paths)) {
5362 throw new restore_step_exception('paths_must_be_array', $paths);
5364 $paths[] = new restore_path_element($nameprefix . 'question_usage',
5365 $element->get_path() . "/{$nameprefix}question_usage");
5366 $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5367 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5368 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5369 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5370 true);
5371 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5372 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5376 * Process question_usages
5378 protected function process_question_usage($data) {
5379 $this->restore_question_usage_worker($data, '');
5383 * Process question_attempts
5385 protected function process_question_attempt($data) {
5386 $this->restore_question_attempt_worker($data, '');
5390 * Process question_attempt_steps
5392 protected function process_question_attempt_step($data) {
5393 $this->restore_question_attempt_step_worker($data, '');
5397 * This method does the actual work for process_question_usage or
5398 * process_{nameprefix}_question_usage.
5399 * @param array $data the data from the XML file.
5400 * @param string $nameprefix the element name prefix.
5402 protected function restore_question_usage_worker($data, $nameprefix) {
5403 global $DB;
5405 // Clear our caches.
5406 $this->qtypes = array();
5407 $this->newquestionids = array();
5409 $data = (object)$data;
5410 $oldid = $data->id;
5412 $oldcontextid = $this->get_task()->get_old_contextid();
5413 $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
5415 // Everything ready, insert (no mapping needed)
5416 $newitemid = $DB->insert_record('question_usages', $data);
5418 $this->inform_new_usage_id($newitemid);
5420 $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
5424 * When process_question_usage creates the new usage, it calls this method
5425 * to let the activity link to the new usage. For example, the quiz uses
5426 * this method to set quiz_attempts.uniqueid to the new usage id.
5427 * @param integer $newusageid
5429 abstract protected function inform_new_usage_id($newusageid);
5432 * This method does the actual work for process_question_attempt or
5433 * process_{nameprefix}_question_attempt.
5434 * @param array $data the data from the XML file.
5435 * @param string $nameprefix the element name prefix.
5437 protected function restore_question_attempt_worker($data, $nameprefix) {
5438 global $DB;
5440 $data = (object)$data;
5441 $oldid = $data->id;
5442 $question = $this->get_mapping('question', $data->questionid);
5444 $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
5445 $data->questionid = $question->newitemid;
5446 if (!property_exists($data, 'variant')) {
5447 $data->variant = 1;
5450 if (!property_exists($data, 'maxfraction')) {
5451 $data->maxfraction = 1;
5454 $newitemid = $DB->insert_record('question_attempts', $data);
5456 $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
5457 $this->qtypes[$newitemid] = $question->info->qtype;
5458 $this->newquestionids[$newitemid] = $data->questionid;
5462 * This method does the actual work for process_question_attempt_step or
5463 * process_{nameprefix}_question_attempt_step.
5464 * @param array $data the data from the XML file.
5465 * @param string $nameprefix the element name prefix.
5467 protected function restore_question_attempt_step_worker($data, $nameprefix) {
5468 global $DB;
5470 $data = (object)$data;
5471 $oldid = $data->id;
5473 // Pull out the response data.
5474 $response = array();
5475 if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
5476 foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
5477 $response[$variable['name']] = $variable['value'];
5480 unset($data->response);
5482 $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
5483 $data->userid = $this->get_mappingid('user', $data->userid);
5485 // Everything ready, insert and create mapping (needed by question_sessions)
5486 $newitemid = $DB->insert_record('question_attempt_steps', $data);
5487 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
5489 // Now process the response data.
5490 $response = $this->questions_recode_response_data(
5491 $this->qtypes[$data->questionattemptid],
5492 $this->newquestionids[$data->questionattemptid],
5493 $data->sequencenumber, $response);
5495 foreach ($response as $name => $value) {
5496 $row = new stdClass();
5497 $row->attemptstepid = $newitemid;
5498 $row->name = $name;
5499 $row->value = $value;
5500 $DB->insert_record('question_attempt_step_data', $row, false);
5505 * Recode the respones data for a particular step of an attempt at at particular question.
5506 * @param string $qtype the question type.
5507 * @param int $newquestionid the question id.
5508 * @param int $sequencenumber the sequence number.
5509 * @param array $response the response data to recode.
5511 public function questions_recode_response_data(
5512 $qtype, $newquestionid, $sequencenumber, array $response) {
5513 $qtyperestorer = $this->get_qtype_restorer($qtype);
5514 if ($qtyperestorer) {
5515 $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
5517 return $response;
5521 * Given a list of question->ids, separated by commas, returns the
5522 * recoded list, with all the restore question mappings applied.
5523 * Note: Used by quiz->questions and quiz_attempts->layout
5524 * Note: 0 = page break (unconverted)
5526 protected function questions_recode_layout($layout) {
5527 // Extracts question id from sequence
5528 if ($questionids = explode(',', $layout)) {
5529 foreach ($questionids as $id => $questionid) {
5530 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
5531 $newquestionid = $this->get_mappingid('question', $questionid);
5532 $questionids[$id] = $newquestionid;
5536 return implode(',', $questionids);
5540 * Get the restore_qtype_plugin subclass for a specific question type.
5541 * @param string $qtype e.g. multichoice.
5542 * @return restore_qtype_plugin instance.
5544 protected function get_qtype_restorer($qtype) {
5545 // Build one static cache to store {@link restore_qtype_plugin}
5546 // while we are needing them, just to save zillions of instantiations
5547 // or using static stuff that will break our nice API
5548 static $qtypeplugins = array();
5550 if (!isset($qtypeplugins[$qtype])) {
5551 $classname = 'restore_qtype_' . $qtype . '_plugin';
5552 if (class_exists($classname)) {
5553 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
5554 } else {
5555 $qtypeplugins[$qtype] = null;
5558 return $qtypeplugins[$qtype];
5561 protected function after_execute() {
5562 parent::after_execute();
5564 // Restore any files belonging to responses.
5565 foreach (question_engine::get_all_response_file_areas() as $filearea) {
5566 $this->add_related_files('question', $filearea, 'question_attempt_step');
5571 * Attach below $element (usually attempts) the needed restore_path_elements
5572 * to restore question attempt data from Moodle 2.0.
5574 * When using this method, the parent element ($element) must be defined with
5575 * $grouped = true. Then, in that elements process method, you must call
5576 * {@link process_legacy_attempt_data()} with the groupded data. See, for
5577 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
5578 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
5579 * @param array $paths the paths array that is being built to describe the
5580 * structure.
5582 protected function add_legacy_question_attempt_data($element, &$paths) {
5583 global $CFG;
5584 require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
5586 // Check $element is restore_path_element
5587 if (!($element instanceof restore_path_element)) {
5588 throw new restore_step_exception('element_must_be_restore_path_element', $element);
5590 // Check $paths is one array
5591 if (!is_array($paths)) {
5592 throw new restore_step_exception('paths_must_be_array', $paths);
5595 $paths[] = new restore_path_element('question_state',
5596 $element->get_path() . '/states/state');
5597 $paths[] = new restore_path_element('question_session',
5598 $element->get_path() . '/sessions/session');
5601 protected function get_attempt_upgrader() {
5602 if (empty($this->attemptupgrader)) {
5603 $this->attemptupgrader = new question_engine_attempt_upgrader();
5604 $this->attemptupgrader->prepare_to_restore();
5606 return $this->attemptupgrader;
5610 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
5611 * @param object $data contains all the grouped attempt data to process.
5612 * @param pbject $quiz data about the activity the attempts belong to. Required
5613 * fields are (basically this only works for the quiz module):
5614 * oldquestions => list of question ids in this activity - using old ids.
5615 * preferredbehaviour => the behaviour to use for questionattempts.
5617 protected function process_legacy_quiz_attempt_data($data, $quiz) {
5618 global $DB;
5619 $upgrader = $this->get_attempt_upgrader();
5621 $data = (object)$data;
5623 $layout = explode(',', $data->layout);
5624 $newlayout = $layout;
5626 // Convert each old question_session into a question_attempt.
5627 $qas = array();
5628 foreach (explode(',', $quiz->oldquestions) as $questionid) {
5629 if ($questionid == 0) {
5630 continue;
5633 $newquestionid = $this->get_mappingid('question', $questionid);
5634 if (!$newquestionid) {
5635 throw new restore_step_exception('questionattemptreferstomissingquestion',
5636 $questionid, $questionid);
5639 $question = $upgrader->load_question($newquestionid, $quiz->id);
5641 foreach ($layout as $key => $qid) {
5642 if ($qid == $questionid) {
5643 $newlayout[$key] = $newquestionid;
5647 list($qsession, $qstates) = $this->find_question_session_and_states(
5648 $data, $questionid);
5650 if (empty($qsession) || empty($qstates)) {
5651 throw new restore_step_exception('questionattemptdatamissing',
5652 $questionid, $questionid);
5655 list($qsession, $qstates) = $this->recode_legacy_response_data(
5656 $question, $qsession, $qstates);
5658 $data->layout = implode(',', $newlayout);
5659 $qas[$newquestionid] = $upgrader->convert_question_attempt(
5660 $quiz, $data, $question, $qsession, $qstates);
5663 // Now create a new question_usage.
5664 $usage = new stdClass();
5665 $usage->component = 'mod_quiz';
5666 $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
5667 $usage->preferredbehaviour = $quiz->preferredbehaviour;
5668 $usage->id = $DB->insert_record('question_usages', $usage);
5670 $this->inform_new_usage_id($usage->id);
5672 $data->uniqueid = $usage->id;
5673 $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
5674 $this->questions_recode_layout($quiz->oldquestions));
5677 protected function find_question_session_and_states($data, $questionid) {
5678 $qsession = null;
5679 foreach ($data->sessions['session'] as $session) {
5680 if ($session['questionid'] == $questionid) {
5681 $qsession = (object) $session;
5682 break;
5686 $qstates = array();
5687 foreach ($data->states['state'] as $state) {
5688 if ($state['question'] == $questionid) {
5689 // It would be natural to use $state['seq_number'] as the array-key
5690 // here, but it seems that buggy behaviour in 2.0 and early can
5691 // mean that that is not unique, so we use id, which is guaranteed
5692 // to be unique.
5693 $qstates[$state['id']] = (object) $state;
5696 ksort($qstates);
5697 $qstates = array_values($qstates);
5699 return array($qsession, $qstates);
5703 * Recode any ids in the response data
5704 * @param object $question the question data
5705 * @param object $qsession the question sessions.
5706 * @param array $qstates the question states.
5708 protected function recode_legacy_response_data($question, $qsession, $qstates) {
5709 $qsession->questionid = $question->id;
5711 foreach ($qstates as &$state) {
5712 $state->question = $question->id;
5713 $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
5716 return array($qsession, $qstates);
5720 * Recode the legacy answer field.
5721 * @param object $state the state to recode the answer of.
5722 * @param string $qtype the question type.
5724 public function restore_recode_legacy_answer($state, $qtype) {
5725 $restorer = $this->get_qtype_restorer($qtype);
5726 if ($restorer) {
5727 return $restorer->recode_legacy_state_answer($state);
5728 } else {
5729 return $state->answer;
5735 * Restore completion defaults for each module type
5737 * @package core_backup
5738 * @copyright 2017 Marina Glancy
5739 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5741 class restore_completion_defaults_structure_step extends restore_structure_step {
5743 * To conditionally decide if this step must be executed.
5745 protected function execute_condition() {
5746 // No completion on the front page.
5747 if ($this->get_courseid() == SITEID) {
5748 return false;
5751 // No default completion info found, don't execute.
5752 $fullpath = $this->task->get_taskbasepath();
5753 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
5754 if (!file_exists($fullpath)) {
5755 return false;
5758 // Arrived here, execute the step.
5759 return true;
5763 * Function that will return the structure to be processed by this restore_step.
5765 * @return restore_path_element[]
5767 protected function define_structure() {
5768 return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
5772 * Processor for path element 'completion_defaults'
5774 * @param stdClass|array $data
5776 protected function process_completion_defaults($data) {
5777 global $DB;
5779 $data = (array)$data;
5780 $oldid = $data['id'];
5781 unset($data['id']);
5783 // Find the module by name since id may be different in another site.
5784 if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
5785 return;
5787 unset($data['modulename']);
5789 // Find the existing record.
5790 $newid = $DB->get_field('course_completion_defaults', 'id',
5791 ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
5792 if (!$newid) {
5793 $newid = $DB->insert_record('course_completion_defaults',
5794 ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
5795 } else {
5796 $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
5799 // Save id mapping for restoring associated events.
5800 $this->set_mapping('course_completion_defaults', $oldid, $newid);
5805 * Index course after restore.
5807 * @package core_backup
5808 * @copyright 2017 The Open University
5809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5811 class restore_course_search_index extends restore_execution_step {
5813 * When this step is executed, we add the course context to the queue for reindexing.
5815 protected function define_execution() {
5816 $context = \context_course::instance($this->task->get_courseid());
5817 \core_search\manager::request_index($context);
5822 * Index activity after restore (when not restoring whole course).
5824 * @package core_backup
5825 * @copyright 2017 The Open University
5826 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5828 class restore_activity_search_index extends restore_execution_step {
5830 * When this step is executed, we add the activity context to the queue for reindexing.
5832 protected function define_execution() {
5833 $context = \context::instance_by_id($this->task->get_contextid());
5834 \core_search\manager::request_index($context);
5839 * Index block after restore (when not restoring whole course).
5841 * @package core_backup
5842 * @copyright 2017 The Open University
5843 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5845 class restore_block_search_index extends restore_execution_step {
5847 * When this step is executed, we add the block context to the queue for reindexing.
5849 protected function define_execution() {
5850 // A block in the restore list may be skipped because a duplicate is detected.
5851 // In this case, there is no new blockid (or context) to get.
5852 if (!empty($this->task->get_blockid())) {
5853 $context = \context_block::instance($this->task->get_blockid());
5854 \core_search\manager::request_index($context);
5860 * Restore action events.
5862 * @package core_backup
5863 * @copyright 2017 onwards Ankit Agarwal
5864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5866 class restore_calendar_action_events extends restore_execution_step {
5868 * What to do when this step is executed.
5870 protected function define_execution() {
5871 // We just queue the task here rather trying to recreate everything manually.
5872 // The task will automatically populate all data.
5873 $task = new \core\task\refresh_mod_calendar_events_task();
5874 $task->set_custom_data(array('courseid' => $this->get_courseid()));
5875 \core\task\manager::queue_adhoc_task($task, true);