Moodle release 2.8.10
[moodle.git] / backup / moodle2 / restore_stepslib.php
blobf824ad1fa303950caed47c53deaf8290456bbcfc
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 // No gradebook info found, don't execute
93 $fullpath = $this->task->get_taskbasepath();
94 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
95 if (!file_exists($fullpath)) {
96 return false;
99 // Some module present in backup file isn't available to restore
100 // in this site, don't execute
101 if ($this->task->is_missing_modules()) {
102 return false;
105 // Some activity has been excluded to be restored, don't execute
106 if ($this->task->is_excluding_activities()) {
107 return false;
110 // There should only be one grade category (the 1 associated with the course itself)
111 // If other categories already exist we're restoring into an existing course.
112 // Restoring categories into a course with an existing category structure is unlikely to go well
113 $category = new stdclass();
114 $category->courseid = $this->get_courseid();
115 $catcount = $DB->count_records('grade_categories', (array)$category);
116 if ($catcount>1) {
117 return false;
120 // Arrived here, execute the step
121 return true;
124 protected function define_structure() {
125 $paths = array();
126 $userinfo = $this->task->get_setting_value('users');
128 $paths[] = new restore_path_element('gradebook', '/gradebook');
129 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
130 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
131 if ($userinfo) {
132 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
134 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
135 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
137 return $paths;
140 protected function process_gradebook($data) {
141 // For non-merge restore types:
142 // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
143 $target = $this->get_task()->get_target();
144 if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) {
145 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
147 if (!empty($data['calculations_freeze'])) {
148 if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING ||
149 $target == backup::TARGET_EXISTING_DELETING) {
150 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
155 protected function process_grade_item($data) {
156 global $DB;
158 $data = (object)$data;
160 $oldid = $data->id;
161 $data->course = $this->get_courseid();
163 $data->courseid = $this->get_courseid();
165 if ($data->itemtype=='manual') {
166 // manual grade items store category id in categoryid
167 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
168 // if mapping failed put in course's grade category
169 if (NULL == $data->categoryid) {
170 $coursecat = grade_category::fetch_course_category($this->get_courseid());
171 $data->categoryid = $coursecat->id;
173 } else if ($data->itemtype=='course') {
174 // course grade item stores their category id in iteminstance
175 $coursecat = grade_category::fetch_course_category($this->get_courseid());
176 $data->iteminstance = $coursecat->id;
177 } else if ($data->itemtype=='category') {
178 // category grade items store their category id in iteminstance
179 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
180 } else {
181 throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
184 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
185 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
187 $data->locktime = $this->apply_date_offset($data->locktime);
188 $data->timecreated = $this->apply_date_offset($data->timecreated);
189 $data->timemodified = $this->apply_date_offset($data->timemodified);
191 $coursecategory = $newitemid = null;
192 //course grade item should already exist so updating instead of inserting
193 if($data->itemtype=='course') {
194 //get the ID of the already created grade item
195 $gi = new stdclass();
196 $gi->courseid = $this->get_courseid();
197 $gi->itemtype = $data->itemtype;
199 //need to get the id of the grade_category that was automatically created for the course
200 $category = new stdclass();
201 $category->courseid = $this->get_courseid();
202 $category->parent = null;
203 //course category fullname starts out as ? but may be edited
204 //$category->fullname = '?';
205 $coursecategory = $DB->get_record('grade_categories', (array)$category);
206 $gi->iteminstance = $coursecategory->id;
208 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
209 if (!empty($existinggradeitem)) {
210 $data->id = $newitemid = $existinggradeitem->id;
211 $DB->update_record('grade_items', $data);
213 } else if ($data->itemtype == 'manual') {
214 // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
215 $gi = array(
216 'itemtype' => $data->itemtype,
217 'courseid' => $data->courseid,
218 'itemname' => $data->itemname,
219 'categoryid' => $data->categoryid,
221 $newitemid = $DB->get_field('grade_items', 'id', $gi);
224 if (empty($newitemid)) {
225 //in case we found the course category but still need to insert the course grade item
226 if ($data->itemtype=='course' && !empty($coursecategory)) {
227 $data->iteminstance = $coursecategory->id;
230 $newitemid = $DB->insert_record('grade_items', $data);
232 $this->set_mapping('grade_item', $oldid, $newitemid);
235 protected function process_grade_grade($data) {
236 global $DB;
238 $data = (object)$data;
239 $oldid = $data->id;
240 $olduserid = $data->userid;
242 $data->itemid = $this->get_new_parentid('grade_item');
244 $data->userid = $this->get_mappingid('user', $data->userid, null);
245 if (!empty($data->userid)) {
246 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
247 $data->locktime = $this->apply_date_offset($data->locktime);
248 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
249 $data->overridden = $this->apply_date_offset($data->overridden);
250 $data->timecreated = $this->apply_date_offset($data->timecreated);
251 $data->timemodified = $this->apply_date_offset($data->timemodified);
253 $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
254 if ($gradeexists) {
255 $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
256 $this->log($message, backup::LOG_DEBUG);
257 } else {
258 $newitemid = $DB->insert_record('grade_grades', $data);
259 $this->set_mapping('grade_grades', $oldid, $newitemid);
261 } else {
262 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
263 $this->log($message, backup::LOG_DEBUG);
267 protected function process_grade_category($data) {
268 global $DB;
270 $data = (object)$data;
271 $oldid = $data->id;
273 $data->course = $this->get_courseid();
274 $data->courseid = $data->course;
276 $data->timecreated = $this->apply_date_offset($data->timecreated);
277 $data->timemodified = $this->apply_date_offset($data->timemodified);
279 $newitemid = null;
280 //no parent means a course level grade category. That may have been created when the course was created
281 if(empty($data->parent)) {
282 //parent was being saved as 0 when it should be null
283 $data->parent = null;
285 //get the already created course level grade category
286 $category = new stdclass();
287 $category->courseid = $this->get_courseid();
288 $category->parent = null;
290 $coursecategory = $DB->get_record('grade_categories', (array)$category);
291 if (!empty($coursecategory)) {
292 $data->id = $newitemid = $coursecategory->id;
293 $DB->update_record('grade_categories', $data);
297 // Add a warning about a removed setting.
298 if (!empty($data->aggregatesubcats)) {
299 set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
302 //need to insert a course category
303 if (empty($newitemid)) {
304 $newitemid = $DB->insert_record('grade_categories', $data);
306 $this->set_mapping('grade_category', $oldid, $newitemid);
308 protected function process_grade_letter($data) {
309 global $DB;
311 $data = (object)$data;
312 $oldid = $data->id;
314 $data->contextid = context_course::instance($this->get_courseid())->id;
316 $gradeletter = (array)$data;
317 unset($gradeletter['id']);
318 if (!$DB->record_exists('grade_letters', $gradeletter)) {
319 $newitemid = $DB->insert_record('grade_letters', $data);
320 } else {
321 $newitemid = $data->id;
324 $this->set_mapping('grade_letter', $oldid, $newitemid);
326 protected function process_grade_setting($data) {
327 global $DB;
329 $data = (object)$data;
330 $oldid = $data->id;
332 $data->courseid = $this->get_courseid();
334 $target = $this->get_task()->get_target();
335 if ($data->name == 'minmaxtouse' &&
336 ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) {
337 // We never restore minmaxtouse during merge.
338 return;
341 if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
342 $newitemid = $DB->insert_record('grade_settings', $data);
343 } else {
344 $newitemid = $data->id;
347 if (!empty($oldid)) {
348 // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
349 $this->set_mapping('grade_setting', $oldid, $newitemid);
354 * put all activity grade items in the correct grade category and mark all for recalculation
356 protected function after_execute() {
357 global $DB;
359 $conditions = array(
360 'backupid' => $this->get_restoreid(),
361 'itemname' => 'grade_item'//,
362 //'itemid' => $itemid
364 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
366 // We need this for calculation magic later on.
367 $mappings = array();
369 if (!empty($rs)) {
370 foreach($rs as $grade_item_backup) {
372 // Store the oldid with the new id.
373 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
375 $updateobj = new stdclass();
376 $updateobj->id = $grade_item_backup->newitemid;
378 //if this is an activity grade item that needs to be put back in its correct category
379 if (!empty($grade_item_backup->parentitemid)) {
380 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
381 if (!is_null($oldcategoryid)) {
382 $updateobj->categoryid = $oldcategoryid;
383 $DB->update_record('grade_items', $updateobj);
385 } else {
386 //mark course and category items as needing to be recalculated
387 $updateobj->needsupdate=1;
388 $DB->update_record('grade_items', $updateobj);
392 $rs->close();
394 // We need to update the calculations for calculated grade items that may reference old
395 // grade item ids using ##gi\d+##.
396 // $mappings can be empty, use 0 if so (won't match ever)
397 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
398 $sql = "SELECT gi.id, gi.calculation
399 FROM {grade_items} gi
400 WHERE gi.id {$sql} AND
401 calculation IS NOT NULL";
402 $rs = $DB->get_recordset_sql($sql, $params);
403 foreach ($rs as $gradeitem) {
404 // Collect all of the used grade item id references
405 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
406 // This calculation doesn't reference any other grade items... EASY!
407 continue;
409 // For this next bit we are going to do the replacement of id's in two steps:
410 // 1. We will replace all old id references with a special mapping reference.
411 // 2. We will replace all mapping references with id's
412 // Why do we do this?
413 // Because there potentially there will be an overlap of ids within the query and we
414 // we substitute the wrong id.. safest way around this is the two step system
415 $calculationmap = array();
416 $mapcount = 0;
417 foreach ($matches[1] as $match) {
418 // Check that the old id is known to us, if not it was broken to begin with and will
419 // continue to be broken.
420 if (!array_key_exists($match, $mappings)) {
421 continue;
423 // Our special mapping key
424 $mapping = '##MAPPING'.$mapcount.'##';
425 // The old id that exists within the calculation now
426 $oldid = '##gi'.$match.'##';
427 // The new id that we want to replace the old one with.
428 $newid = '##gi'.$mappings[$match].'##';
429 // Replace in the special mapping key
430 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
431 // And record the mapping
432 $calculationmap[$mapping] = $newid;
433 $mapcount++;
435 // Iterate all special mappings for this calculation and replace in the new id's
436 foreach ($calculationmap as $mapping => $newid) {
437 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
439 // Update the calculation now that its being remapped
440 $DB->update_record('grade_items', $gradeitem);
442 $rs->close();
444 // Need to correct the grade category path and parent
445 $conditions = array(
446 'courseid' => $this->get_courseid()
449 $rs = $DB->get_recordset('grade_categories', $conditions);
450 // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
451 foreach ($rs as $gc) {
452 if (!empty($gc->parent)) {
453 $grade_category = new stdClass();
454 $grade_category->id = $gc->id;
455 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
456 $DB->update_record('grade_categories', $grade_category);
459 $rs->close();
461 // Now we can rebuild all the paths
462 $rs = $DB->get_recordset('grade_categories', $conditions);
463 foreach ($rs as $gc) {
464 $grade_category = new stdClass();
465 $grade_category->id = $gc->id;
466 $grade_category->path = grade_category::build_path($gc);
467 $grade_category->depth = substr_count($grade_category->path, '/') - 1;
468 $DB->update_record('grade_categories', $grade_category);
470 $rs->close();
472 // Check what to do with the minmaxtouse setting.
473 $this->check_minmaxtouse();
475 // Freeze gradebook calculations if needed.
476 $this->gradebook_calculation_freeze();
478 // Restore marks items as needing update. Update everything now.
479 grade_regrade_final_grades($this->get_courseid());
483 * Freeze gradebook calculation if needed.
485 * This is similar to various upgrade scripts that check if the freeze is needed.
487 protected function gradebook_calculation_freeze() {
488 global $CFG;
489 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
490 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
491 $backupbuild = (int)$matches[1];
493 // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
494 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) {
495 require_once($CFG->libdir . '/db/upgradelib.php');
496 upgrade_extra_credit_weightoverride($this->get_courseid());
498 // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
499 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) {
500 require_once($CFG->libdir . '/db/upgradelib.php');
501 upgrade_calculated_grade_items($this->get_courseid());
506 * Checks what should happen with the course grade setting minmaxtouse.
508 * This is related to the upgrade step at the time the setting was added.
510 * @see MDL-48618
511 * @return void
513 protected function check_minmaxtouse() {
514 global $CFG, $DB;
515 require_once($CFG->libdir . '/gradelib.php');
517 $userinfo = $this->task->get_setting_value('users');
518 $settingname = 'minmaxtouse';
519 $courseid = $this->get_courseid();
520 $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
521 $version28start = 2014111000.00;
522 $version28last = 2014111006.05;
524 $target = $this->get_task()->get_target();
525 if ($minmaxtouse === false &&
526 ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
527 // The setting was not found because this setting did not exist at the time the backup was made.
528 // And we are not restoring as merge, in which case we leave the course as it was.
529 $version = $this->get_task()->get_info()->moodle_version;
531 if ($version < $version28start) {
532 // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
533 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
534 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
537 } else if ($version >= $version28start && $version < $version28last) {
538 // They should be using grade_grade when the course has inconsistencies.
540 $sql = "SELECT gi.id
541 FROM {grade_items} gi
542 JOIN {grade_grades} gg
543 ON gg.itemid = gi.id
544 WHERE gi.courseid = ?
545 AND (gi.itemtype != ? AND gi.itemtype != ?)
546 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
548 // The course can only have inconsistencies when we restore the user info,
549 // we do not need to act on existing grades that were not restored as part of this backup.
550 if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
552 // Display the notice as we do during upgrade.
553 set_config('show_min_max_grades_changed_' . $courseid, 1);
555 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
556 // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
557 // If they are using the site-wide grade_grade setting, we only want to notice them.
558 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
562 } else {
563 // This should never happen because from now on minmaxtouse is always saved in backups.
570 * Step in charge of restoring the grade history of a course.
572 * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
573 * we do not want to restore the history if the gradebook and its content has not been
574 * restored. At least for now.
576 class restore_grade_history_structure_step extends restore_structure_step {
578 protected function execute_condition() {
579 global $CFG, $DB;
581 // No gradebook info found, don't execute.
582 $fullpath = $this->task->get_taskbasepath();
583 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
584 if (!file_exists($fullpath)) {
585 return false;
588 // Some module present in backup file isn't available to restore in this site, don't execute.
589 if ($this->task->is_missing_modules()) {
590 return false;
593 // Some activity has been excluded to be restored, don't execute.
594 if ($this->task->is_excluding_activities()) {
595 return false;
598 // There should only be one grade category (the 1 associated with the course itself).
599 $category = new stdclass();
600 $category->courseid = $this->get_courseid();
601 $catcount = $DB->count_records('grade_categories', (array)$category);
602 if ($catcount > 1) {
603 return false;
606 // Arrived here, execute the step.
607 return true;
610 protected function define_structure() {
611 $paths = array();
613 // Settings to use.
614 $userinfo = $this->get_setting_value('users');
615 $history = $this->get_setting_value('grade_histories');
617 if ($userinfo && $history) {
618 $paths[] = new restore_path_element('grade_grade',
619 '/grade_history/grade_grades/grade_grade');
622 return $paths;
625 protected function process_grade_grade($data) {
626 global $DB;
628 $data = (object)($data);
629 $olduserid = $data->userid;
630 unset($data->id);
632 $data->userid = $this->get_mappingid('user', $data->userid, null);
633 if (!empty($data->userid)) {
634 // Do not apply the date offsets as this is history.
635 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
636 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
637 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
638 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
639 $DB->insert_record('grade_grades_history', $data);
640 } else {
641 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
642 $this->log($message, backup::LOG_DEBUG);
649 * decode all the interlinks present in restored content
650 * relying 100% in the restore_decode_processor that handles
651 * both the contents to modify and the rules to be applied
653 class restore_decode_interlinks extends restore_execution_step {
655 protected function define_execution() {
656 // Get the decoder (from the plan)
657 $decoder = $this->task->get_decoder();
658 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
659 // And launch it, everything will be processed
660 $decoder->execute();
665 * first, ensure that we have no gaps in section numbers
666 * and then, rebuid the course cache
668 class restore_rebuild_course_cache extends restore_execution_step {
670 protected function define_execution() {
671 global $DB;
673 // Although there is some sort of auto-recovery of missing sections
674 // present in course/formats... here we check that all the sections
675 // from 0 to MAX(section->section) exist, creating them if necessary
676 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
677 // Iterate over all sections
678 for ($i = 0; $i <= $maxsection; $i++) {
679 // If the section $i doesn't exist, create it
680 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
681 $sectionrec = array(
682 'course' => $this->get_courseid(),
683 'section' => $i);
684 $DB->insert_record('course_sections', $sectionrec); // missing section created
688 // Rebuild cache now that all sections are in place
689 rebuild_course_cache($this->get_courseid());
690 cache_helper::purge_by_event('changesincourse');
691 cache_helper::purge_by_event('changesincoursecat');
696 * Review all the tasks having one after_restore method
697 * executing it to perform some final adjustments of information
698 * not available when the task was executed.
700 class restore_execute_after_restore extends restore_execution_step {
702 protected function define_execution() {
704 // Simply call to the execute_after_restore() method of the task
705 // that always is the restore_final_task
706 $this->task->launch_execute_after_restore();
712 * Review all the (pending) block positions in backup_ids, matching by
713 * contextid, creating positions as needed. This is executed by the
714 * final task, once all the contexts have been created
716 class restore_review_pending_block_positions extends restore_execution_step {
718 protected function define_execution() {
719 global $DB;
721 // Get all the block_position objects pending to match
722 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
723 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
724 // Process block positions, creating them or accumulating for final step
725 foreach($rs as $posrec) {
726 // Get the complete position object out of the info field.
727 $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
728 // If position is for one already mapped (known) contextid
729 // process it now, creating the position, else nothing to
730 // do, position finally discarded
731 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
732 $position->contextid = $newctx->newitemid;
733 // Create the block position
734 $DB->insert_record('block_positions', $position);
737 $rs->close();
743 * Updates the availability data for course modules and sections.
745 * Runs after the restore of all course modules, sections, and grade items has
746 * completed. This is necessary in order to update IDs that have changed during
747 * restore.
749 * @package core_backup
750 * @copyright 2014 The Open University
751 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
753 class restore_update_availability extends restore_execution_step {
755 protected function define_execution() {
756 global $CFG, $DB;
758 // Note: This code runs even if availability is disabled when restoring.
759 // That will ensure that if you later turn availability on for the site,
760 // there will be no incorrect IDs. (It doesn't take long if the restored
761 // data does not contain any availability information.)
763 // Get modinfo with all data after resetting cache.
764 rebuild_course_cache($this->get_courseid(), true);
765 $modinfo = get_fast_modinfo($this->get_courseid());
767 // Get the date offset for this restore.
768 $dateoffset = $this->apply_date_offset(1) - 1;
770 // Update all sections that were restored.
771 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
772 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
773 $sectionsbyid = null;
774 foreach ($rs as $rec) {
775 if (is_null($sectionsbyid)) {
776 $sectionsbyid = array();
777 foreach ($modinfo->get_section_info_all() as $section) {
778 $sectionsbyid[$section->id] = $section;
781 if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
782 // If the section was not fully restored for some reason
783 // (e.g. due to an earlier error), skip it.
784 $this->get_logger()->process('Section not fully restored: id ' .
785 $rec->newitemid, backup::LOG_WARNING);
786 continue;
788 $section = $sectionsbyid[$rec->newitemid];
789 if (!is_null($section->availability)) {
790 $info = new \core_availability\info_section($section);
791 $info->update_after_restore($this->get_restoreid(),
792 $this->get_courseid(), $this->get_logger(), $dateoffset);
795 $rs->close();
797 // Update all modules that were restored.
798 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
799 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
800 foreach ($rs as $rec) {
801 if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
802 // If the module was not fully restored for some reason
803 // (e.g. due to an earlier error), skip it.
804 $this->get_logger()->process('Module not fully restored: id ' .
805 $rec->newitemid, backup::LOG_WARNING);
806 continue;
808 $cm = $modinfo->get_cm($rec->newitemid);
809 if (!is_null($cm->availability)) {
810 $info = new \core_availability\info_module($cm);
811 $info->update_after_restore($this->get_restoreid(),
812 $this->get_courseid(), $this->get_logger(), $dateoffset);
815 $rs->close();
821 * Process legacy module availability records in backup_ids.
823 * Matches course modules and grade item id once all them have been already restored.
824 * Only if all matchings are satisfied the availability condition will be created.
825 * At the same time, it is required for the site to have that functionality enabled.
827 * This step is included only to handle legacy backups (2.6 and before). It does not
828 * do anything for newer backups.
830 * @copyright 2014 The Open University
831 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
833 class restore_process_course_modules_availability extends restore_execution_step {
835 protected function define_execution() {
836 global $CFG, $DB;
838 // Site hasn't availability enabled
839 if (empty($CFG->enableavailability)) {
840 return;
843 // Do both modules and sections.
844 foreach (array('module', 'section') as $table) {
845 // Get all the availability objects to process.
846 $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
847 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
848 // Process availabilities, creating them if everything matches ok.
849 foreach ($rs as $availrec) {
850 $allmatchesok = true;
851 // Get the complete legacy availability object.
852 $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
854 // Note: This code used to update IDs, but that is now handled by the
855 // current code (after restore) instead of this legacy code.
857 // Get showavailability option.
858 $thingid = ($table === 'module') ? $availability->coursemoduleid :
859 $availability->coursesectionid;
860 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
861 $table . '_showavailability', $thingid);
862 if (!$showrec) {
863 // Should not happen.
864 throw new coding_exception('No matching showavailability record');
866 $show = $showrec->info->showavailability;
868 // The $availability object is now in the format used in the old
869 // system. Interpret this and convert to new system.
870 $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
871 array('id' => $thingid), MUST_EXIST);
872 $newvalue = \core_availability\info::add_legacy_availability_condition(
873 $currentvalue, $availability, $show);
874 $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
875 array('id' => $thingid));
878 $rs->close();
884 * Execution step that, *conditionally* (if there isn't preloaded information)
885 * will load the inforef files for all the included course/section/activity tasks
886 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
888 class restore_load_included_inforef_records extends restore_execution_step {
890 protected function define_execution() {
892 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
893 return;
896 // Get all the included tasks
897 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
898 $progress = $this->task->get_progress();
899 $progress->start_progress($this->get_name(), count($tasks));
900 foreach ($tasks as $task) {
901 // Load the inforef.xml file if exists
902 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
903 if (file_exists($inforefpath)) {
904 // Load each inforef file to temp_ids.
905 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
908 $progress->end_progress();
913 * Execution step that will load all the needed files into backup_files_temp
914 * - info: contains the whole original object (times, names...)
915 * (all them being original ids as loaded from xml)
917 class restore_load_included_files extends restore_structure_step {
919 protected function define_structure() {
921 $file = new restore_path_element('file', '/files/file');
923 return array($file);
927 * Process one <file> element from files.xml
929 * @param array $data the element data
931 public function process_file($data) {
933 $data = (object)$data; // handy
935 // load it if needed:
936 // - it it is one of the annotated inforef files (course/section/activity/block)
937 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
938 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
939 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
940 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
941 $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
942 $data->component == 'grouping' || $data->component == 'grade' ||
943 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
944 if ($isfileref || $iscomponent) {
945 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
951 * Execution step that, *conditionally* (if there isn't preloaded information),
952 * will load all the needed roles to backup_temp_ids. They will be stored with
953 * "role" itemname. Also it will perform one automatic mapping to roles existing
954 * in the target site, based in permissions of the user performing the restore,
955 * archetypes and other bits. At the end, each original role will have its associated
956 * target role or 0 if it's going to be skipped. Note we wrap everything over one
957 * restore_dbops method, as far as the same stuff is going to be also executed
958 * by restore prechecks
960 class restore_load_and_map_roles extends restore_execution_step {
962 protected function define_execution() {
963 if ($this->task->get_preloaded_information()) { // if info is already preloaded
964 return;
967 $file = $this->get_basepath() . '/roles.xml';
968 // Load needed toles to temp_ids
969 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
971 // Process roles, mapping/skipping. Any error throws exception
972 // Note we pass controller's info because it can contain role mapping information
973 // about manual mappings performed by UI
974 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);
979 * Execution step that, *conditionally* (if there isn't preloaded information
980 * and users have been selected in settings, will load all the needed users
981 * to backup_temp_ids. They will be stored with "user" itemname and with
982 * their original contextid as paremitemid
984 class restore_load_included_users extends restore_execution_step {
986 protected function define_execution() {
988 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
989 return;
991 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
992 return;
994 $file = $this->get_basepath() . '/users.xml';
995 // Load needed users to temp_ids.
996 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
1001 * Execution step that, *conditionally* (if there isn't preloaded information
1002 * and users have been selected in settings, will process all the needed users
1003 * in order to decide and perform any action with them (create / map / error)
1004 * Note: Any error will cause exception, as far as this is the same processing
1005 * than the one into restore prechecks (that should have stopped process earlier)
1007 class restore_process_included_users extends restore_execution_step {
1009 protected function define_execution() {
1011 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1012 return;
1014 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1015 return;
1017 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
1018 $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
1023 * Execution step that will create all the needed users as calculated
1024 * by @restore_process_included_users (those having newiteind = 0)
1026 class restore_create_included_users extends restore_execution_step {
1028 protected function define_execution() {
1030 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
1031 $this->task->get_userid(), $this->task->get_progress());
1036 * Structure step that will create all the needed groups and groupings
1037 * by loading them from the groups.xml file performing the required matches.
1038 * Note group members only will be added if restoring user info
1040 class restore_groups_structure_step extends restore_structure_step {
1042 protected function define_structure() {
1044 $paths = array(); // Add paths here
1046 $paths[] = new restore_path_element('group', '/groups/group');
1047 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
1048 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
1050 return $paths;
1053 // Processing functions go here
1054 public function process_group($data) {
1055 global $DB;
1057 $data = (object)$data; // handy
1058 $data->courseid = $this->get_courseid();
1060 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1061 // another a group in the same course
1062 $context = context_course::instance($data->courseid);
1063 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1064 if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
1065 unset($data->idnumber);
1067 } else {
1068 unset($data->idnumber);
1071 $oldid = $data->id; // need this saved for later
1073 $restorefiles = false; // Only if we end creating the group
1075 // Search if the group already exists (by name & description) in the target course
1076 $description_clause = '';
1077 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1078 if (!empty($data->description)) {
1079 $description_clause = ' AND ' .
1080 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1081 $params['description'] = $data->description;
1083 if (!$groupdb = $DB->get_record_sql("SELECT *
1084 FROM {groups}
1085 WHERE courseid = :courseid
1086 AND name = :grname $description_clause", $params)) {
1087 // group doesn't exist, create
1088 $newitemid = $DB->insert_record('groups', $data);
1089 $restorefiles = true; // We'll restore the files
1090 } else {
1091 // group exists, use it
1092 $newitemid = $groupdb->id;
1094 // Save the id mapping
1095 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
1096 // Invalidate the course group data cache just in case.
1097 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1100 public function process_grouping($data) {
1101 global $DB;
1103 $data = (object)$data; // handy
1104 $data->courseid = $this->get_courseid();
1106 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1107 // another a grouping in the same course
1108 $context = context_course::instance($data->courseid);
1109 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1110 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
1111 unset($data->idnumber);
1113 } else {
1114 unset($data->idnumber);
1117 $oldid = $data->id; // need this saved for later
1118 $restorefiles = false; // Only if we end creating the grouping
1120 // Search if the grouping already exists (by name & description) in the target course
1121 $description_clause = '';
1122 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1123 if (!empty($data->description)) {
1124 $description_clause = ' AND ' .
1125 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1126 $params['description'] = $data->description;
1128 if (!$groupingdb = $DB->get_record_sql("SELECT *
1129 FROM {groupings}
1130 WHERE courseid = :courseid
1131 AND name = :grname $description_clause", $params)) {
1132 // grouping doesn't exist, create
1133 $newitemid = $DB->insert_record('groupings', $data);
1134 $restorefiles = true; // We'll restore the files
1135 } else {
1136 // grouping exists, use it
1137 $newitemid = $groupingdb->id;
1139 // Save the id mapping
1140 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1141 // Invalidate the course group data cache just in case.
1142 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1145 public function process_grouping_group($data) {
1146 global $CFG;
1148 require_once($CFG->dirroot.'/group/lib.php');
1150 $data = (object)$data;
1151 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
1154 protected function after_execute() {
1155 // Add group related files, matching with "group" mappings
1156 $this->add_related_files('group', 'icon', 'group');
1157 $this->add_related_files('group', 'description', 'group');
1158 // Add grouping related files, matching with "grouping" mappings
1159 $this->add_related_files('grouping', 'description', 'grouping');
1160 // Invalidate the course group data.
1161 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1167 * Structure step that will create all the needed group memberships
1168 * by loading them from the groups.xml file performing the required matches.
1170 class restore_groups_members_structure_step extends restore_structure_step {
1172 protected $plugins = null;
1174 protected function define_structure() {
1176 $paths = array(); // Add paths here
1178 if ($this->get_setting_value('users')) {
1179 $paths[] = new restore_path_element('group', '/groups/group');
1180 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1183 return $paths;
1186 public function process_group($data) {
1187 $data = (object)$data; // handy
1189 // HACK ALERT!
1190 // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1191 // Let's fake internal state to make $this->get_new_parentid('group') work.
1193 $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1196 public function process_member($data) {
1197 global $DB, $CFG;
1198 require_once("$CFG->dirroot/group/lib.php");
1200 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1202 $data = (object)$data; // handy
1204 // get parent group->id
1205 $data->groupid = $this->get_new_parentid('group');
1207 // map user newitemid and insert if not member already
1208 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1209 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1210 // Check the component, if any, exists.
1211 if (empty($data->component)) {
1212 groups_add_member($data->groupid, $data->userid);
1214 } else if ((strpos($data->component, 'enrol_') === 0)) {
1215 // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1216 // it is possible that enrolment was restored using different plugin type.
1217 if (!isset($this->plugins)) {
1218 $this->plugins = enrol_get_plugins(true);
1220 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1221 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1222 if (isset($this->plugins[$instance->enrol])) {
1223 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1228 } else {
1229 $dir = core_component::get_component_directory($data->component);
1230 if ($dir and is_dir($dir)) {
1231 if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1232 return;
1235 // Bad luck, plugin could not restore the data, let's add normal membership.
1236 groups_add_member($data->groupid, $data->userid);
1237 $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1238 $this->log($message, backup::LOG_WARNING);
1246 * Structure step that will create all the needed scales
1247 * by loading them from the scales.xml
1249 class restore_scales_structure_step extends restore_structure_step {
1251 protected function define_structure() {
1253 $paths = array(); // Add paths here
1254 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1255 return $paths;
1258 protected function process_scale($data) {
1259 global $DB;
1261 $data = (object)$data;
1263 $restorefiles = false; // Only if we end creating the group
1265 $oldid = $data->id; // need this saved for later
1267 // Look for scale (by 'scale' both in standard (course=0) and current course
1268 // with priority to standard scales (ORDER clause)
1269 // scale is not course unique, use get_record_sql to suppress warning
1270 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1271 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
1272 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1273 if (!$scadb = $DB->get_record_sql("SELECT *
1274 FROM {scale}
1275 WHERE courseid IN (0, :courseid)
1276 AND $compare_scale_clause
1277 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1278 // Remap the user if possible, defaut to user performing the restore if not
1279 $userid = $this->get_mappingid('user', $data->userid);
1280 $data->userid = $userid ? $userid : $this->task->get_userid();
1281 // Remap the course if course scale
1282 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1283 // If global scale (course=0), check the user has perms to create it
1284 // falling to course scale if not
1285 $systemctx = context_system::instance();
1286 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1287 $data->courseid = $this->get_courseid();
1289 // scale doesn't exist, create
1290 $newitemid = $DB->insert_record('scale', $data);
1291 $restorefiles = true; // We'll restore the files
1292 } else {
1293 // scale exists, use it
1294 $newitemid = $scadb->id;
1296 // Save the id mapping (with files support at system context)
1297 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1300 protected function after_execute() {
1301 // Add scales related files, matching with "scale" mappings
1302 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1308 * Structure step that will create all the needed outocomes
1309 * by loading them from the outcomes.xml
1311 class restore_outcomes_structure_step extends restore_structure_step {
1313 protected function define_structure() {
1315 $paths = array(); // Add paths here
1316 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1317 return $paths;
1320 protected function process_outcome($data) {
1321 global $DB;
1323 $data = (object)$data;
1325 $restorefiles = false; // Only if we end creating the group
1327 $oldid = $data->id; // need this saved for later
1329 // Look for outcome (by shortname both in standard (courseid=null) and current course
1330 // with priority to standard outcomes (ORDER clause)
1331 // outcome is not course unique, use get_record_sql to suppress warning
1332 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1333 if (!$outdb = $DB->get_record_sql('SELECT *
1334 FROM {grade_outcomes}
1335 WHERE shortname = :shortname
1336 AND (courseid = :courseid OR courseid IS NULL)
1337 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1338 // Remap the user
1339 $userid = $this->get_mappingid('user', $data->usermodified);
1340 $data->usermodified = $userid ? $userid : $this->task->get_userid();
1341 // Remap the scale
1342 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1343 // Remap the course if course outcome
1344 $data->courseid = $data->courseid ? $this->get_courseid() : null;
1345 // If global outcome (course=null), check the user has perms to create it
1346 // falling to course outcome if not
1347 $systemctx = context_system::instance();
1348 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1349 $data->courseid = $this->get_courseid();
1351 // outcome doesn't exist, create
1352 $newitemid = $DB->insert_record('grade_outcomes', $data);
1353 $restorefiles = true; // We'll restore the files
1354 } else {
1355 // scale exists, use it
1356 $newitemid = $outdb->id;
1358 // Set the corresponding grade_outcomes_courses record
1359 $outcourserec = new stdclass();
1360 $outcourserec->courseid = $this->get_courseid();
1361 $outcourserec->outcomeid = $newitemid;
1362 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1363 $DB->insert_record('grade_outcomes_courses', $outcourserec);
1365 // Save the id mapping (with files support at system context)
1366 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1369 protected function after_execute() {
1370 // Add outcomes related files, matching with "outcome" mappings
1371 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1376 * Execution step that, *conditionally* (if there isn't preloaded information
1377 * will load all the question categories and questions (header info only)
1378 * to backup_temp_ids. They will be stored with "question_category" and
1379 * "question" itemnames and with their original contextid and question category
1380 * id as paremitemids
1382 class restore_load_categories_and_questions extends restore_execution_step {
1384 protected function define_execution() {
1386 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1387 return;
1389 $file = $this->get_basepath() . '/questions.xml';
1390 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1395 * Execution step that, *conditionally* (if there isn't preloaded information)
1396 * will process all the needed categories and questions
1397 * in order to decide and perform any action with them (create / map / error)
1398 * Note: Any error will cause exception, as far as this is the same processing
1399 * than the one into restore prechecks (that should have stopped process earlier)
1401 class restore_process_categories_and_questions extends restore_execution_step {
1403 protected function define_execution() {
1405 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1406 return;
1408 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1413 * Structure step that will read the section.xml creating/updating sections
1414 * as needed, rebuilding course cache and other friends
1416 class restore_section_structure_step extends restore_structure_step {
1417 /** @var array Cache: Array of id => course format */
1418 private static $courseformats = array();
1421 * Resets a static cache of course formats. Required for unit testing.
1423 public static function reset_caches() {
1424 self::$courseformats = array();
1427 protected function define_structure() {
1428 global $CFG;
1430 $paths = array();
1432 $section = new restore_path_element('section', '/section');
1433 $paths[] = $section;
1434 if ($CFG->enableavailability) {
1435 $paths[] = new restore_path_element('availability', '/section/availability');
1436 $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1438 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1440 // Apply for 'format' plugins optional paths at section level
1441 $this->add_plugin_structure('format', $section);
1443 // Apply for 'local' plugins optional paths at section level
1444 $this->add_plugin_structure('local', $section);
1446 return $paths;
1449 public function process_section($data) {
1450 global $CFG, $DB;
1451 $data = (object)$data;
1452 $oldid = $data->id; // We'll need this later
1454 $restorefiles = false;
1456 // Look for the section
1457 $section = new stdclass();
1458 $section->course = $this->get_courseid();
1459 $section->section = $data->number;
1460 // Section doesn't exist, create it with all the info from backup
1461 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1462 $section->name = $data->name;
1463 $section->summary = $data->summary;
1464 $section->summaryformat = $data->summaryformat;
1465 $section->sequence = '';
1466 $section->visible = $data->visible;
1467 if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1468 $section->availability = null;
1469 } else {
1470 $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1471 // Include legacy [<2.7] availability data if provided.
1472 if (is_null($section->availability)) {
1473 $section->availability = \core_availability\info::convert_legacy_fields(
1474 $data, true);
1477 $newitemid = $DB->insert_record('course_sections', $section);
1478 $restorefiles = true;
1480 // Section exists, update non-empty information
1481 } else {
1482 $section->id = $secrec->id;
1483 if ((string)$secrec->name === '') {
1484 $section->name = $data->name;
1486 if (empty($secrec->summary)) {
1487 $section->summary = $data->summary;
1488 $section->summaryformat = $data->summaryformat;
1489 $restorefiles = true;
1492 // Don't update availability (I didn't see a useful way to define
1493 // whether existing or new one should take precedence).
1495 $DB->update_record('course_sections', $section);
1496 $newitemid = $secrec->id;
1499 // Annotate the section mapping, with restorefiles option if needed
1500 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1502 // set the new course_section id in the task
1503 $this->task->set_sectionid($newitemid);
1505 // If there is the legacy showavailability data, store this for later use.
1506 // (This data is not present when restoring 'new' backups.)
1507 if (isset($data->showavailability)) {
1508 // Cache the showavailability flag using the backup_ids data field.
1509 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1510 'section_showavailability', $newitemid, 0, null,
1511 (object)array('showavailability' => $data->showavailability));
1514 // Commented out. We never modify course->numsections as far as that is used
1515 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1516 // Note: We keep the code here, to know about and because of the possibility of making this
1517 // optional based on some setting/attribute in the future
1518 // If needed, adjust course->numsections
1519 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1520 // if ($numsections < $section->section) {
1521 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1522 // }
1527 * Process the legacy availability table record. This table does not exist
1528 * in Moodle 2.7+ but we still support restore.
1530 * @param stdClass $data Record data
1532 public function process_availability($data) {
1533 $data = (object)$data;
1534 // Simply going to store the whole availability record now, we'll process
1535 // all them later in the final task (once all activities have been restored)
1536 // Let's call the low level one to be able to store the whole object.
1537 $data->coursesectionid = $this->task->get_sectionid();
1538 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1539 'section_availability', $data->id, 0, null, $data);
1543 * Process the legacy availability fields table record. This table does not
1544 * exist in Moodle 2.7+ but we still support restore.
1546 * @param stdClass $data Record data
1548 public function process_availability_field($data) {
1549 global $DB;
1550 $data = (object)$data;
1551 // Mark it is as passed by default
1552 $passed = true;
1553 $customfieldid = null;
1555 // If a customfield has been used in order to pass we must be able to match an existing
1556 // customfield by name (data->customfield) and type (data->customfieldtype)
1557 if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1558 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1559 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1560 $passed = false;
1561 } else if (!is_null($data->customfield)) {
1562 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1563 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1564 $passed = ($customfieldid !== false);
1567 if ($passed) {
1568 // Create the object to insert into the database
1569 $availfield = new stdClass();
1570 $availfield->coursesectionid = $this->task->get_sectionid();
1571 $availfield->userfield = $data->userfield;
1572 $availfield->customfieldid = $customfieldid;
1573 $availfield->operator = $data->operator;
1574 $availfield->value = $data->value;
1576 // Get showavailability option.
1577 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1578 'section_showavailability', $availfield->coursesectionid);
1579 if (!$showrec) {
1580 // Should not happen.
1581 throw new coding_exception('No matching showavailability record');
1583 $show = $showrec->info->showavailability;
1585 // The $availfield object is now in the format used in the old
1586 // system. Interpret this and convert to new system.
1587 $currentvalue = $DB->get_field('course_sections', 'availability',
1588 array('id' => $availfield->coursesectionid), MUST_EXIST);
1589 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1590 $currentvalue, $availfield, $show);
1591 $DB->set_field('course_sections', 'availability', $newvalue,
1592 array('id' => $availfield->coursesectionid));
1596 public function process_course_format_options($data) {
1597 global $DB;
1598 $courseid = $this->get_courseid();
1599 if (!array_key_exists($courseid, self::$courseformats)) {
1600 // It is safe to have a static cache of course formats because format can not be changed after this point.
1601 self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1603 $data = (array)$data;
1604 if (self::$courseformats[$courseid] === $data['format']) {
1605 // Import section format options only if both courses (the one that was backed up
1606 // and the one we are restoring into) have same formats.
1607 $params = array(
1608 'courseid' => $this->get_courseid(),
1609 'sectionid' => $this->task->get_sectionid(),
1610 'format' => $data['format'],
1611 'name' => $data['name']
1613 if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1614 // Do not overwrite existing information.
1615 $newid = $record->id;
1616 } else {
1617 $params['value'] = $data['value'];
1618 $newid = $DB->insert_record('course_format_options', $params);
1620 $this->set_mapping('course_format_options', $data['id'], $newid);
1624 protected function after_execute() {
1625 // Add section related files, with 'course_section' itemid to match
1626 $this->add_related_files('course', 'section', 'course_section');
1631 * Structure step that will read the course.xml file, loading it and performing
1632 * various actions depending of the site/restore settings. Note that target
1633 * course always exist before arriving here so this step will be updating
1634 * the course record (never inserting)
1636 class restore_course_structure_step extends restore_structure_step {
1638 * @var bool this gets set to true by {@link process_course()} if we are
1639 * restoring an old coures that used the legacy 'module security' feature.
1640 * If so, we have to do more work in {@link after_execute()}.
1642 protected $legacyrestrictmodules = false;
1645 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1646 * array with array keys the module names ('forum', 'quiz', etc.). These are
1647 * the modules that are allowed according to the data in the backup file.
1648 * In {@link after_execute()} we then have to prevent adding of all the other
1649 * types of activity.
1651 protected $legacyallowedmodules = array();
1653 protected function define_structure() {
1655 $course = new restore_path_element('course', '/course');
1656 $category = new restore_path_element('category', '/course/category');
1657 $tag = new restore_path_element('tag', '/course/tags/tag');
1658 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1660 // Apply for 'format' plugins optional paths at course level
1661 $this->add_plugin_structure('format', $course);
1663 // Apply for 'theme' plugins optional paths at course level
1664 $this->add_plugin_structure('theme', $course);
1666 // Apply for 'report' plugins optional paths at course level
1667 $this->add_plugin_structure('report', $course);
1669 // Apply for 'course report' plugins optional paths at course level
1670 $this->add_plugin_structure('coursereport', $course);
1672 // Apply for plagiarism plugins optional paths at course level
1673 $this->add_plugin_structure('plagiarism', $course);
1675 // Apply for local plugins optional paths at course level
1676 $this->add_plugin_structure('local', $course);
1678 return array($course, $category, $tag, $allowed_module);
1682 * Processing functions go here
1684 * @global moodledatabase $DB
1685 * @param stdClass $data
1687 public function process_course($data) {
1688 global $CFG, $DB;
1690 $data = (object)$data;
1692 $fullname = $this->get_setting_value('course_fullname');
1693 $shortname = $this->get_setting_value('course_shortname');
1694 $startdate = $this->get_setting_value('course_startdate');
1696 // Calculate final course names, to avoid dupes
1697 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1699 // Need to change some fields before updating the course record
1700 $data->id = $this->get_courseid();
1701 $data->fullname = $fullname;
1702 $data->shortname= $shortname;
1704 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1705 // another course on this site.
1706 $context = context::instance_by_id($this->task->get_contextid());
1707 if (!empty($data->idnumber) && has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid()) &&
1708 $this->task->is_samesite() && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1709 // Do not reset idnumber.
1710 } else {
1711 $data->idnumber = '';
1714 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1715 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1716 if (empty($data->hiddensections)) {
1717 $data->hiddensections = 0;
1720 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1721 // then we will need to process restricted modules after execution.
1722 $this->legacyrestrictmodules = !empty($data->restrictmodules);
1724 $data->startdate= $this->apply_date_offset($data->startdate);
1725 if ($data->defaultgroupingid) {
1726 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1728 if (empty($CFG->enablecompletion)) {
1729 $data->enablecompletion = 0;
1730 $data->completionstartonenrol = 0;
1731 $data->completionnotify = 0;
1733 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1734 if (!array_key_exists($data->lang, $languages)) {
1735 $data->lang = '';
1738 $themes = get_list_of_themes(); // Get themes for quick search later
1739 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1740 $data->theme = '';
1743 // Check if this is an old SCORM course format.
1744 if ($data->format == 'scorm') {
1745 $data->format = 'singleactivity';
1746 $data->activitytype = 'scorm';
1749 // Course record ready, update it
1750 $DB->update_record('course', $data);
1752 course_get_format($data)->update_course_format_options($data);
1754 // Role name aliases
1755 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1758 public function process_category($data) {
1759 // Nothing to do with the category. UI sets it before restore starts
1762 public function process_tag($data) {
1763 global $CFG, $DB;
1765 $data = (object)$data;
1767 if (!empty($CFG->usetags)) { // if enabled in server
1768 // TODO: This is highly inneficient. Each time we add one tag
1769 // we fetch all the existing because tag_set() deletes them
1770 // so everything must be reinserted on each call
1771 $tags = array();
1772 $existingtags = tag_get_tags('course', $this->get_courseid());
1773 // Re-add all the existitng tags
1774 foreach ($existingtags as $existingtag) {
1775 $tags[] = $existingtag->rawname;
1777 // Add the one being restored
1778 $tags[] = $data->rawname;
1779 // Send all the tags back to the course
1780 tag_set('course', $this->get_courseid(), $tags, 'core',
1781 context_course::instance($this->get_courseid())->id);
1785 public function process_allowed_module($data) {
1786 $data = (object)$data;
1788 // Backwards compatiblity support for the data that used to be in the
1789 // course_allowed_modules table.
1790 if ($this->legacyrestrictmodules) {
1791 $this->legacyallowedmodules[$data->modulename] = 1;
1795 protected function after_execute() {
1796 global $DB;
1798 // Add course related files, without itemid to match
1799 $this->add_related_files('course', 'summary', null);
1800 $this->add_related_files('course', 'overviewfiles', null);
1802 // Deal with legacy allowed modules.
1803 if ($this->legacyrestrictmodules) {
1804 $context = context_course::instance($this->get_courseid());
1806 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1807 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1808 foreach ($managerroleids as $roleid) {
1809 unset($roleids[$roleid]);
1812 foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1813 if (isset($this->legacyallowedmodules[$modname])) {
1814 // Module is allowed, no worries.
1815 continue;
1818 $capability = 'mod/' . $modname . ':addinstance';
1819 foreach ($roleids as $roleid) {
1820 assign_capability($capability, CAP_PREVENT, $roleid, $context);
1828 * Execution step that will migrate legacy files if present.
1830 class restore_course_legacy_files_step extends restore_execution_step {
1831 public function define_execution() {
1832 global $DB;
1834 // Do a check for legacy files and skip if there are none.
1835 $sql = 'SELECT count(*)
1836 FROM {backup_files_temp}
1837 WHERE backupid = ?
1838 AND contextid = ?
1839 AND component = ?
1840 AND filearea = ?';
1841 $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
1843 if ($DB->count_records_sql($sql, $params)) {
1844 $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
1845 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
1846 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
1852 * Structure step that will read the roles.xml file (at course/activity/block levels)
1853 * containing all the role_assignments and overrides for that context. If corresponding to
1854 * one mapped role, they will be applied to target context. Will observe the role_assignments
1855 * setting to decide if ras are restored.
1857 * Note: this needs to be executed after all users are enrolled.
1859 class restore_ras_and_caps_structure_step extends restore_structure_step {
1860 protected $plugins = null;
1862 protected function define_structure() {
1864 $paths = array();
1866 // Observe the role_assignments setting
1867 if ($this->get_setting_value('role_assignments')) {
1868 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1870 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1872 return $paths;
1876 * Assign roles
1878 * This has to be called after enrolments processing.
1880 * @param mixed $data
1881 * @return void
1883 public function process_assignment($data) {
1884 global $DB;
1886 $data = (object)$data;
1888 // Check roleid, userid are one of the mapped ones
1889 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1890 return;
1892 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1893 return;
1895 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1896 // Only assign roles to not deleted users
1897 return;
1899 if (!$contextid = $this->task->get_contextid()) {
1900 return;
1903 if (empty($data->component)) {
1904 // assign standard manual roles
1905 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1906 role_assign($newroleid, $newuserid, $contextid);
1908 } else if ((strpos($data->component, 'enrol_') === 0)) {
1909 // Deal with enrolment roles - ignore the component and just find out the instance via new id,
1910 // it is possible that enrolment was restored using different plugin type.
1911 if (!isset($this->plugins)) {
1912 $this->plugins = enrol_get_plugins(true);
1914 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1915 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1916 if (isset($this->plugins[$instance->enrol])) {
1917 $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
1922 } else {
1923 $data->roleid = $newroleid;
1924 $data->userid = $newuserid;
1925 $data->contextid = $contextid;
1926 $dir = core_component::get_component_directory($data->component);
1927 if ($dir and is_dir($dir)) {
1928 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
1929 return;
1932 // Bad luck, plugin could not restore the data, let's add normal membership.
1933 role_assign($data->roleid, $data->userid, $data->contextid);
1934 $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
1935 $this->log($message, backup::LOG_WARNING);
1939 public function process_override($data) {
1940 $data = (object)$data;
1942 // Check roleid is one of the mapped ones
1943 $newroleid = $this->get_mappingid('role', $data->roleid);
1944 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1945 if ($newroleid && $this->task->get_contextid()) {
1946 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1947 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1948 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1954 * If no instances yet add default enrol methods the same way as when creating new course in UI.
1956 class restore_default_enrolments_step extends restore_execution_step {
1957 public function define_execution() {
1958 global $DB;
1960 $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
1962 if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
1963 // Something already added instances, do not add default instances.
1964 $plugins = enrol_get_plugins(true);
1965 foreach ($plugins as $plugin) {
1966 $plugin->restore_sync_course($course);
1969 } else {
1970 // Looks like a newly created course.
1971 enrol_course_updated(true, $course, null);
1977 * This structure steps restores the enrol plugins and their underlying
1978 * enrolments, performing all the mappings and/or movements required
1980 class restore_enrolments_structure_step extends restore_structure_step {
1981 protected $enrolsynced = false;
1982 protected $plugins = null;
1983 protected $originalstatus = array();
1986 * Conditionally decide if this step should be executed.
1988 * This function checks the following parameter:
1990 * 1. the course/enrolments.xml file exists
1992 * @return bool true is safe to execute, false otherwise
1994 protected function execute_condition() {
1996 // Check it is included in the backup
1997 $fullpath = $this->task->get_taskbasepath();
1998 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1999 if (!file_exists($fullpath)) {
2000 // Not found, can't restore enrolments info
2001 return false;
2004 return true;
2007 protected function define_structure() {
2009 $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2010 $enrolment = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2011 // Attach local plugin stucture to enrol element.
2012 $this->add_plugin_structure('enrol', $enrol);
2014 return array($enrol, $enrolment);
2018 * Create enrolment instances.
2020 * This has to be called after creation of roles
2021 * and before adding of role assignments.
2023 * @param mixed $data
2024 * @return void
2026 public function process_enrol($data) {
2027 global $DB;
2029 $data = (object)$data;
2030 $oldid = $data->id; // We'll need this later.
2031 unset($data->id);
2033 $this->originalstatus[$oldid] = $data->status;
2035 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2036 $this->set_mapping('enrol', $oldid, 0);
2037 return;
2040 if (!isset($this->plugins)) {
2041 $this->plugins = enrol_get_plugins(true);
2044 if (!$this->enrolsynced) {
2045 // Make sure that all plugin may create instances and enrolments automatically
2046 // before the first instance restore - this is suitable especially for plugins
2047 // that synchronise data automatically using course->idnumber or by course categories.
2048 foreach ($this->plugins as $plugin) {
2049 $plugin->restore_sync_course($courserec);
2051 $this->enrolsynced = true;
2054 // Map standard fields - plugin has to process custom fields manually.
2055 $data->roleid = $this->get_mappingid('role', $data->roleid);
2056 $data->courseid = $courserec->id;
2058 if ($this->get_setting_value('enrol_migratetomanual')) {
2059 unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2060 if (!enrol_is_enabled('manual')) {
2061 $this->set_mapping('enrol', $oldid, 0);
2062 return;
2064 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2065 $instance = reset($instances);
2066 $this->set_mapping('enrol', $oldid, $instance->id);
2067 } else {
2068 if ($data->enrol === 'manual') {
2069 $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2070 } else {
2071 $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2073 $this->set_mapping('enrol', $oldid, $instanceid);
2076 } else {
2077 if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2078 $this->set_mapping('enrol', $oldid, 0);
2079 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments";
2080 $this->log($message, backup::LOG_WARNING);
2081 return;
2083 if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2084 // Let's keep the sortorder in old backups.
2085 } else {
2086 // Prevent problems with colliding sortorders in old backups,
2087 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2088 unset($data->sortorder);
2090 // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2091 $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2096 * Create user enrolments.
2098 * This has to be called after creation of enrolment instances
2099 * and before adding of role assignments.
2101 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2103 * @param mixed $data
2104 * @return void
2106 public function process_enrolment($data) {
2107 global $DB;
2109 if (!isset($this->plugins)) {
2110 $this->plugins = enrol_get_plugins(true);
2113 $data = (object)$data;
2115 // Process only if parent instance have been mapped.
2116 if ($enrolid = $this->get_new_parentid('enrol')) {
2117 $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2118 $oldenrolid = $this->get_old_parentid('enrol');
2119 if (isset($this->originalstatus[$oldenrolid])) {
2120 $oldinstancestatus = $this->originalstatus[$oldenrolid];
2122 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2123 // And only if user is a mapped one.
2124 if ($userid = $this->get_mappingid('user', $data->userid)) {
2125 if (isset($this->plugins[$instance->enrol])) {
2126 $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2136 * Make sure the user restoring the course can actually access it.
2138 class restore_fix_restorer_access_step extends restore_execution_step {
2139 protected function define_execution() {
2140 global $CFG, $DB;
2142 if (!$userid = $this->task->get_userid()) {
2143 return;
2146 if (empty($CFG->restorernewroleid)) {
2147 // Bad luck, no fallback role for restorers specified
2148 return;
2151 $courseid = $this->get_courseid();
2152 $context = context_course::instance($courseid);
2154 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2155 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2156 return;
2159 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2160 role_assign($CFG->restorernewroleid, $userid, $context);
2162 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2163 // Extra role is enough, yay!
2164 return;
2167 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2168 // hopefully admin selected suitable $CFG->restorernewroleid ...
2169 if (!enrol_is_enabled('manual')) {
2170 return;
2172 if (!$enrol = enrol_get_plugin('manual')) {
2173 return;
2175 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2176 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2177 $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2178 $enrol->add_instance($course, $fields);
2181 enrol_try_internal_enrol($courseid, $userid);
2187 * This structure steps restores the filters and their configs
2189 class restore_filters_structure_step extends restore_structure_step {
2191 protected function define_structure() {
2193 $paths = array();
2195 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2196 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2198 return $paths;
2201 public function process_active($data) {
2203 $data = (object)$data;
2205 if (strpos($data->filter, 'filter/') === 0) {
2206 $data->filter = substr($data->filter, 7);
2208 } else if (strpos($data->filter, '/') !== false) {
2209 // Unsupported old filter.
2210 return;
2213 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2214 return;
2216 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2219 public function process_config($data) {
2221 $data = (object)$data;
2223 if (strpos($data->filter, 'filter/') === 0) {
2224 $data->filter = substr($data->filter, 7);
2226 } else if (strpos($data->filter, '/') !== false) {
2227 // Unsupported old filter.
2228 return;
2231 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2232 return;
2234 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2240 * This structure steps restores the comments
2241 * Note: Cannot use the comments API because defaults to USER->id.
2242 * That should change allowing to pass $userid
2244 class restore_comments_structure_step extends restore_structure_step {
2246 protected function define_structure() {
2248 $paths = array();
2250 $paths[] = new restore_path_element('comment', '/comments/comment');
2252 return $paths;
2255 public function process_comment($data) {
2256 global $DB;
2258 $data = (object)$data;
2260 // First of all, if the comment has some itemid, ask to the task what to map
2261 $mapping = false;
2262 if ($data->itemid) {
2263 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2264 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2266 // Only restore the comment if has no mapping OR we have found the matching mapping
2267 if (!$mapping || $data->itemid) {
2268 // Only if user mapping and context
2269 $data->userid = $this->get_mappingid('user', $data->userid);
2270 if ($data->userid && $this->task->get_contextid()) {
2271 $data->contextid = $this->task->get_contextid();
2272 // Only if there is another comment with same context/user/timecreated
2273 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2274 if (!$DB->record_exists('comments', $params)) {
2275 $DB->insert_record('comments', $data);
2283 * This structure steps restores the badges and their configs
2285 class restore_badges_structure_step extends restore_structure_step {
2288 * Conditionally decide if this step should be executed.
2290 * This function checks the following parameters:
2292 * 1. Badges and course badges are enabled on the site.
2293 * 2. The course/badges.xml file exists.
2294 * 3. All modules are restorable.
2295 * 4. All modules are marked for restore.
2297 * @return bool True is safe to execute, false otherwise
2299 protected function execute_condition() {
2300 global $CFG;
2302 // First check is badges and course level badges are enabled on this site.
2303 if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2304 // Disabled, don't restore course badges.
2305 return false;
2308 // Check if badges.xml is included in the backup.
2309 $fullpath = $this->task->get_taskbasepath();
2310 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2311 if (!file_exists($fullpath)) {
2312 // Not found, can't restore course badges.
2313 return false;
2316 // Check we are able to restore all backed up modules.
2317 if ($this->task->is_missing_modules()) {
2318 return false;
2321 // Finally check all modules within the backup are being restored.
2322 if ($this->task->is_excluding_activities()) {
2323 return false;
2326 return true;
2329 protected function define_structure() {
2330 $paths = array();
2331 $paths[] = new restore_path_element('badge', '/badges/badge');
2332 $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2333 $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2334 $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2336 return $paths;
2339 public function process_badge($data) {
2340 global $DB, $CFG;
2342 require_once($CFG->libdir . '/badgeslib.php');
2344 $data = (object)$data;
2345 $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2346 if (empty($data->usercreated)) {
2347 $data->usercreated = $this->task->get_userid();
2349 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2350 if (empty($data->usermodified)) {
2351 $data->usermodified = $this->task->get_userid();
2354 // We'll restore the badge image.
2355 $restorefiles = true;
2357 $courseid = $this->get_courseid();
2359 $params = array(
2360 'name' => $data->name,
2361 'description' => $data->description,
2362 'timecreated' => $this->apply_date_offset($data->timecreated),
2363 'timemodified' => $this->apply_date_offset($data->timemodified),
2364 'usercreated' => $data->usercreated,
2365 'usermodified' => $data->usermodified,
2366 'issuername' => $data->issuername,
2367 'issuerurl' => $data->issuerurl,
2368 'issuercontact' => $data->issuercontact,
2369 'expiredate' => $this->apply_date_offset($data->expiredate),
2370 'expireperiod' => $data->expireperiod,
2371 'type' => BADGE_TYPE_COURSE,
2372 'courseid' => $courseid,
2373 'message' => $data->message,
2374 'messagesubject' => $data->messagesubject,
2375 'attachment' => $data->attachment,
2376 'notification' => $data->notification,
2377 'status' => BADGE_STATUS_INACTIVE,
2378 'nextcron' => $this->apply_date_offset($data->nextcron)
2381 $newid = $DB->insert_record('badge', $params);
2382 $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2385 public function process_criterion($data) {
2386 global $DB;
2388 $data = (object)$data;
2390 $params = array(
2391 'badgeid' => $this->get_new_parentid('badge'),
2392 'criteriatype' => $data->criteriatype,
2393 'method' => $data->method
2395 $newid = $DB->insert_record('badge_criteria', $params);
2396 $this->set_mapping('criterion', $data->id, $newid);
2399 public function process_parameter($data) {
2400 global $DB, $CFG;
2402 require_once($CFG->libdir . '/badgeslib.php');
2404 $data = (object)$data;
2405 $criteriaid = $this->get_new_parentid('criterion');
2407 // Parameter array that will go to database.
2408 $params = array();
2409 $params['critid'] = $criteriaid;
2411 $oldparam = explode('_', $data->name);
2413 if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2414 $module = $this->get_mappingid('course_module', $oldparam[1]);
2415 $params['name'] = $oldparam[0] . '_' . $module;
2416 $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2417 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2418 $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2419 $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2420 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2421 $role = $this->get_mappingid('role', $data->value);
2422 if (!empty($role)) {
2423 $params['name'] = 'role_' . $role;
2424 $params['value'] = $role;
2425 } else {
2426 return;
2430 if (!$DB->record_exists('badge_criteria_param', $params)) {
2431 $DB->insert_record('badge_criteria_param', $params);
2435 public function process_manual_award($data) {
2436 global $DB;
2438 $data = (object)$data;
2439 $role = $this->get_mappingid('role', $data->issuerrole);
2441 if (!empty($role)) {
2442 $award = array(
2443 'badgeid' => $this->get_new_parentid('badge'),
2444 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2445 'issuerid' => $this->get_mappingid('user', $data->issuerid),
2446 'issuerrole' => $role,
2447 'datemet' => $this->apply_date_offset($data->datemet)
2450 // Skip the manual award if recipient or issuer can not be mapped to.
2451 if (empty($award['recipientid']) || empty($award['issuerid'])) {
2452 return;
2455 $DB->insert_record('badge_manual_award', $award);
2459 protected function after_execute() {
2460 // Add related files.
2461 $this->add_related_files('badges', 'badgeimage', 'badge');
2466 * This structure steps restores the calendar events
2468 class restore_calendarevents_structure_step extends restore_structure_step {
2470 protected function define_structure() {
2472 $paths = array();
2474 $paths[] = new restore_path_element('calendarevents', '/events/event');
2476 return $paths;
2479 public function process_calendarevents($data) {
2480 global $DB, $SITE, $USER;
2482 $data = (object)$data;
2483 $oldid = $data->id;
2484 $restorefiles = true; // We'll restore the files
2485 // Find the userid and the groupid associated with the event.
2486 $data->userid = $this->get_mappingid('user', $data->userid);
2487 if ($data->userid === false) {
2488 // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2489 // Use the current user ID for these events.
2490 $data->userid = $USER->id;
2492 if (!empty($data->groupid)) {
2493 $data->groupid = $this->get_mappingid('group', $data->groupid);
2494 if ($data->groupid === false) {
2495 return;
2498 // Handle events with empty eventtype //MDL-32827
2499 if(empty($data->eventtype)) {
2500 if ($data->courseid == $SITE->id) { // Site event
2501 $data->eventtype = "site";
2502 } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2503 // Course assingment event
2504 $data->eventtype = "due";
2505 } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event
2506 $data->eventtype = "course";
2507 } else if ($data->groupid) { // Group event
2508 $data->eventtype = "group";
2509 } else if ($data->userid) { // User event
2510 $data->eventtype = "user";
2511 } else {
2512 return;
2516 $params = array(
2517 'name' => $data->name,
2518 'description' => $data->description,
2519 'format' => $data->format,
2520 'courseid' => $this->get_courseid(),
2521 'groupid' => $data->groupid,
2522 'userid' => $data->userid,
2523 'repeatid' => $data->repeatid,
2524 'modulename' => $data->modulename,
2525 'eventtype' => $data->eventtype,
2526 'timestart' => $this->apply_date_offset($data->timestart),
2527 'timeduration' => $data->timeduration,
2528 'visible' => $data->visible,
2529 'uuid' => $data->uuid,
2530 'sequence' => $data->sequence,
2531 'timemodified' => $this->apply_date_offset($data->timemodified));
2532 if ($this->name == 'activity_calendar') {
2533 $params['instance'] = $this->task->get_activityid();
2534 } else {
2535 $params['instance'] = 0;
2537 $sql = "SELECT id
2538 FROM {event}
2539 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2540 AND courseid = ?
2541 AND repeatid = ?
2542 AND modulename = ?
2543 AND timestart = ?
2544 AND timeduration = ?
2545 AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2546 $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
2547 $result = $DB->record_exists_sql($sql, $arg);
2548 if (empty($result)) {
2549 $newitemid = $DB->insert_record('event', $params);
2550 $this->set_mapping('event', $oldid, $newitemid);
2551 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2555 protected function after_execute() {
2556 // Add related files
2557 $this->add_related_files('calendar', 'event_description', 'event_description');
2561 class restore_course_completion_structure_step extends restore_structure_step {
2564 * Conditionally decide if this step should be executed.
2566 * This function checks parameters that are not immediate settings to ensure
2567 * that the enviroment is suitable for the restore of course completion info.
2569 * This function checks the following four parameters:
2571 * 1. Course completion is enabled on the site
2572 * 2. The backup includes course completion information
2573 * 3. All modules are restorable
2574 * 4. All modules are marked for restore.
2576 * @return bool True is safe to execute, false otherwise
2578 protected function execute_condition() {
2579 global $CFG;
2581 // First check course completion is enabled on this site
2582 if (empty($CFG->enablecompletion)) {
2583 // Disabled, don't restore course completion
2584 return false;
2587 // Check it is included in the backup
2588 $fullpath = $this->task->get_taskbasepath();
2589 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2590 if (!file_exists($fullpath)) {
2591 // Not found, can't restore course completion
2592 return false;
2595 // Check we are able to restore all backed up modules
2596 if ($this->task->is_missing_modules()) {
2597 return false;
2600 // Finally check all modules within the backup are being restored.
2601 if ($this->task->is_excluding_activities()) {
2602 return false;
2605 return true;
2609 * Define the course completion structure
2611 * @return array Array of restore_path_element
2613 protected function define_structure() {
2615 // To know if we are including user completion info
2616 $userinfo = $this->get_setting_value('userscompletion');
2618 $paths = array();
2619 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2620 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2622 if ($userinfo) {
2623 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2624 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2627 return $paths;
2632 * Process course completion criteria
2634 * @global moodle_database $DB
2635 * @param stdClass $data
2637 public function process_course_completion_criteria($data) {
2638 global $DB;
2640 $data = (object)$data;
2641 $data->course = $this->get_courseid();
2643 // Apply the date offset to the time end field
2644 $data->timeend = $this->apply_date_offset($data->timeend);
2646 // Map the role from the criteria
2647 if (isset($data->role) && $data->role != '') {
2648 // Newer backups should include roleshortname, which makes this much easier.
2649 if (!empty($data->roleshortname)) {
2650 $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
2651 if (!$roleinstanceid) {
2652 $this->log(
2653 'Could not match the role shortname in course_completion_criteria, so skipping',
2654 backup::LOG_DEBUG
2656 return;
2658 $data->role = $roleinstanceid;
2659 } else {
2660 $data->role = $this->get_mappingid('role', $data->role);
2663 // Check we have an id, otherwise it causes all sorts of bugs.
2664 if (!$data->role) {
2665 $this->log(
2666 'Could not match role in course_completion_criteria, so skipping',
2667 backup::LOG_DEBUG
2669 return;
2673 // If the completion criteria is for a module we need to map the module instance
2674 // to the new module id.
2675 if (!empty($data->moduleinstance) && !empty($data->module)) {
2676 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
2677 if (empty($data->moduleinstance)) {
2678 $this->log(
2679 'Could not match the module instance in course_completion_criteria, so skipping',
2680 backup::LOG_DEBUG
2682 return;
2684 } else {
2685 $data->module = null;
2686 $data->moduleinstance = null;
2689 // We backup the course shortname rather than the ID so that we can match back to the course
2690 if (!empty($data->courseinstanceshortname)) {
2691 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
2692 if (!$courseinstanceid) {
2693 $this->log(
2694 'Could not match the course instance in course_completion_criteria, so skipping',
2695 backup::LOG_DEBUG
2697 return;
2699 } else {
2700 $courseinstanceid = null;
2702 $data->courseinstance = $courseinstanceid;
2704 $params = array(
2705 'course' => $data->course,
2706 'criteriatype' => $data->criteriatype,
2707 'enrolperiod' => $data->enrolperiod,
2708 'courseinstance' => $data->courseinstance,
2709 'module' => $data->module,
2710 'moduleinstance' => $data->moduleinstance,
2711 'timeend' => $data->timeend,
2712 'gradepass' => $data->gradepass,
2713 'role' => $data->role
2715 $newid = $DB->insert_record('course_completion_criteria', $params);
2716 $this->set_mapping('course_completion_criteria', $data->id, $newid);
2720 * Processes course compltion criteria complete records
2722 * @global moodle_database $DB
2723 * @param stdClass $data
2725 public function process_course_completion_crit_compl($data) {
2726 global $DB;
2728 $data = (object)$data;
2730 // This may be empty if criteria could not be restored
2731 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
2733 $data->course = $this->get_courseid();
2734 $data->userid = $this->get_mappingid('user', $data->userid);
2736 if (!empty($data->criteriaid) && !empty($data->userid)) {
2737 $params = array(
2738 'userid' => $data->userid,
2739 'course' => $data->course,
2740 'criteriaid' => $data->criteriaid,
2741 'timecompleted' => $this->apply_date_offset($data->timecompleted)
2743 if (isset($data->gradefinal)) {
2744 $params['gradefinal'] = $data->gradefinal;
2746 if (isset($data->unenroled)) {
2747 $params['unenroled'] = $data->unenroled;
2749 $DB->insert_record('course_completion_crit_compl', $params);
2754 * Process course completions
2756 * @global moodle_database $DB
2757 * @param stdClass $data
2759 public function process_course_completions($data) {
2760 global $DB;
2762 $data = (object)$data;
2764 $data->course = $this->get_courseid();
2765 $data->userid = $this->get_mappingid('user', $data->userid);
2767 if (!empty($data->userid)) {
2768 $params = array(
2769 'userid' => $data->userid,
2770 'course' => $data->course,
2771 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
2772 'timestarted' => $this->apply_date_offset($data->timestarted),
2773 'timecompleted' => $this->apply_date_offset($data->timecompleted),
2774 'reaggregate' => $data->reaggregate
2777 $existing = $DB->get_record('course_completions', array(
2778 'userid' => $data->userid,
2779 'course' => $data->course
2782 // MDL-46651 - If cron writes out a new record before we get to it
2783 // then we should replace it with the Truth data from the backup.
2784 // This may be obsolete after MDL-48518 is resolved
2785 if ($existing) {
2786 $params['id'] = $existing->id;
2787 $DB->update_record('course_completions', $params);
2788 } else {
2789 $DB->insert_record('course_completions', $params);
2795 * Process course completion aggregate methods
2797 * @global moodle_database $DB
2798 * @param stdClass $data
2800 public function process_course_completion_aggr_methd($data) {
2801 global $DB;
2803 $data = (object)$data;
2805 $data->course = $this->get_courseid();
2807 // Only create the course_completion_aggr_methd records if
2808 // the target course has not them defined. MDL-28180
2809 if (!$DB->record_exists('course_completion_aggr_methd', array(
2810 'course' => $data->course,
2811 'criteriatype' => $data->criteriatype))) {
2812 $params = array(
2813 'course' => $data->course,
2814 'criteriatype' => $data->criteriatype,
2815 'method' => $data->method,
2816 'value' => $data->value,
2818 $DB->insert_record('course_completion_aggr_methd', $params);
2825 * This structure step restores course logs (cmid = 0), delegating
2826 * the hard work to the corresponding {@link restore_logs_processor} passing the
2827 * collection of {@link restore_log_rule} rules to be observed as they are defined
2828 * by the task. Note this is only executed based in the 'logs' setting.
2830 * NOTE: This is executed by final task, to have all the activities already restored
2832 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2833 * records are. There are others like 'calendar' and 'upload' that will be handled
2834 * later.
2836 * NOTE: All the missing actions (not able to be restored) are sent to logs for
2837 * debugging purposes
2839 class restore_course_logs_structure_step extends restore_structure_step {
2842 * Conditionally decide if this step should be executed.
2844 * This function checks the following parameter:
2846 * 1. the course/logs.xml file exists
2848 * @return bool true is safe to execute, false otherwise
2850 protected function execute_condition() {
2852 // Check it is included in the backup
2853 $fullpath = $this->task->get_taskbasepath();
2854 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2855 if (!file_exists($fullpath)) {
2856 // Not found, can't restore course logs
2857 return false;
2860 return true;
2863 protected function define_structure() {
2865 $paths = array();
2867 // Simple, one plain level of information contains them
2868 $paths[] = new restore_path_element('log', '/logs/log');
2870 return $paths;
2873 protected function process_log($data) {
2874 global $DB;
2876 $data = (object)($data);
2878 $data->time = $this->apply_date_offset($data->time);
2879 $data->userid = $this->get_mappingid('user', $data->userid);
2880 $data->course = $this->get_courseid();
2881 $data->cmid = 0;
2883 // For any reason user wasn't remapped ok, stop processing this
2884 if (empty($data->userid)) {
2885 return;
2888 // Everything ready, let's delegate to the restore_logs_processor
2890 // Set some fixed values that will save tons of DB requests
2891 $values = array(
2892 'course' => $this->get_courseid());
2893 // Get instance and process log record
2894 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2896 // If we have data, insert it, else something went wrong in the restore_logs_processor
2897 if ($data) {
2898 if (empty($data->url)) {
2899 $data->url = '';
2901 if (empty($data->info)) {
2902 $data->info = '';
2904 // Store the data in the legacy log table if we are still using it.
2905 $manager = get_log_manager();
2906 if (method_exists($manager, 'legacy_add_to_log')) {
2907 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
2908 $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
2915 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2916 * sharing its same structure but modifying the way records are handled
2918 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2920 protected function process_log($data) {
2921 global $DB;
2923 $data = (object)($data);
2925 $data->time = $this->apply_date_offset($data->time);
2926 $data->userid = $this->get_mappingid('user', $data->userid);
2927 $data->course = $this->get_courseid();
2928 $data->cmid = $this->task->get_moduleid();
2930 // For any reason user wasn't remapped ok, stop processing this
2931 if (empty($data->userid)) {
2932 return;
2935 // Everything ready, let's delegate to the restore_logs_processor
2937 // Set some fixed values that will save tons of DB requests
2938 $values = array(
2939 'course' => $this->get_courseid(),
2940 'course_module' => $this->task->get_moduleid(),
2941 $this->task->get_modulename() => $this->task->get_activityid());
2942 // Get instance and process log record
2943 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2945 // If we have data, insert it, else something went wrong in the restore_logs_processor
2946 if ($data) {
2947 if (empty($data->url)) {
2948 $data->url = '';
2950 if (empty($data->info)) {
2951 $data->info = '';
2953 // Store the data in the legacy log table if we are still using it.
2954 $manager = get_log_manager();
2955 if (method_exists($manager, 'legacy_add_to_log')) {
2956 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
2957 $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
2965 * Defines the restore step for advanced grading methods attached to the activity module
2967 class restore_activity_grading_structure_step extends restore_structure_step {
2970 * This step is executed only if the grading file is present
2972 protected function execute_condition() {
2974 $fullpath = $this->task->get_taskbasepath();
2975 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2976 if (!file_exists($fullpath)) {
2977 return false;
2980 return true;
2985 * Declares paths in the grading.xml file we are interested in
2987 protected function define_structure() {
2989 $paths = array();
2990 $userinfo = $this->get_setting_value('userinfo');
2992 $area = new restore_path_element('grading_area', '/areas/area');
2993 $paths[] = $area;
2994 // attach local plugin stucture to $area element
2995 $this->add_plugin_structure('local', $area);
2997 $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
2998 $paths[] = $definition;
2999 $this->add_plugin_structure('gradingform', $definition);
3000 // attach local plugin stucture to $definition element
3001 $this->add_plugin_structure('local', $definition);
3004 if ($userinfo) {
3005 $instance = new restore_path_element('grading_instance',
3006 '/areas/area/definitions/definition/instances/instance');
3007 $paths[] = $instance;
3008 $this->add_plugin_structure('gradingform', $instance);
3009 // attach local plugin stucture to $intance element
3010 $this->add_plugin_structure('local', $instance);
3013 return $paths;
3017 * Processes one grading area element
3019 * @param array $data element data
3021 protected function process_grading_area($data) {
3022 global $DB;
3024 $task = $this->get_task();
3025 $data = (object)$data;
3026 $oldid = $data->id;
3027 $data->component = 'mod_'.$task->get_modulename();
3028 $data->contextid = $task->get_contextid();
3030 $newid = $DB->insert_record('grading_areas', $data);
3031 $this->set_mapping('grading_area', $oldid, $newid);
3035 * Processes one grading definition element
3037 * @param array $data element data
3039 protected function process_grading_definition($data) {
3040 global $DB;
3042 $task = $this->get_task();
3043 $data = (object)$data;
3044 $oldid = $data->id;
3045 $data->areaid = $this->get_new_parentid('grading_area');
3046 $data->copiedfromid = null;
3047 $data->timecreated = time();
3048 $data->usercreated = $task->get_userid();
3049 $data->timemodified = $data->timecreated;
3050 $data->usermodified = $data->usercreated;
3052 $newid = $DB->insert_record('grading_definitions', $data);
3053 $this->set_mapping('grading_definition', $oldid, $newid, true);
3057 * Processes one grading form instance element
3059 * @param array $data element data
3061 protected function process_grading_instance($data) {
3062 global $DB;
3064 $data = (object)$data;
3066 // new form definition id
3067 $newformid = $this->get_new_parentid('grading_definition');
3069 // get the name of the area we are restoring to
3070 $sql = "SELECT ga.areaname
3071 FROM {grading_definitions} gd
3072 JOIN {grading_areas} ga ON gd.areaid = ga.id
3073 WHERE gd.id = ?";
3074 $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
3076 // get the mapped itemid - the activity module is expected to define the mappings
3077 // for each gradable area
3078 $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
3080 $oldid = $data->id;
3081 $data->definitionid = $newformid;
3082 $data->raterid = $this->get_mappingid('user', $data->raterid);
3083 $data->itemid = $newitemid;
3085 $newid = $DB->insert_record('grading_instances', $data);
3086 $this->set_mapping('grading_instance', $oldid, $newid);
3090 * Final operations when the database records are inserted
3092 protected function after_execute() {
3093 // Add files embedded into the definition description
3094 $this->add_related_files('grading', 'description', 'grading_definition');
3100 * This structure step restores the grade items associated with one activity
3101 * All the grade items are made child of the "course" grade item but the original
3102 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3103 * the complete gradebook (categories and calculations), that information is
3104 * available there
3106 class restore_activity_grades_structure_step extends restore_structure_step {
3108 protected function define_structure() {
3110 $paths = array();
3111 $userinfo = $this->get_setting_value('userinfo');
3113 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3114 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3115 if ($userinfo) {
3116 $paths[] = new restore_path_element('grade_grade',
3117 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
3119 return $paths;
3122 protected function process_grade_item($data) {
3123 global $DB;
3125 $data = (object)($data);
3126 $oldid = $data->id; // We'll need these later
3127 $oldparentid = $data->categoryid;
3128 $courseid = $this->get_courseid();
3130 $idnumber = null;
3131 if (!empty($data->idnumber)) {
3132 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
3133 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
3134 // so the best is to keep the ones already in the gradebook
3135 // Potential problem: duplicates if same items are restored more than once. :-(
3136 // This needs to be fixed in some way (outcomes & activities with multiple items)
3137 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
3138 // In any case, verify always for uniqueness
3139 $sql = "SELECT cm.id
3140 FROM {course_modules} cm
3141 WHERE cm.course = :courseid AND
3142 cm.idnumber = :idnumber AND
3143 cm.id <> :cmid";
3144 $params = array(
3145 'courseid' => $courseid,
3146 'idnumber' => $data->idnumber,
3147 'cmid' => $this->task->get_moduleid()
3149 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
3150 $idnumber = $data->idnumber;
3154 if (!empty($data->categoryid)) {
3155 // If the grade category id of the grade item being restored belongs to this course
3156 // then it is a fair assumption that this is the correct grade category for the activity
3157 // and we should leave it in place, if not then unset it.
3158 // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
3159 $conditions = array('id' => $data->categoryid, 'courseid' => $courseid);
3160 if (!$this->task->is_samesite() || !$DB->record_exists('grade_categories', $conditions)) {
3161 unset($data->categoryid);
3165 unset($data->id);
3166 $data->courseid = $this->get_courseid();
3167 $data->iteminstance = $this->task->get_activityid();
3168 $data->idnumber = $idnumber;
3169 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
3170 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
3171 $data->timecreated = $this->apply_date_offset($data->timecreated);
3172 $data->timemodified = $this->apply_date_offset($data->timemodified);
3174 $gradeitem = new grade_item($data, false);
3175 $gradeitem->insert('restore');
3177 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
3178 $gradeitem->sortorder = $data->sortorder;
3179 $gradeitem->update('restore');
3181 // Set mapping, saving the original category id into parentitemid
3182 // gradebook restore (final task) will need it to reorganise items
3183 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
3186 protected function process_grade_grade($data) {
3187 $data = (object)($data);
3188 $olduserid = $data->userid;
3189 $oldid = $data->id;
3190 unset($data->id);
3192 $data->itemid = $this->get_new_parentid('grade_item');
3194 $data->userid = $this->get_mappingid('user', $data->userid, null);
3195 if (!empty($data->userid)) {
3196 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
3197 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
3198 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
3199 $data->overridden = $this->apply_date_offset($data->overridden);
3201 $grade = new grade_grade($data, false);
3202 $grade->insert('restore');
3203 $this->set_mapping('grade_grades', $oldid, $grade->id);
3204 } else {
3205 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
3210 * process activity grade_letters. Note that, while these are possible,
3211 * because grade_letters are contextid based, in practice, only course
3212 * context letters can be defined. So we keep here this method knowing
3213 * it won't be executed ever. gradebook restore will restore course letters.
3215 protected function process_grade_letter($data) {
3216 global $DB;
3218 $data['contextid'] = $this->task->get_contextid();
3219 $gradeletter = (object)$data;
3221 // Check if it exists before adding it
3222 unset($data['id']);
3223 if (!$DB->record_exists('grade_letters', $data)) {
3224 $newitemid = $DB->insert_record('grade_letters', $gradeletter);
3226 // no need to save any grade_letter mapping
3229 public function after_restore() {
3230 // Fix grade item's sortorder after restore, as it might have duplicates.
3231 $courseid = $this->get_task()->get_courseid();
3232 grade_item::fix_duplicate_sortorder($courseid);
3237 * Step in charge of restoring the grade history of an activity.
3239 * This step is added to the task regardless of the setting 'grade_histories'.
3240 * The reason is to allow for a more flexible step in case the logic needs to be
3241 * split accross different settings to control the history of items and/or grades.
3243 class restore_activity_grade_history_structure_step extends restore_structure_step {
3246 * This step is executed only if the grade history file is present.
3248 protected function execute_condition() {
3249 $fullpath = $this->task->get_taskbasepath();
3250 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3251 if (!file_exists($fullpath)) {
3252 return false;
3254 return true;
3257 protected function define_structure() {
3258 $paths = array();
3260 // Settings to use.
3261 $userinfo = $this->get_setting_value('userinfo');
3262 $history = $this->get_setting_value('grade_histories');
3264 if ($userinfo && $history) {
3265 $paths[] = new restore_path_element('grade_grade',
3266 '/grade_history/grade_grades/grade_grade');
3269 return $paths;
3272 protected function process_grade_grade($data) {
3273 global $DB;
3275 $data = (object) $data;
3276 $olduserid = $data->userid;
3277 unset($data->id);
3279 $data->userid = $this->get_mappingid('user', $data->userid, null);
3280 if (!empty($data->userid)) {
3281 // Do not apply the date offsets as this is history.
3282 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
3283 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
3284 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
3285 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
3286 $DB->insert_record('grade_grades_history', $data);
3287 } else {
3288 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
3289 $this->log($message, backup::LOG_DEBUG);
3296 * This structure steps restores one instance + positions of one block
3297 * Note: Positions corresponding to one existing context are restored
3298 * here, but all the ones having unknown contexts are sent to backup_ids
3299 * for a later chance to be restored at the end (final task)
3301 class restore_block_instance_structure_step extends restore_structure_step {
3303 protected function define_structure() {
3305 $paths = array();
3307 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
3308 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
3310 return $paths;
3313 public function process_block($data) {
3314 global $DB, $CFG;
3316 $data = (object)$data; // Handy
3317 $oldcontextid = $data->contextid;
3318 $oldid = $data->id;
3319 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
3321 // Look for the parent contextid
3322 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
3323 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
3326 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
3327 // If there is already one block of that type in the parent context
3328 // and the block is not multiple, stop processing
3329 // Use blockslib loader / method executor
3330 if (!$bi = block_instance($data->blockname)) {
3331 return false;
3334 if (!$bi->instance_allow_multiple()) {
3335 // The block cannot be added twice, so we will check if the same block is already being
3336 // displayed on the same page. For this, rather than mocking a page and using the block_manager
3337 // we use a similar query to the one in block_manager::load_blocks(), this will give us
3338 // a very good idea of the blocks already displayed in the context.
3339 $params = array(
3340 'blockname' => $data->blockname
3343 // Context matching test.
3344 $context = context::instance_by_id($data->parentcontextid);
3345 $contextsql = 'bi.parentcontextid = :contextid';
3346 $params['contextid'] = $context->id;
3348 $parentcontextids = $context->get_parent_context_ids();
3349 if ($parentcontextids) {
3350 list($parentcontextsql, $parentcontextparams) =
3351 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
3352 $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
3353 $params = array_merge($params, $parentcontextparams);
3356 // Page type pattern test.
3357 $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
3358 list($pagetypepatternsql, $pagetypepatternparams) =
3359 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
3360 $params = array_merge($params, $pagetypepatternparams);
3362 // Sub page pattern test.
3363 $subpagepatternsql = 'bi.subpagepattern IS NULL';
3364 if ($data->subpagepattern !== null) {
3365 $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
3366 $params['subpagepattern'] = $data->subpagepattern;
3369 $exists = $DB->record_exists_sql("SELECT bi.id
3370 FROM {block_instances} bi
3371 JOIN {block} b ON b.name = bi.blockname
3372 WHERE bi.blockname = :blockname
3373 AND $contextsql
3374 AND bi.pagetypepattern $pagetypepatternsql
3375 AND $subpagepatternsql", $params);
3376 if ($exists) {
3377 // There is at least one very similar block visible on the page where we
3378 // are trying to restore the block. In these circumstances the block API
3379 // would not allow the user to add another instance of the block, so we
3380 // apply the same rule here.
3381 return false;
3385 // If there is already one block of that type in the parent context
3386 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
3387 // stop processing
3388 $params = array(
3389 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
3390 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
3391 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
3392 if ($birecs = $DB->get_records('block_instances', $params)) {
3393 foreach($birecs as $birec) {
3394 if ($birec->configdata == $data->configdata) {
3395 return false;
3400 // Set task old contextid, blockid and blockname once we know them
3401 $this->task->set_old_contextid($oldcontextid);
3402 $this->task->set_old_blockid($oldid);
3403 $this->task->set_blockname($data->blockname);
3405 // Let's look for anything within configdata neededing processing
3406 // (nulls and uses of legacy file.php)
3407 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
3408 $configdata = (array)unserialize(base64_decode($data->configdata));
3409 foreach ($configdata as $attribute => $value) {
3410 if (in_array($attribute, $attrstotransform)) {
3411 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
3414 $data->configdata = base64_encode(serialize((object)$configdata));
3417 // Create the block instance
3418 $newitemid = $DB->insert_record('block_instances', $data);
3419 // Save the mapping (with restorefiles support)
3420 $this->set_mapping('block_instance', $oldid, $newitemid, true);
3421 // Create the block context
3422 $newcontextid = context_block::instance($newitemid)->id;
3423 // Save the block contexts mapping and sent it to task
3424 $this->set_mapping('context', $oldcontextid, $newcontextid);
3425 $this->task->set_contextid($newcontextid);
3426 $this->task->set_blockid($newitemid);
3428 // Restore block fileareas if declared
3429 $component = 'block_' . $this->task->get_blockname();
3430 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
3431 $this->add_related_files($component, $filearea, null);
3434 // Process block positions, creating them or accumulating for final step
3435 foreach($positions as $position) {
3436 $position = (object)$position;
3437 $position->blockinstanceid = $newitemid; // The instance is always the restored one
3438 // If position is for one already mapped (known) contextid
3439 // process it now, creating the position
3440 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
3441 $position->contextid = $newpositionctxid;
3442 // Create the block position
3443 $DB->insert_record('block_positions', $position);
3445 // The position belongs to an unknown context, send it to backup_ids
3446 // to process them as part of the final steps of restore. We send the
3447 // whole $position object there, hence use the low level method.
3448 } else {
3449 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
3456 * Structure step to restore common course_module information
3458 * This step will process the module.xml file for one activity, in order to restore
3459 * the corresponding information to the course_modules table, skipping various bits
3460 * of information based on CFG settings (groupings, completion...) in order to fullfill
3461 * all the reqs to be able to create the context to be used by all the rest of steps
3462 * in the activity restore task
3464 class restore_module_structure_step extends restore_structure_step {
3466 protected function define_structure() {
3467 global $CFG;
3469 $paths = array();
3471 $module = new restore_path_element('module', '/module');
3472 $paths[] = $module;
3473 if ($CFG->enableavailability) {
3474 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
3475 $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
3478 // Apply for 'format' plugins optional paths at module level
3479 $this->add_plugin_structure('format', $module);
3481 // Apply for 'plagiarism' plugins optional paths at module level
3482 $this->add_plugin_structure('plagiarism', $module);
3484 // Apply for 'local' plugins optional paths at module level
3485 $this->add_plugin_structure('local', $module);
3487 return $paths;
3490 protected function process_module($data) {
3491 global $CFG, $DB;
3493 $data = (object)$data;
3494 $oldid = $data->id;
3495 $this->task->set_old_moduleversion($data->version);
3497 $data->course = $this->task->get_courseid();
3498 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
3499 // Map section (first try by course_section mapping match. Useful in course and section restores)
3500 $data->section = $this->get_mappingid('course_section', $data->sectionid);
3501 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
3502 $params = array(
3503 'course' => $this->get_courseid(),
3504 'section' => $data->sectionnumber);
3505 $data->section = $DB->get_field('course_sections', 'id', $params);
3507 if (!$data->section) { // sectionnumber failed, try to get first section in course
3508 $params = array(
3509 'course' => $this->get_courseid());
3510 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
3512 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
3513 $sectionrec = array(
3514 'course' => $this->get_courseid(),
3515 'section' => 0);
3516 $DB->insert_record('course_sections', $sectionrec); // section 0
3517 $sectionrec = array(
3518 'course' => $this->get_courseid(),
3519 'section' => 1);
3520 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
3522 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
3523 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
3524 $data->idnumber = '';
3526 if (empty($CFG->enablecompletion)) { // completion
3527 $data->completion = 0;
3528 $data->completiongradeitemnumber = null;
3529 $data->completionview = 0;
3530 $data->completionexpected = 0;
3531 } else {
3532 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
3534 if (empty($CFG->enableavailability)) {
3535 $data->availability = null;
3537 // Backups that did not include showdescription, set it to default 0
3538 // (this is not totally necessary as it has a db default, but just to
3539 // be explicit).
3540 if (!isset($data->showdescription)) {
3541 $data->showdescription = 0;
3543 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
3545 if (empty($data->availability)) {
3546 // If there are legacy availablility data fields (and no new format data),
3547 // convert the old fields.
3548 $data->availability = \core_availability\info::convert_legacy_fields(
3549 $data, false);
3550 } else if (!empty($data->groupmembersonly)) {
3551 // There is current availability data, but it still has groupmembersonly
3552 // as well (2.7 backups), convert just that part.
3553 require_once($CFG->dirroot . '/lib/db/upgradelib.php');
3554 $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
3557 // course_module record ready, insert it
3558 $newitemid = $DB->insert_record('course_modules', $data);
3559 // save mapping
3560 $this->set_mapping('course_module', $oldid, $newitemid);
3561 // set the new course_module id in the task
3562 $this->task->set_moduleid($newitemid);
3563 // we can now create the context safely
3564 $ctxid = context_module::instance($newitemid)->id;
3565 // set the new context id in the task
3566 $this->task->set_contextid($ctxid);
3567 // update sequence field in course_section
3568 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
3569 $sequence .= ',' . $newitemid;
3570 } else {
3571 $sequence = $newitemid;
3573 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
3575 // If there is the legacy showavailability data, store this for later use.
3576 // (This data is not present when restoring 'new' backups.)
3577 if (isset($data->showavailability)) {
3578 // Cache the showavailability flag using the backup_ids data field.
3579 restore_dbops::set_backup_ids_record($this->get_restoreid(),
3580 'module_showavailability', $newitemid, 0, null,
3581 (object)array('showavailability' => $data->showavailability));
3586 * Process the legacy availability table record. This table does not exist
3587 * in Moodle 2.7+ but we still support restore.
3589 * @param stdClass $data Record data
3591 protected function process_availability($data) {
3592 $data = (object)$data;
3593 // Simply going to store the whole availability record now, we'll process
3594 // all them later in the final task (once all activities have been restored)
3595 // Let's call the low level one to be able to store the whole object
3596 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
3597 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
3601 * Process the legacy availability fields table record. This table does not
3602 * exist in Moodle 2.7+ but we still support restore.
3604 * @param stdClass $data Record data
3606 protected function process_availability_field($data) {
3607 global $DB;
3608 $data = (object)$data;
3609 // Mark it is as passed by default
3610 $passed = true;
3611 $customfieldid = null;
3613 // If a customfield has been used in order to pass we must be able to match an existing
3614 // customfield by name (data->customfield) and type (data->customfieldtype)
3615 if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
3616 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
3617 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
3618 $passed = false;
3619 } else if (!empty($data->customfield)) {
3620 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
3621 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
3622 $passed = ($customfieldid !== false);
3625 if ($passed) {
3626 // Create the object to insert into the database
3627 $availfield = new stdClass();
3628 $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
3629 $availfield->userfield = $data->userfield;
3630 $availfield->customfieldid = $customfieldid;
3631 $availfield->operator = $data->operator;
3632 $availfield->value = $data->value;
3634 // Get showavailability option.
3635 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
3636 'module_showavailability', $availfield->coursemoduleid);
3637 if (!$showrec) {
3638 // Should not happen.
3639 throw new coding_exception('No matching showavailability record');
3641 $show = $showrec->info->showavailability;
3643 // The $availfieldobject is now in the format used in the old
3644 // system. Interpret this and convert to new system.
3645 $currentvalue = $DB->get_field('course_modules', 'availability',
3646 array('id' => $availfield->coursemoduleid), MUST_EXIST);
3647 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
3648 $currentvalue, $availfield, $show);
3649 $DB->set_field('course_modules', 'availability', $newvalue,
3650 array('id' => $availfield->coursemoduleid));
3656 * Structure step that will process the user activity completion
3657 * information if all these conditions are met:
3658 * - Target site has completion enabled ($CFG->enablecompletion)
3659 * - Activity includes completion info (file_exists)
3661 class restore_userscompletion_structure_step extends restore_structure_step {
3663 * To conditionally decide if this step must be executed
3664 * Note the "settings" conditions are evaluated in the
3665 * corresponding task. Here we check for other conditions
3666 * not being restore settings (files, site settings...)
3668 protected function execute_condition() {
3669 global $CFG;
3671 // Completion disabled in this site, don't execute
3672 if (empty($CFG->enablecompletion)) {
3673 return false;
3676 // No user completion info found, don't execute
3677 $fullpath = $this->task->get_taskbasepath();
3678 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3679 if (!file_exists($fullpath)) {
3680 return false;
3683 // Arrived here, execute the step
3684 return true;
3687 protected function define_structure() {
3689 $paths = array();
3691 $paths[] = new restore_path_element('completion', '/completions/completion');
3693 return $paths;
3696 protected function process_completion($data) {
3697 global $DB;
3699 $data = (object)$data;
3701 $data->coursemoduleid = $this->task->get_moduleid();
3702 $data->userid = $this->get_mappingid('user', $data->userid);
3703 $data->timemodified = $this->apply_date_offset($data->timemodified);
3705 // Find the existing record
3706 $existing = $DB->get_record('course_modules_completion', array(
3707 'coursemoduleid' => $data->coursemoduleid,
3708 'userid' => $data->userid), 'id, timemodified');
3709 // Check we didn't already insert one for this cmid and userid
3710 // (there aren't supposed to be duplicates in that field, but
3711 // it was possible until MDL-28021 was fixed).
3712 if ($existing) {
3713 // Update it to these new values, but only if the time is newer
3714 if ($existing->timemodified < $data->timemodified) {
3715 $data->id = $existing->id;
3716 $DB->update_record('course_modules_completion', $data);
3718 } else {
3719 // Normal entry where it doesn't exist already
3720 $DB->insert_record('course_modules_completion', $data);
3726 * Abstract structure step, parent of all the activity structure steps. Used to suuport
3727 * the main <activity ...> tag and process it. Also provides subplugin support for
3728 * activities.
3730 abstract class restore_activity_structure_step extends restore_structure_step {
3732 protected function add_subplugin_structure($subplugintype, $element) {
3734 global $CFG;
3736 // Check the requested subplugintype is a valid one
3737 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
3738 if (!file_exists($subpluginsfile)) {
3739 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
3741 include($subpluginsfile);
3742 if (!array_key_exists($subplugintype, $subplugins)) {
3743 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
3745 // Get all the restore path elements, looking across all the subplugin dirs
3746 $subpluginsdirs = core_component::get_plugin_list($subplugintype);
3747 foreach ($subpluginsdirs as $name => $subpluginsdir) {
3748 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
3749 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
3750 if (file_exists($restorefile)) {
3751 require_once($restorefile);
3752 $restoresubplugin = new $classname($subplugintype, $name, $this);
3753 // Add subplugin paths to the step
3754 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
3760 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
3761 * have the parent task available for wrapping purposes (get course/context....)
3762 * @return restore_task
3764 public function get_task() {
3765 return $this->task;
3769 * Adds support for the 'activity' path that is common to all the activities
3770 * and will be processed globally here
3772 protected function prepare_activity_structure($paths) {
3774 $paths[] = new restore_path_element('activity', '/activity');
3776 return $paths;
3780 * Process the activity path, informing the task about various ids, needed later
3782 protected function process_activity($data) {
3783 $data = (object)$data;
3784 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
3785 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
3786 $this->task->set_old_activityid($data->id); // Save old activityid in task
3790 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
3791 * and will adjust the new activity id (the instance) in various places
3793 protected function apply_activity_instance($newitemid) {
3794 global $DB;
3796 $this->task->set_activityid($newitemid); // Save activity id in task
3797 // Apply the id to course_sections->instanceid
3798 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
3799 // Do the mapping for modulename, preparing it for files by oldcontext
3800 $modulename = $this->task->get_modulename();
3801 $oldid = $this->task->get_old_activityid();
3802 $this->set_mapping($modulename, $oldid, $newitemid, true);
3807 * Structure step in charge of creating/mapping all the qcats and qs
3808 * by parsing the questions.xml file and checking it against the
3809 * results calculated by {@link restore_process_categories_and_questions}
3810 * and stored in backup_ids_temp
3812 class restore_create_categories_and_questions extends restore_structure_step {
3814 /** @var array $cachecategory store a question category */
3815 protected $cachedcategory = null;
3817 protected function define_structure() {
3819 $category = new restore_path_element('question_category', '/question_categories/question_category');
3820 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
3821 $hint = new restore_path_element('question_hint',
3822 '/question_categories/question_category/questions/question/question_hints/question_hint');
3824 $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag');
3826 // Apply for 'qtype' plugins optional paths at question level
3827 $this->add_plugin_structure('qtype', $question);
3829 // Apply for 'local' plugins optional paths at question level
3830 $this->add_plugin_structure('local', $question);
3832 return array($category, $question, $hint, $tag);
3835 protected function process_question_category($data) {
3836 global $DB;
3838 $data = (object)$data;
3839 $oldid = $data->id;
3841 // Check we have one mapping for this category
3842 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
3843 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
3846 // Check we have to create the category (newitemid = 0)
3847 if ($mapping->newitemid) {
3848 return; // newitemid != 0, this category is going to be mapped. Nothing to do
3851 // Arrived here, newitemid = 0, we need to create the category
3852 // we'll do it at parentitemid context, but for CONTEXT_MODULE
3853 // categories, that will be created at CONTEXT_COURSE and moved
3854 // to module context later when the activity is created
3855 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
3856 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
3858 $data->contextid = $mapping->parentitemid;
3860 // Let's create the question_category and save mapping
3861 $newitemid = $DB->insert_record('question_categories', $data);
3862 $this->set_mapping('question_category', $oldid, $newitemid);
3863 // Also annotate them as question_category_created, we need
3864 // that later when remapping parents
3865 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
3868 protected function process_question($data) {
3869 global $DB;
3871 $data = (object)$data;
3872 $oldid = $data->id;
3874 // Check we have one mapping for this question
3875 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
3876 return; // No mapping = this question doesn't need to be created/mapped
3879 // Get the mapped category (cannot use get_new_parentid() because not
3880 // all the categories have been created, so it is not always available
3881 // Instead we get the mapping for the question->parentitemid because
3882 // we have loaded qcatids there for all parsed questions
3883 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
3885 // In the past, there were some very sloppy values of penalty. Fix them.
3886 if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
3887 $data->penalty = 0.3333333;
3889 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
3890 $data->penalty = 0.6666667;
3892 if ($data->penalty >= 1) {
3893 $data->penalty = 1;
3896 $userid = $this->get_mappingid('user', $data->createdby);
3897 $data->createdby = $userid ? $userid : $this->task->get_userid();
3899 $userid = $this->get_mappingid('user', $data->modifiedby);
3900 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
3902 // With newitemid = 0, let's create the question
3903 if (!$questionmapping->newitemid) {
3904 $newitemid = $DB->insert_record('question', $data);
3905 $this->set_mapping('question', $oldid, $newitemid);
3906 // Also annotate them as question_created, we need
3907 // that later when remapping parents (keeping the old categoryid as parentid)
3908 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
3909 } else {
3910 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
3911 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
3912 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
3915 // Note, we don't restore any question files yet
3916 // as far as the CONTEXT_MODULE categories still
3917 // haven't their contexts to be restored to
3918 // The {@link restore_create_question_files}, executed in the final step
3919 // step will be in charge of restoring all the question files
3922 protected function process_question_hint($data) {
3923 global $DB;
3925 $data = (object)$data;
3926 $oldid = $data->id;
3928 // Detect if the question is created or mapped
3929 $oldquestionid = $this->get_old_parentid('question');
3930 $newquestionid = $this->get_new_parentid('question');
3931 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
3933 // If the question has been created by restore, we need to create its question_answers too
3934 if ($questioncreated) {
3935 // Adjust some columns
3936 $data->questionid = $newquestionid;
3937 // Insert record
3938 $newitemid = $DB->insert_record('question_hints', $data);
3940 // The question existed, we need to map the existing question_hints
3941 } else {
3942 // Look in question_hints by hint text matching
3943 $sql = 'SELECT id
3944 FROM {question_hints}
3945 WHERE questionid = ?
3946 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
3947 $params = array($newquestionid, $data->hint);
3948 $newitemid = $DB->get_field_sql($sql, $params);
3950 // Not able to find the hint, let's try cleaning the hint text
3951 // of all the question's hints in DB as slower fallback. MDL-33863.
3952 if (!$newitemid) {
3953 $potentialhints = $DB->get_records('question_hints',
3954 array('questionid' => $newquestionid), '', 'id, hint');
3955 foreach ($potentialhints as $potentialhint) {
3956 // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
3957 $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
3958 $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
3959 if ($cleanhint === $data->hint) {
3960 $newitemid = $data->id;
3965 // If we haven't found the newitemid, something has gone really wrong, question in DB
3966 // is missing hints, exception
3967 if (!$newitemid) {
3968 $info = new stdClass();
3969 $info->filequestionid = $oldquestionid;
3970 $info->dbquestionid = $newquestionid;
3971 $info->hint = $data->hint;
3972 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
3975 // Create mapping (I'm not sure if this is really needed?)
3976 $this->set_mapping('question_hint', $oldid, $newitemid);
3979 protected function process_tag($data) {
3980 global $CFG, $DB;
3982 $data = (object)$data;
3983 $newquestion = $this->get_new_parentid('question');
3984 $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
3985 if (!$questioncreated) {
3986 // This question already exists in the question bank. Nothing for us to do.
3987 return;
3990 if (!empty($CFG->usetags)) { // if enabled in server
3991 // TODO: This is highly inefficient. Each time we add one tag
3992 // we fetch all the existing because tag_set() deletes them
3993 // so everything must be reinserted on each call
3994 $tags = array();
3995 $existingtags = tag_get_tags('question', $newquestion);
3996 // Re-add all the existitng tags
3997 foreach ($existingtags as $existingtag) {
3998 $tags[] = $existingtag->rawname;
4000 // Add the one being restored
4001 $tags[] = $data->rawname;
4002 // Get the category, so we can then later get the context.
4003 $categoryid = $this->get_new_parentid('question_category');
4004 if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
4005 $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
4007 // Send all the tags back to the question
4008 tag_set('question', $newquestion, $tags, 'core_question', $this->cachedcategory->contextid);
4012 protected function after_execute() {
4013 global $DB;
4015 // First of all, recode all the created question_categories->parent fields
4016 $qcats = $DB->get_records('backup_ids_temp', array(
4017 'backupid' => $this->get_restoreid(),
4018 'itemname' => 'question_category_created'));
4019 foreach ($qcats as $qcat) {
4020 $newparent = 0;
4021 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
4022 // Get new parent (mapped or created, so we look in quesiton_category mappings)
4023 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
4024 'backupid' => $this->get_restoreid(),
4025 'itemname' => 'question_category',
4026 'itemid' => $dbcat->parent))) {
4027 // contextids must match always, as far as we always include complete qbanks, just check it
4028 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
4029 if ($dbcat->contextid == $newparentctxid) {
4030 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
4031 } else {
4032 $newparent = 0; // No ctx match for both cats, no parent relationship
4035 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
4036 if (!$newparent) {
4037 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
4041 // Now, recode all the created question->parent fields
4042 $qs = $DB->get_records('backup_ids_temp', array(
4043 'backupid' => $this->get_restoreid(),
4044 'itemname' => 'question_created'));
4045 foreach ($qs as $q) {
4046 $newparent = 0;
4047 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
4048 // Get new parent (mapped or created, so we look in question mappings)
4049 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
4050 'backupid' => $this->get_restoreid(),
4051 'itemname' => 'question',
4052 'itemid' => $dbq->parent))) {
4053 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
4057 // Note, we don't restore any question files yet
4058 // as far as the CONTEXT_MODULE categories still
4059 // haven't their contexts to be restored to
4060 // The {@link restore_create_question_files}, executed in the final step
4061 // step will be in charge of restoring all the question files
4066 * Execution step that will move all the CONTEXT_MODULE question categories
4067 * created at early stages of restore in course context (because modules weren't
4068 * created yet) to their target module (matching by old-new-contextid mapping)
4070 class restore_move_module_questions_categories extends restore_execution_step {
4072 protected function define_execution() {
4073 global $DB;
4075 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
4076 foreach ($contexts as $contextid => $contextlevel) {
4077 // Only if context mapping exists (i.e. the module has been restored)
4078 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
4079 // Update all the qcats having their parentitemid set to the original contextid
4080 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
4081 FROM {backup_ids_temp}
4082 WHERE backupid = ?
4083 AND itemname = 'question_category'
4084 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
4085 foreach ($modulecats as $modulecat) {
4086 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
4087 // And set new contextid also in question_category mapping (will be
4088 // used by {@link restore_create_question_files} later
4089 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
4097 * Execution step that will create all the question/answers/qtype-specific files for the restored
4098 * questions. It must be executed after {@link restore_move_module_questions_categories}
4099 * because only then each question is in its final category and only then the
4100 * contexts can be determined.
4102 class restore_create_question_files extends restore_execution_step {
4104 /** @var array Question-type specific component items cache. */
4105 private $qtypecomponentscache = array();
4108 * Preform the restore_create_question_files step.
4110 protected function define_execution() {
4111 global $DB;
4113 // Track progress, as this task can take a long time.
4114 $progress = $this->task->get_progress();
4115 $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
4117 // Parentitemids of question_createds in backup_ids_temp are the category it is in.
4118 // MUST use a recordset, as there is no unique key in the first (or any) column.
4119 $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
4120 FROM {backup_ids_temp} bi
4121 JOIN {question} q ON q.id = bi.newitemid
4122 WHERE bi.backupid = ?
4123 AND bi.itemname = 'question_created'
4124 ORDER BY categoryid ASC", array($this->get_restoreid()));
4126 $currentcatid = -1;
4127 foreach ($catqtypes as $categoryid => $row) {
4128 $qtype = $row->qtype;
4130 // Check if we are in a new category.
4131 if ($currentcatid !== $categoryid) {
4132 // Report progress for each category.
4133 $progress->progress();
4135 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4136 'question_category', $categoryid)) {
4137 // Something went really wrong, cannot find the question_category for the question_created records.
4138 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
4139 continue;
4142 // Calculate source and target contexts.
4143 $oldctxid = $qcatmapping->info->contextid;
4144 $newctxid = $qcatmapping->parentitemid;
4146 $this->send_common_files($oldctxid, $newctxid, $progress);
4147 $currentcatid = $categoryid;
4150 $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
4152 $catqtypes->close();
4153 $progress->end_progress();
4157 * Send the common question files to a new context.
4159 * @param int $oldctxid Old context id.
4160 * @param int $newctxid New context id.
4161 * @param \core\progress $progress Progress object to use.
4163 private function send_common_files($oldctxid, $newctxid, $progress) {
4164 // Add common question files (question and question_answer ones).
4165 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
4166 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4167 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
4168 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4169 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
4170 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
4171 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
4172 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
4173 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
4174 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
4175 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
4176 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4177 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
4178 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4179 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
4180 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
4184 * Send the question type specific files to a new context.
4186 * @param text $qtype The qtype name to send.
4187 * @param int $oldctxid Old context id.
4188 * @param int $newctxid New context id.
4189 * @param \core\progress $progress Progress object to use.
4191 private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
4192 if (!isset($this->qtypecomponentscache[$qtype])) {
4193 $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
4195 $components = $this->qtypecomponentscache[$qtype];
4196 foreach ($components as $component => $fileareas) {
4197 foreach ($fileareas as $filearea => $mapping) {
4198 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
4199 $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
4206 * Try to restore aliases and references to external files.
4208 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
4209 * We expect that all regular (non-alias) files have already been restored. Make sure
4210 * there is no restore step executed after this one that would call send_files_to_pool() again.
4212 * You may notice we have hardcoded support for Server files, Legacy course files
4213 * and user Private files here at the moment. This could be eventually replaced with a set of
4214 * callbacks in the future if needed.
4216 * @copyright 2012 David Mudrak <david@moodle.com>
4217 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4219 class restore_process_file_aliases_queue extends restore_execution_step {
4221 /** @var array internal cache for {@link choose_repository()} */
4222 private $cachereposbyid = array();
4224 /** @var array internal cache for {@link choose_repository()} */
4225 private $cachereposbytype = array();
4228 * What to do when this step is executed.
4230 protected function define_execution() {
4231 global $DB;
4233 $this->log('processing file aliases queue', backup::LOG_DEBUG);
4235 $fs = get_file_storage();
4237 // Load the queue.
4238 $rs = $DB->get_recordset('backup_ids_temp',
4239 array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'),
4240 '', 'info');
4242 // Iterate over aliases in the queue.
4243 foreach ($rs as $record) {
4244 $info = backup_controller_dbops::decode_backup_temp_info($record->info);
4246 // Try to pick a repository instance that should serve the alias.
4247 $repository = $this->choose_repository($info);
4249 if (is_null($repository)) {
4250 $this->notify_failure($info, 'unable to find a matching repository instance');
4251 continue;
4254 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
4255 // Aliases to Server files and Legacy course files may refer to a file
4256 // contained in the backup file or to some existing file (if we are on the
4257 // same site).
4258 try {
4259 $reference = file_storage::unpack_reference($info->oldfile->reference);
4260 } catch (Exception $e) {
4261 $this->notify_failure($info, 'invalid reference field format');
4262 continue;
4265 // Let's see if the referred source file was also included in the backup.
4266 $candidates = $DB->get_recordset('backup_files_temp', array(
4267 'backupid' => $this->get_restoreid(),
4268 'contextid' => $reference['contextid'],
4269 'component' => $reference['component'],
4270 'filearea' => $reference['filearea'],
4271 'itemid' => $reference['itemid'],
4272 ), '', 'info, newcontextid, newitemid');
4274 $source = null;
4276 foreach ($candidates as $candidate) {
4277 $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
4278 if ($candidateinfo->filename === $reference['filename']
4279 and $candidateinfo->filepath === $reference['filepath']
4280 and !is_null($candidate->newcontextid)
4281 and !is_null($candidate->newitemid) ) {
4282 $source = $candidateinfo;
4283 $source->contextid = $candidate->newcontextid;
4284 $source->itemid = $candidate->newitemid;
4285 break;
4288 $candidates->close();
4290 if ($source) {
4291 // We have an alias that refers to another file also included in
4292 // the backup. Let us change the reference field so that it refers
4293 // to the restored copy of the original file.
4294 $reference = file_storage::pack_reference($source);
4296 // Send the new alias to the filepool.
4297 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4298 $this->notify_success($info);
4299 continue;
4301 } else {
4302 // This is a reference to some moodle file that was not contained in the backup
4303 // file. If we are restoring to the same site, keep the reference untouched
4304 // and restore the alias as is if the referenced file exists.
4305 if ($this->task->is_samesite()) {
4306 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
4307 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
4308 $reference = file_storage::pack_reference($reference);
4309 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4310 $this->notify_success($info);
4311 continue;
4312 } else {
4313 $this->notify_failure($info, 'referenced file not found');
4314 continue;
4317 // If we are at other site, we can't restore this alias.
4318 } else {
4319 $this->notify_failure($info, 'referenced file not included');
4320 continue;
4324 } else if ($info->oldfile->repositorytype === 'user') {
4325 if ($this->task->is_samesite()) {
4326 // For aliases to user Private files at the same site, we have a chance to check
4327 // if the referenced file still exists.
4328 try {
4329 $reference = file_storage::unpack_reference($info->oldfile->reference);
4330 } catch (Exception $e) {
4331 $this->notify_failure($info, 'invalid reference field format');
4332 continue;
4334 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
4335 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
4336 $reference = file_storage::pack_reference($reference);
4337 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4338 $this->notify_success($info);
4339 continue;
4340 } else {
4341 $this->notify_failure($info, 'referenced file not found');
4342 continue;
4345 // If we are at other site, we can't restore this alias.
4346 } else {
4347 $this->notify_failure($info, 'restoring at another site');
4348 continue;
4351 } else {
4352 // This is a reference to some external file such as in boxnet or dropbox.
4353 // If we are restoring to the same site, keep the reference untouched and
4354 // restore the alias as is.
4355 if ($this->task->is_samesite()) {
4356 $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
4357 $this->notify_success($info);
4358 continue;
4360 // If we are at other site, we can't restore this alias.
4361 } else {
4362 $this->notify_failure($info, 'restoring at another site');
4363 continue;
4367 $rs->close();
4371 * Choose the repository instance that should handle the alias.
4373 * At the same site, we can rely on repository instance id and we just
4374 * check it still exists. On other site, try to find matching Server files or
4375 * Legacy course files repository instance. Return null if no matching
4376 * repository instance can be found.
4378 * @param stdClass $info
4379 * @return repository|null
4381 private function choose_repository(stdClass $info) {
4382 global $DB, $CFG;
4383 require_once($CFG->dirroot.'/repository/lib.php');
4385 if ($this->task->is_samesite()) {
4386 // We can rely on repository instance id.
4388 if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
4389 return $this->cachereposbyid[$info->oldfile->repositoryid];
4392 $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
4394 try {
4395 $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
4396 return $this->cachereposbyid[$info->oldfile->repositoryid];
4397 } catch (Exception $e) {
4398 $this->cachereposbyid[$info->oldfile->repositoryid] = null;
4399 return null;
4402 } else {
4403 // We can rely on repository type only.
4405 if (empty($info->oldfile->repositorytype)) {
4406 return null;
4409 if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
4410 return $this->cachereposbytype[$info->oldfile->repositorytype];
4413 $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
4415 // Both Server files and Legacy course files repositories have a single
4416 // instance at the system context to use. Let us try to find it.
4417 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
4418 $sql = "SELECT ri.id
4419 FROM {repository} r
4420 JOIN {repository_instances} ri ON ri.typeid = r.id
4421 WHERE r.type = ? AND ri.contextid = ?";
4422 $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
4423 if (empty($ris)) {
4424 return null;
4426 $repoids = array_keys($ris);
4427 $repoid = reset($repoids);
4428 try {
4429 $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
4430 return $this->cachereposbytype[$info->oldfile->repositorytype];
4431 } catch (Exception $e) {
4432 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
4433 return null;
4437 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
4438 return null;
4443 * Let the user know that the given alias was successfully restored
4445 * @param stdClass $info
4447 private function notify_success(stdClass $info) {
4448 $filedesc = $this->describe_alias($info);
4449 $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
4453 * Let the user know that the given alias can't be restored
4455 * @param stdClass $info
4456 * @param string $reason detailed reason to be logged
4458 private function notify_failure(stdClass $info, $reason = '') {
4459 $filedesc = $this->describe_alias($info);
4460 if ($reason) {
4461 $reason = ' ('.$reason.')';
4463 $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
4464 $this->add_result_item('file_aliases_restore_failures', $filedesc);
4468 * Return a human readable description of the alias file
4470 * @param stdClass $info
4471 * @return string
4473 private function describe_alias(stdClass $info) {
4475 $filedesc = $this->expected_alias_location($info->newfile);
4477 if (!is_null($info->oldfile->source)) {
4478 $filedesc .= ' ('.$info->oldfile->source.')';
4481 return $filedesc;
4485 * Return the expected location of a file
4487 * Please note this may and may not work as a part of URL to pluginfile.php
4488 * (depends on how the given component/filearea deals with the itemid).
4490 * @param stdClass $filerecord
4491 * @return string
4493 private function expected_alias_location($filerecord) {
4495 $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
4496 if (!is_null($filerecord->itemid)) {
4497 $filedesc .= '/'.$filerecord->itemid;
4499 $filedesc .= $filerecord->filepath.$filerecord->filename;
4501 return $filedesc;
4505 * Append a value to the given resultset
4507 * @param string $name name of the result containing a list of values
4508 * @param mixed $value value to add as another item in that result
4510 private function add_result_item($name, $value) {
4512 $results = $this->task->get_results();
4514 if (isset($results[$name])) {
4515 if (!is_array($results[$name])) {
4516 throw new coding_exception('Unable to append a result item into a non-array structure.');
4518 $current = $results[$name];
4519 $current[] = $value;
4520 $this->task->add_result(array($name => $current));
4522 } else {
4523 $this->task->add_result(array($name => array($value)));
4530 * Abstract structure step, to be used by all the activities using core questions stuff
4531 * (like the quiz module), to support qtype plugins, states and sessions
4533 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
4534 /** @var array question_attempt->id to qtype. */
4535 protected $qtypes = array();
4536 /** @var array question_attempt->id to questionid. */
4537 protected $newquestionids = array();
4540 * Attach below $element (usually attempts) the needed restore_path_elements
4541 * to restore question_usages and all they contain.
4543 * If you use the $nameprefix parameter, then you will need to implement some
4544 * extra methods in your class, like
4546 * protected function process_{nameprefix}question_attempt($data) {
4547 * $this->restore_question_usage_worker($data, '{nameprefix}');
4549 * protected function process_{nameprefix}question_attempt($data) {
4550 * $this->restore_question_attempt_worker($data, '{nameprefix}');
4552 * protected function process_{nameprefix}question_attempt_step($data) {
4553 * $this->restore_question_attempt_step_worker($data, '{nameprefix}');
4556 * @param restore_path_element $element the parent element that the usages are stored inside.
4557 * @param array $paths the paths array that is being built.
4558 * @param string $nameprefix should match the prefix passed to the corresponding
4559 * backup_questions_activity_structure_step::add_question_usages call.
4561 protected function add_question_usages($element, &$paths, $nameprefix = '') {
4562 // Check $element is restore_path_element
4563 if (! $element instanceof restore_path_element) {
4564 throw new restore_step_exception('element_must_be_restore_path_element', $element);
4567 // Check $paths is one array
4568 if (!is_array($paths)) {
4569 throw new restore_step_exception('paths_must_be_array', $paths);
4571 $paths[] = new restore_path_element($nameprefix . 'question_usage',
4572 $element->get_path() . "/{$nameprefix}question_usage");
4573 $paths[] = new restore_path_element($nameprefix . 'question_attempt',
4574 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
4575 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
4576 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
4577 true);
4578 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
4579 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
4583 * Process question_usages
4585 protected function process_question_usage($data) {
4586 $this->restore_question_usage_worker($data, '');
4590 * Process question_attempts
4592 protected function process_question_attempt($data) {
4593 $this->restore_question_attempt_worker($data, '');
4597 * Process question_attempt_steps
4599 protected function process_question_attempt_step($data) {
4600 $this->restore_question_attempt_step_worker($data, '');
4604 * This method does the acutal work for process_question_usage or
4605 * process_{nameprefix}_question_usage.
4606 * @param array $data the data from the XML file.
4607 * @param string $nameprefix the element name prefix.
4609 protected function restore_question_usage_worker($data, $nameprefix) {
4610 global $DB;
4612 // Clear our caches.
4613 $this->qtypes = array();
4614 $this->newquestionids = array();
4616 $data = (object)$data;
4617 $oldid = $data->id;
4619 $oldcontextid = $this->get_task()->get_old_contextid();
4620 $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
4622 // Everything ready, insert (no mapping needed)
4623 $newitemid = $DB->insert_record('question_usages', $data);
4625 $this->inform_new_usage_id($newitemid);
4627 $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
4631 * When process_question_usage creates the new usage, it calls this method
4632 * to let the activity link to the new usage. For example, the quiz uses
4633 * this method to set quiz_attempts.uniqueid to the new usage id.
4634 * @param integer $newusageid
4636 abstract protected function inform_new_usage_id($newusageid);
4639 * This method does the acutal work for process_question_attempt or
4640 * process_{nameprefix}_question_attempt.
4641 * @param array $data the data from the XML file.
4642 * @param string $nameprefix the element name prefix.
4644 protected function restore_question_attempt_worker($data, $nameprefix) {
4645 global $DB;
4647 $data = (object)$data;
4648 $oldid = $data->id;
4649 $question = $this->get_mapping('question', $data->questionid);
4651 $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
4652 $data->questionid = $question->newitemid;
4653 if (!property_exists($data, 'variant')) {
4654 $data->variant = 1;
4656 $data->timemodified = $this->apply_date_offset($data->timemodified);
4658 if (!property_exists($data, 'maxfraction')) {
4659 $data->maxfraction = 1;
4662 $newitemid = $DB->insert_record('question_attempts', $data);
4664 $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
4665 $this->qtypes[$newitemid] = $question->info->qtype;
4666 $this->newquestionids[$newitemid] = $data->questionid;
4670 * This method does the acutal work for process_question_attempt_step or
4671 * process_{nameprefix}_question_attempt_step.
4672 * @param array $data the data from the XML file.
4673 * @param string $nameprefix the element name prefix.
4675 protected function restore_question_attempt_step_worker($data, $nameprefix) {
4676 global $DB;
4678 $data = (object)$data;
4679 $oldid = $data->id;
4681 // Pull out the response data.
4682 $response = array();
4683 if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
4684 foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
4685 $response[$variable['name']] = $variable['value'];
4688 unset($data->response);
4690 $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
4691 $data->timecreated = $this->apply_date_offset($data->timecreated);
4692 $data->userid = $this->get_mappingid('user', $data->userid);
4694 // Everything ready, insert and create mapping (needed by question_sessions)
4695 $newitemid = $DB->insert_record('question_attempt_steps', $data);
4696 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
4698 // Now process the response data.
4699 $response = $this->questions_recode_response_data(
4700 $this->qtypes[$data->questionattemptid],
4701 $this->newquestionids[$data->questionattemptid],
4702 $data->sequencenumber, $response);
4704 foreach ($response as $name => $value) {
4705 $row = new stdClass();
4706 $row->attemptstepid = $newitemid;
4707 $row->name = $name;
4708 $row->value = $value;
4709 $DB->insert_record('question_attempt_step_data', $row, false);
4714 * Recode the respones data for a particular step of an attempt at at particular question.
4715 * @param string $qtype the question type.
4716 * @param int $newquestionid the question id.
4717 * @param int $sequencenumber the sequence number.
4718 * @param array $response the response data to recode.
4720 public function questions_recode_response_data(
4721 $qtype, $newquestionid, $sequencenumber, array $response) {
4722 $qtyperestorer = $this->get_qtype_restorer($qtype);
4723 if ($qtyperestorer) {
4724 $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
4726 return $response;
4730 * Given a list of question->ids, separated by commas, returns the
4731 * recoded list, with all the restore question mappings applied.
4732 * Note: Used by quiz->questions and quiz_attempts->layout
4733 * Note: 0 = page break (unconverted)
4735 protected function questions_recode_layout($layout) {
4736 // Extracts question id from sequence
4737 if ($questionids = explode(',', $layout)) {
4738 foreach ($questionids as $id => $questionid) {
4739 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
4740 $newquestionid = $this->get_mappingid('question', $questionid);
4741 $questionids[$id] = $newquestionid;
4745 return implode(',', $questionids);
4749 * Get the restore_qtype_plugin subclass for a specific question type.
4750 * @param string $qtype e.g. multichoice.
4751 * @return restore_qtype_plugin instance.
4753 protected function get_qtype_restorer($qtype) {
4754 // Build one static cache to store {@link restore_qtype_plugin}
4755 // while we are needing them, just to save zillions of instantiations
4756 // or using static stuff that will break our nice API
4757 static $qtypeplugins = array();
4759 if (!isset($qtypeplugins[$qtype])) {
4760 $classname = 'restore_qtype_' . $qtype . '_plugin';
4761 if (class_exists($classname)) {
4762 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
4763 } else {
4764 $qtypeplugins[$qtype] = null;
4767 return $qtypeplugins[$qtype];
4770 protected function after_execute() {
4771 parent::after_execute();
4773 // Restore any files belonging to responses.
4774 foreach (question_engine::get_all_response_file_areas() as $filearea) {
4775 $this->add_related_files('question', $filearea, 'question_attempt_step');
4780 * Attach below $element (usually attempts) the needed restore_path_elements
4781 * to restore question attempt data from Moodle 2.0.
4783 * When using this method, the parent element ($element) must be defined with
4784 * $grouped = true. Then, in that elements process method, you must call
4785 * {@link process_legacy_attempt_data()} with the groupded data. See, for
4786 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
4787 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
4788 * @param array $paths the paths array that is being built to describe the
4789 * structure.
4791 protected function add_legacy_question_attempt_data($element, &$paths) {
4792 global $CFG;
4793 require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
4795 // Check $element is restore_path_element
4796 if (!($element instanceof restore_path_element)) {
4797 throw new restore_step_exception('element_must_be_restore_path_element', $element);
4799 // Check $paths is one array
4800 if (!is_array($paths)) {
4801 throw new restore_step_exception('paths_must_be_array', $paths);
4804 $paths[] = new restore_path_element('question_state',
4805 $element->get_path() . '/states/state');
4806 $paths[] = new restore_path_element('question_session',
4807 $element->get_path() . '/sessions/session');
4810 protected function get_attempt_upgrader() {
4811 if (empty($this->attemptupgrader)) {
4812 $this->attemptupgrader = new question_engine_attempt_upgrader();
4813 $this->attemptupgrader->prepare_to_restore();
4815 return $this->attemptupgrader;
4819 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
4820 * @param object $data contains all the grouped attempt data to process.
4821 * @param pbject $quiz data about the activity the attempts belong to. Required
4822 * fields are (basically this only works for the quiz module):
4823 * oldquestions => list of question ids in this activity - using old ids.
4824 * preferredbehaviour => the behaviour to use for questionattempts.
4826 protected function process_legacy_quiz_attempt_data($data, $quiz) {
4827 global $DB;
4828 $upgrader = $this->get_attempt_upgrader();
4830 $data = (object)$data;
4832 $layout = explode(',', $data->layout);
4833 $newlayout = $layout;
4835 // Convert each old question_session into a question_attempt.
4836 $qas = array();
4837 foreach (explode(',', $quiz->oldquestions) as $questionid) {
4838 if ($questionid == 0) {
4839 continue;
4842 $newquestionid = $this->get_mappingid('question', $questionid);
4843 if (!$newquestionid) {
4844 throw new restore_step_exception('questionattemptreferstomissingquestion',
4845 $questionid, $questionid);
4848 $question = $upgrader->load_question($newquestionid, $quiz->id);
4850 foreach ($layout as $key => $qid) {
4851 if ($qid == $questionid) {
4852 $newlayout[$key] = $newquestionid;
4856 list($qsession, $qstates) = $this->find_question_session_and_states(
4857 $data, $questionid);
4859 if (empty($qsession) || empty($qstates)) {
4860 throw new restore_step_exception('questionattemptdatamissing',
4861 $questionid, $questionid);
4864 list($qsession, $qstates) = $this->recode_legacy_response_data(
4865 $question, $qsession, $qstates);
4867 $data->layout = implode(',', $newlayout);
4868 $qas[$newquestionid] = $upgrader->convert_question_attempt(
4869 $quiz, $data, $question, $qsession, $qstates);
4872 // Now create a new question_usage.
4873 $usage = new stdClass();
4874 $usage->component = 'mod_quiz';
4875 $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
4876 $usage->preferredbehaviour = $quiz->preferredbehaviour;
4877 $usage->id = $DB->insert_record('question_usages', $usage);
4879 $this->inform_new_usage_id($usage->id);
4881 $data->uniqueid = $usage->id;
4882 $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
4883 $this->questions_recode_layout($quiz->oldquestions));
4886 protected function find_question_session_and_states($data, $questionid) {
4887 $qsession = null;
4888 foreach ($data->sessions['session'] as $session) {
4889 if ($session['questionid'] == $questionid) {
4890 $qsession = (object) $session;
4891 break;
4895 $qstates = array();
4896 foreach ($data->states['state'] as $state) {
4897 if ($state['question'] == $questionid) {
4898 // It would be natural to use $state['seq_number'] as the array-key
4899 // here, but it seems that buggy behaviour in 2.0 and early can
4900 // mean that that is not unique, so we use id, which is guaranteed
4901 // to be unique.
4902 $qstates[$state['id']] = (object) $state;
4905 ksort($qstates);
4906 $qstates = array_values($qstates);
4908 return array($qsession, $qstates);
4912 * Recode any ids in the response data
4913 * @param object $question the question data
4914 * @param object $qsession the question sessions.
4915 * @param array $qstates the question states.
4917 protected function recode_legacy_response_data($question, $qsession, $qstates) {
4918 $qsession->questionid = $question->id;
4920 foreach ($qstates as &$state) {
4921 $state->question = $question->id;
4922 $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
4925 return array($qsession, $qstates);
4929 * Recode the legacy answer field.
4930 * @param object $state the state to recode the answer of.
4931 * @param string $qtype the question type.
4933 public function restore_recode_legacy_answer($state, $qtype) {
4934 $restorer = $this->get_qtype_restorer($qtype);
4935 if ($restorer) {
4936 return $restorer->recode_legacy_state_answer($state);
4937 } else {
4938 return $state->answer;