Merge branch 'MDL-20367-master' of git://github.com/damyon/moodle
[moodle.git] / backup / moodle2 / restore_stepslib.php
blob3035c7e35781e69022a7507d81244c304af762c2
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) {
143 protected function process_grade_item($data) {
144 global $DB;
146 $data = (object)$data;
148 $oldid = $data->id;
149 $data->course = $this->get_courseid();
151 $data->courseid = $this->get_courseid();
153 if ($data->itemtype=='manual') {
154 // manual grade items store category id in categoryid
155 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
156 // if mapping failed put in course's grade category
157 if (NULL == $data->categoryid) {
158 $coursecat = grade_category::fetch_course_category($this->get_courseid());
159 $data->categoryid = $coursecat->id;
161 } else if ($data->itemtype=='course') {
162 // course grade item stores their category id in iteminstance
163 $coursecat = grade_category::fetch_course_category($this->get_courseid());
164 $data->iteminstance = $coursecat->id;
165 } else if ($data->itemtype=='category') {
166 // category grade items store their category id in iteminstance
167 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
168 } else {
169 throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
172 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
173 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
175 $data->locktime = $this->apply_date_offset($data->locktime);
176 $data->timecreated = $this->apply_date_offset($data->timecreated);
177 $data->timemodified = $this->apply_date_offset($data->timemodified);
179 $coursecategory = $newitemid = null;
180 //course grade item should already exist so updating instead of inserting
181 if($data->itemtype=='course') {
182 //get the ID of the already created grade item
183 $gi = new stdclass();
184 $gi->courseid = $this->get_courseid();
185 $gi->itemtype = $data->itemtype;
187 //need to get the id of the grade_category that was automatically created for the course
188 $category = new stdclass();
189 $category->courseid = $this->get_courseid();
190 $category->parent = null;
191 //course category fullname starts out as ? but may be edited
192 //$category->fullname = '?';
193 $coursecategory = $DB->get_record('grade_categories', (array)$category);
194 $gi->iteminstance = $coursecategory->id;
196 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
197 if (!empty($existinggradeitem)) {
198 $data->id = $newitemid = $existinggradeitem->id;
199 $DB->update_record('grade_items', $data);
201 } else if ($data->itemtype == 'manual') {
202 // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
203 $gi = array(
204 'itemtype' => $data->itemtype,
205 'courseid' => $data->courseid,
206 'itemname' => $data->itemname,
207 'categoryid' => $data->categoryid,
209 $newitemid = $DB->get_field('grade_items', 'id', $gi);
212 if (empty($newitemid)) {
213 //in case we found the course category but still need to insert the course grade item
214 if ($data->itemtype=='course' && !empty($coursecategory)) {
215 $data->iteminstance = $coursecategory->id;
218 $newitemid = $DB->insert_record('grade_items', $data);
220 $this->set_mapping('grade_item', $oldid, $newitemid);
223 protected function process_grade_grade($data) {
224 global $DB;
226 $data = (object)$data;
227 $oldid = $data->id;
228 $olduserid = $data->userid;
230 $data->itemid = $this->get_new_parentid('grade_item');
232 $data->userid = $this->get_mappingid('user', $data->userid, null);
233 if (!empty($data->userid)) {
234 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
235 $data->locktime = $this->apply_date_offset($data->locktime);
236 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
237 $data->overridden = $this->apply_date_offset($data->overridden);
238 $data->timecreated = $this->apply_date_offset($data->timecreated);
239 $data->timemodified = $this->apply_date_offset($data->timemodified);
241 $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
242 if ($gradeexists) {
243 $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
244 $this->log($message, backup::LOG_DEBUG);
245 } else {
246 $newitemid = $DB->insert_record('grade_grades', $data);
247 $this->set_mapping('grade_grades', $oldid, $newitemid);
249 } else {
250 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
251 $this->log($message, backup::LOG_DEBUG);
255 protected function process_grade_category($data) {
256 global $DB;
258 $data = (object)$data;
259 $oldid = $data->id;
261 $data->course = $this->get_courseid();
262 $data->courseid = $data->course;
264 $data->timecreated = $this->apply_date_offset($data->timecreated);
265 $data->timemodified = $this->apply_date_offset($data->timemodified);
267 $newitemid = null;
268 //no parent means a course level grade category. That may have been created when the course was created
269 if(empty($data->parent)) {
270 //parent was being saved as 0 when it should be null
271 $data->parent = null;
273 //get the already created course level grade category
274 $category = new stdclass();
275 $category->courseid = $this->get_courseid();
276 $category->parent = null;
278 $coursecategory = $DB->get_record('grade_categories', (array)$category);
279 if (!empty($coursecategory)) {
280 $data->id = $newitemid = $coursecategory->id;
281 $DB->update_record('grade_categories', $data);
285 // Add a warning about a removed setting.
286 if (!empty($data->aggregatesubcats)) {
287 set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
290 //need to insert a course category
291 if (empty($newitemid)) {
292 $newitemid = $DB->insert_record('grade_categories', $data);
294 $this->set_mapping('grade_category', $oldid, $newitemid);
296 protected function process_grade_letter($data) {
297 global $DB;
299 $data = (object)$data;
300 $oldid = $data->id;
302 $data->contextid = context_course::instance($this->get_courseid())->id;
304 $gradeletter = (array)$data;
305 unset($gradeletter['id']);
306 if (!$DB->record_exists('grade_letters', $gradeletter)) {
307 $newitemid = $DB->insert_record('grade_letters', $data);
308 } else {
309 $newitemid = $data->id;
312 $this->set_mapping('grade_letter', $oldid, $newitemid);
314 protected function process_grade_setting($data) {
315 global $DB;
317 $data = (object)$data;
318 $oldid = $data->id;
320 $data->courseid = $this->get_courseid();
322 if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
323 $newitemid = $DB->insert_record('grade_settings', $data);
324 } else {
325 $newitemid = $data->id;
328 $this->set_mapping('grade_setting', $oldid, $newitemid);
332 * put all activity grade items in the correct grade category and mark all for recalculation
334 protected function after_execute() {
335 global $DB;
337 $conditions = array(
338 'backupid' => $this->get_restoreid(),
339 'itemname' => 'grade_item'//,
340 //'itemid' => $itemid
342 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
344 // We need this for calculation magic later on.
345 $mappings = array();
347 if (!empty($rs)) {
348 foreach($rs as $grade_item_backup) {
350 // Store the oldid with the new id.
351 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
353 $updateobj = new stdclass();
354 $updateobj->id = $grade_item_backup->newitemid;
356 //if this is an activity grade item that needs to be put back in its correct category
357 if (!empty($grade_item_backup->parentitemid)) {
358 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
359 if (!is_null($oldcategoryid)) {
360 $updateobj->categoryid = $oldcategoryid;
361 $DB->update_record('grade_items', $updateobj);
363 } else {
364 //mark course and category items as needing to be recalculated
365 $updateobj->needsupdate=1;
366 $DB->update_record('grade_items', $updateobj);
370 $rs->close();
372 // We need to update the calculations for calculated grade items that may reference old
373 // grade item ids using ##gi\d+##.
374 // $mappings can be empty, use 0 if so (won't match ever)
375 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
376 $sql = "SELECT gi.id, gi.calculation
377 FROM {grade_items} gi
378 WHERE gi.id {$sql} AND
379 calculation IS NOT NULL";
380 $rs = $DB->get_recordset_sql($sql, $params);
381 foreach ($rs as $gradeitem) {
382 // Collect all of the used grade item id references
383 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
384 // This calculation doesn't reference any other grade items... EASY!
385 continue;
387 // For this next bit we are going to do the replacement of id's in two steps:
388 // 1. We will replace all old id references with a special mapping reference.
389 // 2. We will replace all mapping references with id's
390 // Why do we do this?
391 // Because there potentially there will be an overlap of ids within the query and we
392 // we substitute the wrong id.. safest way around this is the two step system
393 $calculationmap = array();
394 $mapcount = 0;
395 foreach ($matches[1] as $match) {
396 // Check that the old id is known to us, if not it was broken to begin with and will
397 // continue to be broken.
398 if (!array_key_exists($match, $mappings)) {
399 continue;
401 // Our special mapping key
402 $mapping = '##MAPPING'.$mapcount.'##';
403 // The old id that exists within the calculation now
404 $oldid = '##gi'.$match.'##';
405 // The new id that we want to replace the old one with.
406 $newid = '##gi'.$mappings[$match].'##';
407 // Replace in the special mapping key
408 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
409 // And record the mapping
410 $calculationmap[$mapping] = $newid;
411 $mapcount++;
413 // Iterate all special mappings for this calculation and replace in the new id's
414 foreach ($calculationmap as $mapping => $newid) {
415 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
417 // Update the calculation now that its being remapped
418 $DB->update_record('grade_items', $gradeitem);
420 $rs->close();
422 // Need to correct the grade category path and parent
423 $conditions = array(
424 'courseid' => $this->get_courseid()
427 $rs = $DB->get_recordset('grade_categories', $conditions);
428 // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
429 foreach ($rs as $gc) {
430 if (!empty($gc->parent)) {
431 $grade_category = new stdClass();
432 $grade_category->id = $gc->id;
433 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
434 $DB->update_record('grade_categories', $grade_category);
437 $rs->close();
439 // Now we can rebuild all the paths
440 $rs = $DB->get_recordset('grade_categories', $conditions);
441 foreach ($rs as $gc) {
442 $grade_category = new stdClass();
443 $grade_category->id = $gc->id;
444 $grade_category->path = grade_category::build_path($gc);
445 $grade_category->depth = substr_count($grade_category->path, '/') - 1;
446 $DB->update_record('grade_categories', $grade_category);
448 $rs->close();
450 // Restore marks items as needing update. Update everything now.
451 grade_regrade_final_grades($this->get_courseid());
456 * Step in charge of restoring the grade history of a course.
458 * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
459 * we do not want to restore the history if the gradebook and its content has not been
460 * restored. At least for now.
462 class restore_grade_history_structure_step extends restore_structure_step {
464 protected function execute_condition() {
465 global $CFG, $DB;
467 // No gradebook info found, don't execute.
468 $fullpath = $this->task->get_taskbasepath();
469 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
470 if (!file_exists($fullpath)) {
471 return false;
474 // Some module present in backup file isn't available to restore in this site, don't execute.
475 if ($this->task->is_missing_modules()) {
476 return false;
479 // Some activity has been excluded to be restored, don't execute.
480 if ($this->task->is_excluding_activities()) {
481 return false;
484 // There should only be one grade category (the 1 associated with the course itself).
485 $category = new stdclass();
486 $category->courseid = $this->get_courseid();
487 $catcount = $DB->count_records('grade_categories', (array)$category);
488 if ($catcount > 1) {
489 return false;
492 // Arrived here, execute the step.
493 return true;
496 protected function define_structure() {
497 $paths = array();
499 // Settings to use.
500 $userinfo = $this->get_setting_value('users');
501 $history = $this->get_setting_value('grade_histories');
503 if ($userinfo && $history) {
504 $paths[] = new restore_path_element('grade_grade',
505 '/grade_history/grade_grades/grade_grade');
508 return $paths;
511 protected function process_grade_grade($data) {
512 global $DB;
514 $data = (object)($data);
515 $olduserid = $data->userid;
516 unset($data->id);
518 $data->userid = $this->get_mappingid('user', $data->userid, null);
519 if (!empty($data->userid)) {
520 // Do not apply the date offsets as this is history.
521 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
522 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
523 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
524 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
525 $DB->insert_record('grade_grades_history', $data);
526 } else {
527 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
528 $this->log($message, backup::LOG_DEBUG);
535 * decode all the interlinks present in restored content
536 * relying 100% in the restore_decode_processor that handles
537 * both the contents to modify and the rules to be applied
539 class restore_decode_interlinks extends restore_execution_step {
541 protected function define_execution() {
542 // Get the decoder (from the plan)
543 $decoder = $this->task->get_decoder();
544 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
545 // And launch it, everything will be processed
546 $decoder->execute();
551 * first, ensure that we have no gaps in section numbers
552 * and then, rebuid the course cache
554 class restore_rebuild_course_cache extends restore_execution_step {
556 protected function define_execution() {
557 global $DB;
559 // Although there is some sort of auto-recovery of missing sections
560 // present in course/formats... here we check that all the sections
561 // from 0 to MAX(section->section) exist, creating them if necessary
562 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
563 // Iterate over all sections
564 for ($i = 0; $i <= $maxsection; $i++) {
565 // If the section $i doesn't exist, create it
566 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
567 $sectionrec = array(
568 'course' => $this->get_courseid(),
569 'section' => $i);
570 $DB->insert_record('course_sections', $sectionrec); // missing section created
574 // Rebuild cache now that all sections are in place
575 rebuild_course_cache($this->get_courseid());
576 cache_helper::purge_by_event('changesincourse');
577 cache_helper::purge_by_event('changesincoursecat');
582 * Review all the tasks having one after_restore method
583 * executing it to perform some final adjustments of information
584 * not available when the task was executed.
586 class restore_execute_after_restore extends restore_execution_step {
588 protected function define_execution() {
590 // Simply call to the execute_after_restore() method of the task
591 // that always is the restore_final_task
592 $this->task->launch_execute_after_restore();
598 * Review all the (pending) block positions in backup_ids, matching by
599 * contextid, creating positions as needed. This is executed by the
600 * final task, once all the contexts have been created
602 class restore_review_pending_block_positions extends restore_execution_step {
604 protected function define_execution() {
605 global $DB;
607 // Get all the block_position objects pending to match
608 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
609 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
610 // Process block positions, creating them or accumulating for final step
611 foreach($rs as $posrec) {
612 // Get the complete position object out of the info field.
613 $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
614 // If position is for one already mapped (known) contextid
615 // process it now, creating the position, else nothing to
616 // do, position finally discarded
617 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
618 $position->contextid = $newctx->newitemid;
619 // Create the block position
620 $DB->insert_record('block_positions', $position);
623 $rs->close();
629 * Updates the availability data for course modules and sections.
631 * Runs after the restore of all course modules, sections, and grade items has
632 * completed. This is necessary in order to update IDs that have changed during
633 * restore.
635 * @package core_backup
636 * @copyright 2014 The Open University
637 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
639 class restore_update_availability extends restore_execution_step {
641 protected function define_execution() {
642 global $CFG, $DB;
644 // Note: This code runs even if availability is disabled when restoring.
645 // That will ensure that if you later turn availability on for the site,
646 // there will be no incorrect IDs. (It doesn't take long if the restored
647 // data does not contain any availability information.)
649 // Get modinfo with all data after resetting cache.
650 rebuild_course_cache($this->get_courseid(), true);
651 $modinfo = get_fast_modinfo($this->get_courseid());
653 // Get the date offset for this restore.
654 $dateoffset = $this->apply_date_offset(1) - 1;
656 // Update all sections that were restored.
657 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
658 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
659 $sectionsbyid = null;
660 foreach ($rs as $rec) {
661 if (is_null($sectionsbyid)) {
662 $sectionsbyid = array();
663 foreach ($modinfo->get_section_info_all() as $section) {
664 $sectionsbyid[$section->id] = $section;
667 if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
668 // If the section was not fully restored for some reason
669 // (e.g. due to an earlier error), skip it.
670 $this->get_logger()->process('Section not fully restored: id ' .
671 $rec->newitemid, backup::LOG_WARNING);
672 continue;
674 $section = $sectionsbyid[$rec->newitemid];
675 if (!is_null($section->availability)) {
676 $info = new \core_availability\info_section($section);
677 $info->update_after_restore($this->get_restoreid(),
678 $this->get_courseid(), $this->get_logger(), $dateoffset);
681 $rs->close();
683 // Update all modules that were restored.
684 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
685 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
686 foreach ($rs as $rec) {
687 if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
688 // If the module was not fully restored for some reason
689 // (e.g. due to an earlier error), skip it.
690 $this->get_logger()->process('Module not fully restored: id ' .
691 $rec->newitemid, backup::LOG_WARNING);
692 continue;
694 $cm = $modinfo->get_cm($rec->newitemid);
695 if (!is_null($cm->availability)) {
696 $info = new \core_availability\info_module($cm);
697 $info->update_after_restore($this->get_restoreid(),
698 $this->get_courseid(), $this->get_logger(), $dateoffset);
701 $rs->close();
707 * Process legacy module availability records in backup_ids.
709 * Matches course modules and grade item id once all them have been already restored.
710 * Only if all matchings are satisfied the availability condition will be created.
711 * At the same time, it is required for the site to have that functionality enabled.
713 * This step is included only to handle legacy backups (2.6 and before). It does not
714 * do anything for newer backups.
716 * @copyright 2014 The Open University
717 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
719 class restore_process_course_modules_availability extends restore_execution_step {
721 protected function define_execution() {
722 global $CFG, $DB;
724 // Site hasn't availability enabled
725 if (empty($CFG->enableavailability)) {
726 return;
729 // Do both modules and sections.
730 foreach (array('module', 'section') as $table) {
731 // Get all the availability objects to process.
732 $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
733 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
734 // Process availabilities, creating them if everything matches ok.
735 foreach ($rs as $availrec) {
736 $allmatchesok = true;
737 // Get the complete legacy availability object.
738 $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
740 // Note: This code used to update IDs, but that is now handled by the
741 // current code (after restore) instead of this legacy code.
743 // Get showavailability option.
744 $thingid = ($table === 'module') ? $availability->coursemoduleid :
745 $availability->coursesectionid;
746 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
747 $table . '_showavailability', $thingid);
748 if (!$showrec) {
749 // Should not happen.
750 throw new coding_exception('No matching showavailability record');
752 $show = $showrec->info->showavailability;
754 // The $availability object is now in the format used in the old
755 // system. Interpret this and convert to new system.
756 $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
757 array('id' => $thingid), MUST_EXIST);
758 $newvalue = \core_availability\info::add_legacy_availability_condition(
759 $currentvalue, $availability, $show);
760 $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
761 array('id' => $thingid));
764 $rs->close();
770 * Execution step that, *conditionally* (if there isn't preloaded information)
771 * will load the inforef files for all the included course/section/activity tasks
772 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
774 class restore_load_included_inforef_records extends restore_execution_step {
776 protected function define_execution() {
778 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
779 return;
782 // Get all the included tasks
783 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
784 $progress = $this->task->get_progress();
785 $progress->start_progress($this->get_name(), count($tasks));
786 foreach ($tasks as $task) {
787 // Load the inforef.xml file if exists
788 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
789 if (file_exists($inforefpath)) {
790 // Load each inforef file to temp_ids.
791 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
794 $progress->end_progress();
799 * Execution step that will load all the needed files into backup_files_temp
800 * - info: contains the whole original object (times, names...)
801 * (all them being original ids as loaded from xml)
803 class restore_load_included_files extends restore_structure_step {
805 protected function define_structure() {
807 $file = new restore_path_element('file', '/files/file');
809 return array($file);
813 * Process one <file> element from files.xml
815 * @param array $data the element data
817 public function process_file($data) {
819 $data = (object)$data; // handy
821 // load it if needed:
822 // - it it is one of the annotated inforef files (course/section/activity/block)
823 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
824 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
825 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
826 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
827 $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
828 $data->component == 'grouping' || $data->component == 'grade' ||
829 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
830 if ($isfileref || $iscomponent) {
831 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
837 * Execution step that, *conditionally* (if there isn't preloaded information),
838 * will load all the needed roles to backup_temp_ids. They will be stored with
839 * "role" itemname. Also it will perform one automatic mapping to roles existing
840 * in the target site, based in permissions of the user performing the restore,
841 * archetypes and other bits. At the end, each original role will have its associated
842 * target role or 0 if it's going to be skipped. Note we wrap everything over one
843 * restore_dbops method, as far as the same stuff is going to be also executed
844 * by restore prechecks
846 class restore_load_and_map_roles extends restore_execution_step {
848 protected function define_execution() {
849 if ($this->task->get_preloaded_information()) { // if info is already preloaded
850 return;
853 $file = $this->get_basepath() . '/roles.xml';
854 // Load needed toles to temp_ids
855 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
857 // Process roles, mapping/skipping. Any error throws exception
858 // Note we pass controller's info because it can contain role mapping information
859 // about manual mappings performed by UI
860 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);
865 * Execution step that, *conditionally* (if there isn't preloaded information
866 * and users have been selected in settings, will load all the needed users
867 * to backup_temp_ids. They will be stored with "user" itemname and with
868 * their original contextid as paremitemid
870 class restore_load_included_users extends restore_execution_step {
872 protected function define_execution() {
874 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
875 return;
877 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
878 return;
880 $file = $this->get_basepath() . '/users.xml';
881 // Load needed users to temp_ids.
882 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
887 * Execution step that, *conditionally* (if there isn't preloaded information
888 * and users have been selected in settings, will process all the needed users
889 * in order to decide and perform any action with them (create / map / error)
890 * Note: Any error will cause exception, as far as this is the same processing
891 * than the one into restore prechecks (that should have stopped process earlier)
893 class restore_process_included_users extends restore_execution_step {
895 protected function define_execution() {
897 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
898 return;
900 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
901 return;
903 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
904 $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
909 * Execution step that will create all the needed users as calculated
910 * by @restore_process_included_users (those having newiteind = 0)
912 class restore_create_included_users extends restore_execution_step {
914 protected function define_execution() {
916 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
917 $this->task->get_userid(), $this->task->get_progress());
922 * Structure step that will create all the needed groups and groupings
923 * by loading them from the groups.xml file performing the required matches.
924 * Note group members only will be added if restoring user info
926 class restore_groups_structure_step extends restore_structure_step {
928 protected function define_structure() {
930 $paths = array(); // Add paths here
932 $paths[] = new restore_path_element('group', '/groups/group');
933 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
934 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
936 return $paths;
939 // Processing functions go here
940 public function process_group($data) {
941 global $DB;
943 $data = (object)$data; // handy
944 $data->courseid = $this->get_courseid();
946 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
947 // another a group in the same course
948 $context = context_course::instance($data->courseid);
949 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
950 if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
951 unset($data->idnumber);
953 } else {
954 unset($data->idnumber);
957 $oldid = $data->id; // need this saved for later
959 $restorefiles = false; // Only if we end creating the group
961 // Search if the group already exists (by name & description) in the target course
962 $description_clause = '';
963 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
964 if (!empty($data->description)) {
965 $description_clause = ' AND ' .
966 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
967 $params['description'] = $data->description;
969 if (!$groupdb = $DB->get_record_sql("SELECT *
970 FROM {groups}
971 WHERE courseid = :courseid
972 AND name = :grname $description_clause", $params)) {
973 // group doesn't exist, create
974 $newitemid = $DB->insert_record('groups', $data);
975 $restorefiles = true; // We'll restore the files
976 } else {
977 // group exists, use it
978 $newitemid = $groupdb->id;
980 // Save the id mapping
981 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
982 // Invalidate the course group data cache just in case.
983 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
986 public function process_grouping($data) {
987 global $DB;
989 $data = (object)$data; // handy
990 $data->courseid = $this->get_courseid();
992 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
993 // another a grouping in the same course
994 $context = context_course::instance($data->courseid);
995 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
996 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
997 unset($data->idnumber);
999 } else {
1000 unset($data->idnumber);
1003 $oldid = $data->id; // need this saved for later
1004 $restorefiles = false; // Only if we end creating the grouping
1006 // Search if the grouping already exists (by name & description) in the target course
1007 $description_clause = '';
1008 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1009 if (!empty($data->description)) {
1010 $description_clause = ' AND ' .
1011 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1012 $params['description'] = $data->description;
1014 if (!$groupingdb = $DB->get_record_sql("SELECT *
1015 FROM {groupings}
1016 WHERE courseid = :courseid
1017 AND name = :grname $description_clause", $params)) {
1018 // grouping doesn't exist, create
1019 $newitemid = $DB->insert_record('groupings', $data);
1020 $restorefiles = true; // We'll restore the files
1021 } else {
1022 // grouping exists, use it
1023 $newitemid = $groupingdb->id;
1025 // Save the id mapping
1026 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1027 // Invalidate the course group data cache just in case.
1028 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1031 public function process_grouping_group($data) {
1032 global $CFG;
1034 require_once($CFG->dirroot.'/group/lib.php');
1036 $data = (object)$data;
1037 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
1040 protected function after_execute() {
1041 // Add group related files, matching with "group" mappings
1042 $this->add_related_files('group', 'icon', 'group');
1043 $this->add_related_files('group', 'description', 'group');
1044 // Add grouping related files, matching with "grouping" mappings
1045 $this->add_related_files('grouping', 'description', 'grouping');
1046 // Invalidate the course group data.
1047 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1053 * Structure step that will create all the needed group memberships
1054 * by loading them from the groups.xml file performing the required matches.
1056 class restore_groups_members_structure_step extends restore_structure_step {
1058 protected $plugins = null;
1060 protected function define_structure() {
1062 $paths = array(); // Add paths here
1064 if ($this->get_setting_value('users')) {
1065 $paths[] = new restore_path_element('group', '/groups/group');
1066 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1069 return $paths;
1072 public function process_group($data) {
1073 $data = (object)$data; // handy
1075 // HACK ALERT!
1076 // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1077 // Let's fake internal state to make $this->get_new_parentid('group') work.
1079 $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1082 public function process_member($data) {
1083 global $DB, $CFG;
1084 require_once("$CFG->dirroot/group/lib.php");
1086 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1088 $data = (object)$data; // handy
1090 // get parent group->id
1091 $data->groupid = $this->get_new_parentid('group');
1093 // map user newitemid and insert if not member already
1094 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1095 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1096 // Check the component, if any, exists.
1097 if (empty($data->component)) {
1098 groups_add_member($data->groupid, $data->userid);
1100 } else if ((strpos($data->component, 'enrol_') === 0)) {
1101 // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1102 // it is possible that enrolment was restored using different plugin type.
1103 if (!isset($this->plugins)) {
1104 $this->plugins = enrol_get_plugins(true);
1106 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1107 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1108 if (isset($this->plugins[$instance->enrol])) {
1109 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1114 } else {
1115 $dir = core_component::get_component_directory($data->component);
1116 if ($dir and is_dir($dir)) {
1117 if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1118 return;
1121 // Bad luck, plugin could not restore the data, let's add normal membership.
1122 groups_add_member($data->groupid, $data->userid);
1123 $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1124 $this->log($message, backup::LOG_WARNING);
1132 * Structure step that will create all the needed scales
1133 * by loading them from the scales.xml
1135 class restore_scales_structure_step extends restore_structure_step {
1137 protected function define_structure() {
1139 $paths = array(); // Add paths here
1140 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1141 return $paths;
1144 protected function process_scale($data) {
1145 global $DB;
1147 $data = (object)$data;
1149 $restorefiles = false; // Only if we end creating the group
1151 $oldid = $data->id; // need this saved for later
1153 // Look for scale (by 'scale' both in standard (course=0) and current course
1154 // with priority to standard scales (ORDER clause)
1155 // scale is not course unique, use get_record_sql to suppress warning
1156 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1157 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
1158 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1159 if (!$scadb = $DB->get_record_sql("SELECT *
1160 FROM {scale}
1161 WHERE courseid IN (0, :courseid)
1162 AND $compare_scale_clause
1163 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1164 // Remap the user if possible, defaut to user performing the restore if not
1165 $userid = $this->get_mappingid('user', $data->userid);
1166 $data->userid = $userid ? $userid : $this->task->get_userid();
1167 // Remap the course if course scale
1168 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1169 // If global scale (course=0), check the user has perms to create it
1170 // falling to course scale if not
1171 $systemctx = context_system::instance();
1172 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1173 $data->courseid = $this->get_courseid();
1175 // scale doesn't exist, create
1176 $newitemid = $DB->insert_record('scale', $data);
1177 $restorefiles = true; // We'll restore the files
1178 } else {
1179 // scale exists, use it
1180 $newitemid = $scadb->id;
1182 // Save the id mapping (with files support at system context)
1183 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1186 protected function after_execute() {
1187 // Add scales related files, matching with "scale" mappings
1188 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1194 * Structure step that will create all the needed outocomes
1195 * by loading them from the outcomes.xml
1197 class restore_outcomes_structure_step extends restore_structure_step {
1199 protected function define_structure() {
1201 $paths = array(); // Add paths here
1202 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1203 return $paths;
1206 protected function process_outcome($data) {
1207 global $DB;
1209 $data = (object)$data;
1211 $restorefiles = false; // Only if we end creating the group
1213 $oldid = $data->id; // need this saved for later
1215 // Look for outcome (by shortname both in standard (courseid=null) and current course
1216 // with priority to standard outcomes (ORDER clause)
1217 // outcome is not course unique, use get_record_sql to suppress warning
1218 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1219 if (!$outdb = $DB->get_record_sql('SELECT *
1220 FROM {grade_outcomes}
1221 WHERE shortname = :shortname
1222 AND (courseid = :courseid OR courseid IS NULL)
1223 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1224 // Remap the user
1225 $userid = $this->get_mappingid('user', $data->usermodified);
1226 $data->usermodified = $userid ? $userid : $this->task->get_userid();
1227 // Remap the scale
1228 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1229 // Remap the course if course outcome
1230 $data->courseid = $data->courseid ? $this->get_courseid() : null;
1231 // If global outcome (course=null), check the user has perms to create it
1232 // falling to course outcome if not
1233 $systemctx = context_system::instance();
1234 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1235 $data->courseid = $this->get_courseid();
1237 // outcome doesn't exist, create
1238 $newitemid = $DB->insert_record('grade_outcomes', $data);
1239 $restorefiles = true; // We'll restore the files
1240 } else {
1241 // scale exists, use it
1242 $newitemid = $outdb->id;
1244 // Set the corresponding grade_outcomes_courses record
1245 $outcourserec = new stdclass();
1246 $outcourserec->courseid = $this->get_courseid();
1247 $outcourserec->outcomeid = $newitemid;
1248 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1249 $DB->insert_record('grade_outcomes_courses', $outcourserec);
1251 // Save the id mapping (with files support at system context)
1252 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1255 protected function after_execute() {
1256 // Add outcomes related files, matching with "outcome" mappings
1257 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1262 * Execution step that, *conditionally* (if there isn't preloaded information
1263 * will load all the question categories and questions (header info only)
1264 * to backup_temp_ids. They will be stored with "question_category" and
1265 * "question" itemnames and with their original contextid and question category
1266 * id as paremitemids
1268 class restore_load_categories_and_questions extends restore_execution_step {
1270 protected function define_execution() {
1272 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1273 return;
1275 $file = $this->get_basepath() . '/questions.xml';
1276 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1281 * Execution step that, *conditionally* (if there isn't preloaded information)
1282 * will process all the needed categories and questions
1283 * in order to decide and perform any action with them (create / map / error)
1284 * Note: Any error will cause exception, as far as this is the same processing
1285 * than the one into restore prechecks (that should have stopped process earlier)
1287 class restore_process_categories_and_questions extends restore_execution_step {
1289 protected function define_execution() {
1291 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1292 return;
1294 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1299 * Structure step that will read the section.xml creating/updating sections
1300 * as needed, rebuilding course cache and other friends
1302 class restore_section_structure_step extends restore_structure_step {
1304 protected function define_structure() {
1305 global $CFG;
1307 $paths = array();
1309 $section = new restore_path_element('section', '/section');
1310 $paths[] = $section;
1311 if ($CFG->enableavailability) {
1312 $paths[] = new restore_path_element('availability', '/section/availability');
1313 $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1315 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1317 // Apply for 'format' plugins optional paths at section level
1318 $this->add_plugin_structure('format', $section);
1320 // Apply for 'local' plugins optional paths at section level
1321 $this->add_plugin_structure('local', $section);
1323 return $paths;
1326 public function process_section($data) {
1327 global $CFG, $DB;
1328 $data = (object)$data;
1329 $oldid = $data->id; // We'll need this later
1331 $restorefiles = false;
1333 // Look for the section
1334 $section = new stdclass();
1335 $section->course = $this->get_courseid();
1336 $section->section = $data->number;
1337 // Section doesn't exist, create it with all the info from backup
1338 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1339 $section->name = $data->name;
1340 $section->summary = $data->summary;
1341 $section->summaryformat = $data->summaryformat;
1342 $section->sequence = '';
1343 $section->visible = $data->visible;
1344 if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1345 $section->availability = null;
1346 } else {
1347 $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1348 // Include legacy [<2.7] availability data if provided.
1349 if (is_null($section->availability)) {
1350 $section->availability = \core_availability\info::convert_legacy_fields(
1351 $data, true);
1354 $newitemid = $DB->insert_record('course_sections', $section);
1355 $restorefiles = true;
1357 // Section exists, update non-empty information
1358 } else {
1359 $section->id = $secrec->id;
1360 if ((string)$secrec->name === '') {
1361 $section->name = $data->name;
1363 if (empty($secrec->summary)) {
1364 $section->summary = $data->summary;
1365 $section->summaryformat = $data->summaryformat;
1366 $restorefiles = true;
1369 // Don't update availability (I didn't see a useful way to define
1370 // whether existing or new one should take precedence).
1372 $DB->update_record('course_sections', $section);
1373 $newitemid = $secrec->id;
1376 // Annotate the section mapping, with restorefiles option if needed
1377 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1379 // set the new course_section id in the task
1380 $this->task->set_sectionid($newitemid);
1382 // If there is the legacy showavailability data, store this for later use.
1383 // (This data is not present when restoring 'new' backups.)
1384 if (isset($data->showavailability)) {
1385 // Cache the showavailability flag using the backup_ids data field.
1386 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1387 'section_showavailability', $newitemid, 0, null,
1388 (object)array('showavailability' => $data->showavailability));
1391 // Commented out. We never modify course->numsections as far as that is used
1392 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1393 // Note: We keep the code here, to know about and because of the possibility of making this
1394 // optional based on some setting/attribute in the future
1395 // If needed, adjust course->numsections
1396 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1397 // if ($numsections < $section->section) {
1398 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1399 // }
1404 * Process the legacy availability table record. This table does not exist
1405 * in Moodle 2.7+ but we still support restore.
1407 * @param stdClass $data Record data
1409 public function process_availability($data) {
1410 $data = (object)$data;
1411 // Simply going to store the whole availability record now, we'll process
1412 // all them later in the final task (once all activities have been restored)
1413 // Let's call the low level one to be able to store the whole object.
1414 $data->coursesectionid = $this->task->get_sectionid();
1415 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1416 'section_availability', $data->id, 0, null, $data);
1420 * Process the legacy availability fields table record. This table does not
1421 * exist in Moodle 2.7+ but we still support restore.
1423 * @param stdClass $data Record data
1425 public function process_availability_field($data) {
1426 global $DB;
1427 $data = (object)$data;
1428 // Mark it is as passed by default
1429 $passed = true;
1430 $customfieldid = null;
1432 // If a customfield has been used in order to pass we must be able to match an existing
1433 // customfield by name (data->customfield) and type (data->customfieldtype)
1434 if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1435 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1436 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1437 $passed = false;
1438 } else if (!is_null($data->customfield)) {
1439 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1440 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1441 $passed = ($customfieldid !== false);
1444 if ($passed) {
1445 // Create the object to insert into the database
1446 $availfield = new stdClass();
1447 $availfield->coursesectionid = $this->task->get_sectionid();
1448 $availfield->userfield = $data->userfield;
1449 $availfield->customfieldid = $customfieldid;
1450 $availfield->operator = $data->operator;
1451 $availfield->value = $data->value;
1453 // Get showavailability option.
1454 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1455 'section_showavailability', $availfield->coursesectionid);
1456 if (!$showrec) {
1457 // Should not happen.
1458 throw new coding_exception('No matching showavailability record');
1460 $show = $showrec->info->showavailability;
1462 // The $availfield object is now in the format used in the old
1463 // system. Interpret this and convert to new system.
1464 $currentvalue = $DB->get_field('course_sections', 'availability',
1465 array('id' => $availfield->coursesectionid), MUST_EXIST);
1466 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1467 $currentvalue, $availfield, $show);
1468 $DB->set_field('course_sections', 'availability', $newvalue,
1469 array('id' => $availfield->coursesectionid));
1473 public function process_course_format_options($data) {
1474 global $DB;
1475 $data = (object)$data;
1476 $oldid = $data->id;
1477 unset($data->id);
1478 $data->sectionid = $this->task->get_sectionid();
1479 $data->courseid = $this->get_courseid();
1480 $newid = $DB->insert_record('course_format_options', $data);
1481 $this->set_mapping('course_format_options', $oldid, $newid);
1484 protected function after_execute() {
1485 // Add section related files, with 'course_section' itemid to match
1486 $this->add_related_files('course', 'section', 'course_section');
1491 * Structure step that will read the course.xml file, loading it and performing
1492 * various actions depending of the site/restore settings. Note that target
1493 * course always exist before arriving here so this step will be updating
1494 * the course record (never inserting)
1496 class restore_course_structure_step extends restore_structure_step {
1498 * @var bool this gets set to true by {@link process_course()} if we are
1499 * restoring an old coures that used the legacy 'module security' feature.
1500 * If so, we have to do more work in {@link after_execute()}.
1502 protected $legacyrestrictmodules = false;
1505 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1506 * array with array keys the module names ('forum', 'quiz', etc.). These are
1507 * the modules that are allowed according to the data in the backup file.
1508 * In {@link after_execute()} we then have to prevent adding of all the other
1509 * types of activity.
1511 protected $legacyallowedmodules = array();
1513 protected function define_structure() {
1515 $course = new restore_path_element('course', '/course');
1516 $category = new restore_path_element('category', '/course/category');
1517 $tag = new restore_path_element('tag', '/course/tags/tag');
1518 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1520 // Apply for 'format' plugins optional paths at course level
1521 $this->add_plugin_structure('format', $course);
1523 // Apply for 'theme' plugins optional paths at course level
1524 $this->add_plugin_structure('theme', $course);
1526 // Apply for 'report' plugins optional paths at course level
1527 $this->add_plugin_structure('report', $course);
1529 // Apply for 'course report' plugins optional paths at course level
1530 $this->add_plugin_structure('coursereport', $course);
1532 // Apply for plagiarism plugins optional paths at course level
1533 $this->add_plugin_structure('plagiarism', $course);
1535 // Apply for local plugins optional paths at course level
1536 $this->add_plugin_structure('local', $course);
1538 return array($course, $category, $tag, $allowed_module);
1542 * Processing functions go here
1544 * @global moodledatabase $DB
1545 * @param stdClass $data
1547 public function process_course($data) {
1548 global $CFG, $DB;
1550 $data = (object)$data;
1552 $fullname = $this->get_setting_value('course_fullname');
1553 $shortname = $this->get_setting_value('course_shortname');
1554 $startdate = $this->get_setting_value('course_startdate');
1556 // Calculate final course names, to avoid dupes
1557 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1559 // Need to change some fields before updating the course record
1560 $data->id = $this->get_courseid();
1561 $data->fullname = $fullname;
1562 $data->shortname= $shortname;
1564 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1565 // another course on this site.
1566 $context = context::instance_by_id($this->task->get_contextid());
1567 if (!empty($data->idnumber) && has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid()) &&
1568 $this->task->is_samesite() && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1569 // Do not reset idnumber.
1570 } else {
1571 $data->idnumber = '';
1574 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1575 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1576 if (empty($data->hiddensections)) {
1577 $data->hiddensections = 0;
1580 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1581 // then we will need to process restricted modules after execution.
1582 $this->legacyrestrictmodules = !empty($data->restrictmodules);
1584 $data->startdate= $this->apply_date_offset($data->startdate);
1585 if ($data->defaultgroupingid) {
1586 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1588 if (empty($CFG->enablecompletion)) {
1589 $data->enablecompletion = 0;
1590 $data->completionstartonenrol = 0;
1591 $data->completionnotify = 0;
1593 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1594 if (!array_key_exists($data->lang, $languages)) {
1595 $data->lang = '';
1598 $themes = get_list_of_themes(); // Get themes for quick search later
1599 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1600 $data->theme = '';
1603 // Check if this is an old SCORM course format.
1604 if ($data->format == 'scorm') {
1605 $data->format = 'singleactivity';
1606 $data->activitytype = 'scorm';
1609 // Course record ready, update it
1610 $DB->update_record('course', $data);
1612 course_get_format($data)->update_course_format_options($data);
1614 // Role name aliases
1615 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1618 public function process_category($data) {
1619 // Nothing to do with the category. UI sets it before restore starts
1622 public function process_tag($data) {
1623 global $CFG, $DB;
1625 $data = (object)$data;
1627 if (!empty($CFG->usetags)) { // if enabled in server
1628 // TODO: This is highly inneficient. Each time we add one tag
1629 // we fetch all the existing because tag_set() deletes them
1630 // so everything must be reinserted on each call
1631 $tags = array();
1632 $existingtags = tag_get_tags('course', $this->get_courseid());
1633 // Re-add all the existitng tags
1634 foreach ($existingtags as $existingtag) {
1635 $tags[] = $existingtag->rawname;
1637 // Add the one being restored
1638 $tags[] = $data->rawname;
1639 // Send all the tags back to the course
1640 tag_set('course', $this->get_courseid(), $tags, 'core',
1641 context_course::instance($this->get_courseid())->id);
1645 public function process_allowed_module($data) {
1646 $data = (object)$data;
1648 // Backwards compatiblity support for the data that used to be in the
1649 // course_allowed_modules table.
1650 if ($this->legacyrestrictmodules) {
1651 $this->legacyallowedmodules[$data->modulename] = 1;
1655 protected function after_execute() {
1656 global $DB;
1658 // Add course related files, without itemid to match
1659 $this->add_related_files('course', 'summary', null);
1660 $this->add_related_files('course', 'overviewfiles', null);
1662 // Deal with legacy allowed modules.
1663 if ($this->legacyrestrictmodules) {
1664 $context = context_course::instance($this->get_courseid());
1666 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1667 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1668 foreach ($managerroleids as $roleid) {
1669 unset($roleids[$roleid]);
1672 foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1673 if (isset($this->legacyallowedmodules[$modname])) {
1674 // Module is allowed, no worries.
1675 continue;
1678 $capability = 'mod/' . $modname . ':addinstance';
1679 foreach ($roleids as $roleid) {
1680 assign_capability($capability, CAP_PREVENT, $roleid, $context);
1688 * Execution step that will migrate legacy files if present.
1690 class restore_course_legacy_files_step extends restore_execution_step {
1691 public function define_execution() {
1692 global $DB;
1694 // Do a check for legacy files and skip if there are none.
1695 $sql = 'SELECT count(*)
1696 FROM {backup_files_temp}
1697 WHERE backupid = ?
1698 AND contextid = ?
1699 AND component = ?
1700 AND filearea = ?';
1701 $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
1703 if ($DB->count_records_sql($sql, $params)) {
1704 $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
1705 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
1706 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
1712 * Structure step that will read the roles.xml file (at course/activity/block levels)
1713 * containing all the role_assignments and overrides for that context. If corresponding to
1714 * one mapped role, they will be applied to target context. Will observe the role_assignments
1715 * setting to decide if ras are restored.
1717 * Note: this needs to be executed after all users are enrolled.
1719 class restore_ras_and_caps_structure_step extends restore_structure_step {
1720 protected $plugins = null;
1722 protected function define_structure() {
1724 $paths = array();
1726 // Observe the role_assignments setting
1727 if ($this->get_setting_value('role_assignments')) {
1728 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1730 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1732 return $paths;
1736 * Assign roles
1738 * This has to be called after enrolments processing.
1740 * @param mixed $data
1741 * @return void
1743 public function process_assignment($data) {
1744 global $DB;
1746 $data = (object)$data;
1748 // Check roleid, userid are one of the mapped ones
1749 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1750 return;
1752 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1753 return;
1755 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1756 // Only assign roles to not deleted users
1757 return;
1759 if (!$contextid = $this->task->get_contextid()) {
1760 return;
1763 if (empty($data->component)) {
1764 // assign standard manual roles
1765 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1766 role_assign($newroleid, $newuserid, $contextid);
1768 } else if ((strpos($data->component, 'enrol_') === 0)) {
1769 // Deal with enrolment roles - ignore the component and just find out the instance via new id,
1770 // it is possible that enrolment was restored using different plugin type.
1771 if (!isset($this->plugins)) {
1772 $this->plugins = enrol_get_plugins(true);
1774 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1775 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1776 if (isset($this->plugins[$instance->enrol])) {
1777 $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
1782 } else {
1783 $data->roleid = $newroleid;
1784 $data->userid = $newuserid;
1785 $data->contextid = $contextid;
1786 $dir = core_component::get_component_directory($data->component);
1787 if ($dir and is_dir($dir)) {
1788 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
1789 return;
1792 // Bad luck, plugin could not restore the data, let's add normal membership.
1793 role_assign($data->roleid, $data->userid, $data->contextid);
1794 $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
1795 $this->log($message, backup::LOG_WARNING);
1799 public function process_override($data) {
1800 $data = (object)$data;
1802 // Check roleid is one of the mapped ones
1803 $newroleid = $this->get_mappingid('role', $data->roleid);
1804 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1805 if ($newroleid && $this->task->get_contextid()) {
1806 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1807 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1808 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1814 * If no instances yet add default enrol methods the same way as when creating new course in UI.
1816 class restore_default_enrolments_step extends restore_execution_step {
1817 public function define_execution() {
1818 global $DB;
1820 $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
1822 if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
1823 // Something already added instances, do not add default instances.
1824 $plugins = enrol_get_plugins(true);
1825 foreach ($plugins as $plugin) {
1826 $plugin->restore_sync_course($course);
1829 } else {
1830 // Looks like a newly created course.
1831 enrol_course_updated(true, $course, null);
1837 * This structure steps restores the enrol plugins and their underlying
1838 * enrolments, performing all the mappings and/or movements required
1840 class restore_enrolments_structure_step extends restore_structure_step {
1841 protected $enrolsynced = false;
1842 protected $plugins = null;
1843 protected $originalstatus = array();
1846 * Conditionally decide if this step should be executed.
1848 * This function checks the following parameter:
1850 * 1. the course/enrolments.xml file exists
1852 * @return bool true is safe to execute, false otherwise
1854 protected function execute_condition() {
1856 // Check it is included in the backup
1857 $fullpath = $this->task->get_taskbasepath();
1858 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1859 if (!file_exists($fullpath)) {
1860 // Not found, can't restore enrolments info
1861 return false;
1864 return true;
1867 protected function define_structure() {
1869 $paths = array();
1871 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1872 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1874 return $paths;
1878 * Create enrolment instances.
1880 * This has to be called after creation of roles
1881 * and before adding of role assignments.
1883 * @param mixed $data
1884 * @return void
1886 public function process_enrol($data) {
1887 global $DB;
1889 $data = (object)$data;
1890 $oldid = $data->id; // We'll need this later.
1891 unset($data->id);
1893 $this->originalstatus[$oldid] = $data->status;
1895 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
1896 $this->set_mapping('enrol', $oldid, 0);
1897 return;
1900 if (!isset($this->plugins)) {
1901 $this->plugins = enrol_get_plugins(true);
1904 if (!$this->enrolsynced) {
1905 // Make sure that all plugin may create instances and enrolments automatically
1906 // before the first instance restore - this is suitable especially for plugins
1907 // that synchronise data automatically using course->idnumber or by course categories.
1908 foreach ($this->plugins as $plugin) {
1909 $plugin->restore_sync_course($courserec);
1911 $this->enrolsynced = true;
1914 // Map standard fields - plugin has to process custom fields manually.
1915 $data->roleid = $this->get_mappingid('role', $data->roleid);
1916 $data->courseid = $courserec->id;
1918 if ($this->get_setting_value('enrol_migratetomanual')) {
1919 unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
1920 if (!enrol_is_enabled('manual')) {
1921 $this->set_mapping('enrol', $oldid, 0);
1922 return;
1924 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
1925 $instance = reset($instances);
1926 $this->set_mapping('enrol', $oldid, $instance->id);
1927 } else {
1928 if ($data->enrol === 'manual') {
1929 $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
1930 } else {
1931 $instanceid = $this->plugins['manual']->add_default_instance($courserec);
1933 $this->set_mapping('enrol', $oldid, $instanceid);
1936 } else {
1937 if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
1938 $this->set_mapping('enrol', $oldid, 0);
1939 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments";
1940 $this->log($message, backup::LOG_WARNING);
1941 return;
1943 if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
1944 // Let's keep the sortorder in old backups.
1945 } else {
1946 // Prevent problems with colliding sortorders in old backups,
1947 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
1948 unset($data->sortorder);
1950 // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
1951 $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
1956 * Create user enrolments.
1958 * This has to be called after creation of enrolment instances
1959 * and before adding of role assignments.
1961 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
1963 * @param mixed $data
1964 * @return void
1966 public function process_enrolment($data) {
1967 global $DB;
1969 if (!isset($this->plugins)) {
1970 $this->plugins = enrol_get_plugins(true);
1973 $data = (object)$data;
1975 // Process only if parent instance have been mapped.
1976 if ($enrolid = $this->get_new_parentid('enrol')) {
1977 $oldinstancestatus = ENROL_INSTANCE_ENABLED;
1978 $oldenrolid = $this->get_old_parentid('enrol');
1979 if (isset($this->originalstatus[$oldenrolid])) {
1980 $oldinstancestatus = $this->originalstatus[$oldenrolid];
1982 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1983 // And only if user is a mapped one.
1984 if ($userid = $this->get_mappingid('user', $data->userid)) {
1985 if (isset($this->plugins[$instance->enrol])) {
1986 $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
1996 * Make sure the user restoring the course can actually access it.
1998 class restore_fix_restorer_access_step extends restore_execution_step {
1999 protected function define_execution() {
2000 global $CFG, $DB;
2002 if (!$userid = $this->task->get_userid()) {
2003 return;
2006 if (empty($CFG->restorernewroleid)) {
2007 // Bad luck, no fallback role for restorers specified
2008 return;
2011 $courseid = $this->get_courseid();
2012 $context = context_course::instance($courseid);
2014 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2015 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2016 return;
2019 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2020 role_assign($CFG->restorernewroleid, $userid, $context);
2022 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2023 // Extra role is enough, yay!
2024 return;
2027 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2028 // hopefully admin selected suitable $CFG->restorernewroleid ...
2029 if (!enrol_is_enabled('manual')) {
2030 return;
2032 if (!$enrol = enrol_get_plugin('manual')) {
2033 return;
2035 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2036 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2037 $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2038 $enrol->add_instance($course, $fields);
2041 enrol_try_internal_enrol($courseid, $userid);
2047 * This structure steps restores the filters and their configs
2049 class restore_filters_structure_step extends restore_structure_step {
2051 protected function define_structure() {
2053 $paths = array();
2055 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2056 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2058 return $paths;
2061 public function process_active($data) {
2063 $data = (object)$data;
2065 if (strpos($data->filter, 'filter/') === 0) {
2066 $data->filter = substr($data->filter, 7);
2068 } else if (strpos($data->filter, '/') !== false) {
2069 // Unsupported old filter.
2070 return;
2073 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2074 return;
2076 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2079 public function process_config($data) {
2081 $data = (object)$data;
2083 if (strpos($data->filter, 'filter/') === 0) {
2084 $data->filter = substr($data->filter, 7);
2086 } else if (strpos($data->filter, '/') !== false) {
2087 // Unsupported old filter.
2088 return;
2091 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2092 return;
2094 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2100 * This structure steps restores the comments
2101 * Note: Cannot use the comments API because defaults to USER->id.
2102 * That should change allowing to pass $userid
2104 class restore_comments_structure_step extends restore_structure_step {
2106 protected function define_structure() {
2108 $paths = array();
2110 $paths[] = new restore_path_element('comment', '/comments/comment');
2112 return $paths;
2115 public function process_comment($data) {
2116 global $DB;
2118 $data = (object)$data;
2120 // First of all, if the comment has some itemid, ask to the task what to map
2121 $mapping = false;
2122 if ($data->itemid) {
2123 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2124 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2126 // Only restore the comment if has no mapping OR we have found the matching mapping
2127 if (!$mapping || $data->itemid) {
2128 // Only if user mapping and context
2129 $data->userid = $this->get_mappingid('user', $data->userid);
2130 if ($data->userid && $this->task->get_contextid()) {
2131 $data->contextid = $this->task->get_contextid();
2132 // Only if there is another comment with same context/user/timecreated
2133 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2134 if (!$DB->record_exists('comments', $params)) {
2135 $DB->insert_record('comments', $data);
2143 * This structure steps restores the badges and their configs
2145 class restore_badges_structure_step extends restore_structure_step {
2148 * Conditionally decide if this step should be executed.
2150 * This function checks the following parameters:
2152 * 1. Badges and course badges are enabled on the site.
2153 * 2. The course/badges.xml file exists.
2154 * 3. All modules are restorable.
2155 * 4. All modules are marked for restore.
2157 * @return bool True is safe to execute, false otherwise
2159 protected function execute_condition() {
2160 global $CFG;
2162 // First check is badges and course level badges are enabled on this site.
2163 if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2164 // Disabled, don't restore course badges.
2165 return false;
2168 // Check if badges.xml is included in the backup.
2169 $fullpath = $this->task->get_taskbasepath();
2170 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2171 if (!file_exists($fullpath)) {
2172 // Not found, can't restore course badges.
2173 return false;
2176 // Check we are able to restore all backed up modules.
2177 if ($this->task->is_missing_modules()) {
2178 return false;
2181 // Finally check all modules within the backup are being restored.
2182 if ($this->task->is_excluding_activities()) {
2183 return false;
2186 return true;
2189 protected function define_structure() {
2190 $paths = array();
2191 $paths[] = new restore_path_element('badge', '/badges/badge');
2192 $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2193 $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2194 $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2196 return $paths;
2199 public function process_badge($data) {
2200 global $DB, $CFG;
2202 require_once($CFG->libdir . '/badgeslib.php');
2204 $data = (object)$data;
2205 $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2206 if (empty($data->usercreated)) {
2207 $data->usercreated = $this->task->get_userid();
2209 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2210 if (empty($data->usermodified)) {
2211 $data->usermodified = $this->task->get_userid();
2214 // We'll restore the badge image.
2215 $restorefiles = true;
2217 $courseid = $this->get_courseid();
2219 $params = array(
2220 'name' => $data->name,
2221 'description' => $data->description,
2222 'timecreated' => $this->apply_date_offset($data->timecreated),
2223 'timemodified' => $this->apply_date_offset($data->timemodified),
2224 'usercreated' => $data->usercreated,
2225 'usermodified' => $data->usermodified,
2226 'issuername' => $data->issuername,
2227 'issuerurl' => $data->issuerurl,
2228 'issuercontact' => $data->issuercontact,
2229 'expiredate' => $this->apply_date_offset($data->expiredate),
2230 'expireperiod' => $data->expireperiod,
2231 'type' => BADGE_TYPE_COURSE,
2232 'courseid' => $courseid,
2233 'message' => $data->message,
2234 'messagesubject' => $data->messagesubject,
2235 'attachment' => $data->attachment,
2236 'notification' => $data->notification,
2237 'status' => BADGE_STATUS_INACTIVE,
2238 'nextcron' => $this->apply_date_offset($data->nextcron)
2241 $newid = $DB->insert_record('badge', $params);
2242 $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2245 public function process_criterion($data) {
2246 global $DB;
2248 $data = (object)$data;
2250 $params = array(
2251 'badgeid' => $this->get_new_parentid('badge'),
2252 'criteriatype' => $data->criteriatype,
2253 'method' => $data->method
2255 $newid = $DB->insert_record('badge_criteria', $params);
2256 $this->set_mapping('criterion', $data->id, $newid);
2259 public function process_parameter($data) {
2260 global $DB, $CFG;
2262 require_once($CFG->libdir . '/badgeslib.php');
2264 $data = (object)$data;
2265 $criteriaid = $this->get_new_parentid('criterion');
2267 // Parameter array that will go to database.
2268 $params = array();
2269 $params['critid'] = $criteriaid;
2271 $oldparam = explode('_', $data->name);
2273 if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2274 $module = $this->get_mappingid('course_module', $oldparam[1]);
2275 $params['name'] = $oldparam[0] . '_' . $module;
2276 $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2277 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2278 $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2279 $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2280 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2281 $role = $this->get_mappingid('role', $data->value);
2282 if (!empty($role)) {
2283 $params['name'] = 'role_' . $role;
2284 $params['value'] = $role;
2285 } else {
2286 return;
2290 if (!$DB->record_exists('badge_criteria_param', $params)) {
2291 $DB->insert_record('badge_criteria_param', $params);
2295 public function process_manual_award($data) {
2296 global $DB;
2298 $data = (object)$data;
2299 $role = $this->get_mappingid('role', $data->issuerrole);
2301 if (!empty($role)) {
2302 $award = array(
2303 'badgeid' => $this->get_new_parentid('badge'),
2304 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2305 'issuerid' => $this->get_mappingid('user', $data->issuerid),
2306 'issuerrole' => $role,
2307 'datemet' => $this->apply_date_offset($data->datemet)
2310 // Skip the manual award if recipient or issuer can not be mapped to.
2311 if (empty($award['recipientid']) || empty($award['issuerid'])) {
2312 return;
2315 $DB->insert_record('badge_manual_award', $award);
2319 protected function after_execute() {
2320 // Add related files.
2321 $this->add_related_files('badges', 'badgeimage', 'badge');
2326 * This structure steps restores the calendar events
2328 class restore_calendarevents_structure_step extends restore_structure_step {
2330 protected function define_structure() {
2332 $paths = array();
2334 $paths[] = new restore_path_element('calendarevents', '/events/event');
2336 return $paths;
2339 public function process_calendarevents($data) {
2340 global $DB, $SITE;
2342 $data = (object)$data;
2343 $oldid = $data->id;
2344 $restorefiles = true; // We'll restore the files
2345 // Find the userid and the groupid associated with the event. Return if not found.
2346 $data->userid = $this->get_mappingid('user', $data->userid);
2347 if ($data->userid === false) {
2348 return;
2350 if (!empty($data->groupid)) {
2351 $data->groupid = $this->get_mappingid('group', $data->groupid);
2352 if ($data->groupid === false) {
2353 return;
2356 // Handle events with empty eventtype //MDL-32827
2357 if(empty($data->eventtype)) {
2358 if ($data->courseid == $SITE->id) { // Site event
2359 $data->eventtype = "site";
2360 } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2361 // Course assingment event
2362 $data->eventtype = "due";
2363 } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event
2364 $data->eventtype = "course";
2365 } else if ($data->groupid) { // Group event
2366 $data->eventtype = "group";
2367 } else if ($data->userid) { // User event
2368 $data->eventtype = "user";
2369 } else {
2370 return;
2374 $params = array(
2375 'name' => $data->name,
2376 'description' => $data->description,
2377 'format' => $data->format,
2378 'courseid' => $this->get_courseid(),
2379 'groupid' => $data->groupid,
2380 'userid' => $data->userid,
2381 'repeatid' => $data->repeatid,
2382 'modulename' => $data->modulename,
2383 'eventtype' => $data->eventtype,
2384 'timestart' => $this->apply_date_offset($data->timestart),
2385 'timeduration' => $data->timeduration,
2386 'visible' => $data->visible,
2387 'uuid' => $data->uuid,
2388 'sequence' => $data->sequence,
2389 'timemodified' => $this->apply_date_offset($data->timemodified));
2390 if ($this->name == 'activity_calendar') {
2391 $params['instance'] = $this->task->get_activityid();
2392 } else {
2393 $params['instance'] = 0;
2395 $sql = "SELECT id
2396 FROM {event}
2397 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2398 AND courseid = ?
2399 AND repeatid = ?
2400 AND modulename = ?
2401 AND timestart = ?
2402 AND timeduration = ?
2403 AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2404 $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
2405 $result = $DB->record_exists_sql($sql, $arg);
2406 if (empty($result)) {
2407 $newitemid = $DB->insert_record('event', $params);
2408 $this->set_mapping('event', $oldid, $newitemid);
2409 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2413 protected function after_execute() {
2414 // Add related files
2415 $this->add_related_files('calendar', 'event_description', 'event_description');
2419 class restore_course_completion_structure_step extends restore_structure_step {
2422 * Conditionally decide if this step should be executed.
2424 * This function checks parameters that are not immediate settings to ensure
2425 * that the enviroment is suitable for the restore of course completion info.
2427 * This function checks the following four parameters:
2429 * 1. Course completion is enabled on the site
2430 * 2. The backup includes course completion information
2431 * 3. All modules are restorable
2432 * 4. All modules are marked for restore.
2434 * @return bool True is safe to execute, false otherwise
2436 protected function execute_condition() {
2437 global $CFG;
2439 // First check course completion is enabled on this site
2440 if (empty($CFG->enablecompletion)) {
2441 // Disabled, don't restore course completion
2442 return false;
2445 // Check it is included in the backup
2446 $fullpath = $this->task->get_taskbasepath();
2447 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2448 if (!file_exists($fullpath)) {
2449 // Not found, can't restore course completion
2450 return false;
2453 // Check we are able to restore all backed up modules
2454 if ($this->task->is_missing_modules()) {
2455 return false;
2458 // Finally check all modules within the backup are being restored.
2459 if ($this->task->is_excluding_activities()) {
2460 return false;
2463 return true;
2467 * Define the course completion structure
2469 * @return array Array of restore_path_element
2471 protected function define_structure() {
2473 // To know if we are including user completion info
2474 $userinfo = $this->get_setting_value('userscompletion');
2476 $paths = array();
2477 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2478 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2480 if ($userinfo) {
2481 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2482 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2485 return $paths;
2490 * Process course completion criteria
2492 * @global moodle_database $DB
2493 * @param stdClass $data
2495 public function process_course_completion_criteria($data) {
2496 global $DB;
2498 $data = (object)$data;
2499 $data->course = $this->get_courseid();
2501 // Apply the date offset to the time end field
2502 $data->timeend = $this->apply_date_offset($data->timeend);
2504 // Map the role from the criteria
2505 if (!empty($data->role)) {
2506 $data->role = $this->get_mappingid('role', $data->role);
2509 $skipcriteria = false;
2511 // If the completion criteria is for a module we need to map the module instance
2512 // to the new module id.
2513 if (!empty($data->moduleinstance) && !empty($data->module)) {
2514 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
2515 if (empty($data->moduleinstance)) {
2516 $skipcriteria = true;
2518 } else {
2519 $data->module = null;
2520 $data->moduleinstance = null;
2523 // We backup the course shortname rather than the ID so that we can match back to the course
2524 if (!empty($data->courseinstanceshortname)) {
2525 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
2526 if (!$courseinstanceid) {
2527 $skipcriteria = true;
2529 } else {
2530 $courseinstanceid = null;
2532 $data->courseinstance = $courseinstanceid;
2534 if (!$skipcriteria) {
2535 $params = array(
2536 'course' => $data->course,
2537 'criteriatype' => $data->criteriatype,
2538 'enrolperiod' => $data->enrolperiod,
2539 'courseinstance' => $data->courseinstance,
2540 'module' => $data->module,
2541 'moduleinstance' => $data->moduleinstance,
2542 'timeend' => $data->timeend,
2543 'gradepass' => $data->gradepass,
2544 'role' => $data->role
2546 $newid = $DB->insert_record('course_completion_criteria', $params);
2547 $this->set_mapping('course_completion_criteria', $data->id, $newid);
2552 * Processes course compltion criteria complete records
2554 * @global moodle_database $DB
2555 * @param stdClass $data
2557 public function process_course_completion_crit_compl($data) {
2558 global $DB;
2560 $data = (object)$data;
2562 // This may be empty if criteria could not be restored
2563 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
2565 $data->course = $this->get_courseid();
2566 $data->userid = $this->get_mappingid('user', $data->userid);
2568 if (!empty($data->criteriaid) && !empty($data->userid)) {
2569 $params = array(
2570 'userid' => $data->userid,
2571 'course' => $data->course,
2572 'criteriaid' => $data->criteriaid,
2573 'timecompleted' => $this->apply_date_offset($data->timecompleted)
2575 if (isset($data->gradefinal)) {
2576 $params['gradefinal'] = $data->gradefinal;
2578 if (isset($data->unenroled)) {
2579 $params['unenroled'] = $data->unenroled;
2581 $DB->insert_record('course_completion_crit_compl', $params);
2586 * Process course completions
2588 * @global moodle_database $DB
2589 * @param stdClass $data
2591 public function process_course_completions($data) {
2592 global $DB;
2594 $data = (object)$data;
2596 $data->course = $this->get_courseid();
2597 $data->userid = $this->get_mappingid('user', $data->userid);
2599 if (!empty($data->userid)) {
2600 $params = array(
2601 'userid' => $data->userid,
2602 'course' => $data->course,
2603 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
2604 'timestarted' => $this->apply_date_offset($data->timestarted),
2605 'timecompleted' => $this->apply_date_offset($data->timecompleted),
2606 'reaggregate' => $data->reaggregate
2608 $DB->insert_record('course_completions', $params);
2613 * Process course completion aggregate methods
2615 * @global moodle_database $DB
2616 * @param stdClass $data
2618 public function process_course_completion_aggr_methd($data) {
2619 global $DB;
2621 $data = (object)$data;
2623 $data->course = $this->get_courseid();
2625 // Only create the course_completion_aggr_methd records if
2626 // the target course has not them defined. MDL-28180
2627 if (!$DB->record_exists('course_completion_aggr_methd', array(
2628 'course' => $data->course,
2629 'criteriatype' => $data->criteriatype))) {
2630 $params = array(
2631 'course' => $data->course,
2632 'criteriatype' => $data->criteriatype,
2633 'method' => $data->method,
2634 'value' => $data->value,
2636 $DB->insert_record('course_completion_aggr_methd', $params);
2643 * This structure step restores course logs (cmid = 0), delegating
2644 * the hard work to the corresponding {@link restore_logs_processor} passing the
2645 * collection of {@link restore_log_rule} rules to be observed as they are defined
2646 * by the task. Note this is only executed based in the 'logs' setting.
2648 * NOTE: This is executed by final task, to have all the activities already restored
2650 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2651 * records are. There are others like 'calendar' and 'upload' that will be handled
2652 * later.
2654 * NOTE: All the missing actions (not able to be restored) are sent to logs for
2655 * debugging purposes
2657 class restore_course_logs_structure_step extends restore_structure_step {
2660 * Conditionally decide if this step should be executed.
2662 * This function checks the following parameter:
2664 * 1. the course/logs.xml file exists
2666 * @return bool true is safe to execute, false otherwise
2668 protected function execute_condition() {
2670 // Check it is included in the backup
2671 $fullpath = $this->task->get_taskbasepath();
2672 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2673 if (!file_exists($fullpath)) {
2674 // Not found, can't restore course logs
2675 return false;
2678 return true;
2681 protected function define_structure() {
2683 $paths = array();
2685 // Simple, one plain level of information contains them
2686 $paths[] = new restore_path_element('log', '/logs/log');
2688 return $paths;
2691 protected function process_log($data) {
2692 global $DB;
2694 $data = (object)($data);
2696 $data->time = $this->apply_date_offset($data->time);
2697 $data->userid = $this->get_mappingid('user', $data->userid);
2698 $data->course = $this->get_courseid();
2699 $data->cmid = 0;
2701 // For any reason user wasn't remapped ok, stop processing this
2702 if (empty($data->userid)) {
2703 return;
2706 // Everything ready, let's delegate to the restore_logs_processor
2708 // Set some fixed values that will save tons of DB requests
2709 $values = array(
2710 'course' => $this->get_courseid());
2711 // Get instance and process log record
2712 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2714 // If we have data, insert it, else something went wrong in the restore_logs_processor
2715 if ($data) {
2716 if (empty($data->url)) {
2717 $data->url = '';
2719 if (empty($data->info)) {
2720 $data->info = '';
2722 // Store the data in the legacy log table if we are still using it.
2723 $manager = get_log_manager();
2724 if (method_exists($manager, 'legacy_add_to_log')) {
2725 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
2726 $data->info, $data->cmid, $data->userid);
2733 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2734 * sharing its same structure but modifying the way records are handled
2736 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2738 protected function process_log($data) {
2739 global $DB;
2741 $data = (object)($data);
2743 $data->time = $this->apply_date_offset($data->time);
2744 $data->userid = $this->get_mappingid('user', $data->userid);
2745 $data->course = $this->get_courseid();
2746 $data->cmid = $this->task->get_moduleid();
2748 // For any reason user wasn't remapped ok, stop processing this
2749 if (empty($data->userid)) {
2750 return;
2753 // Everything ready, let's delegate to the restore_logs_processor
2755 // Set some fixed values that will save tons of DB requests
2756 $values = array(
2757 'course' => $this->get_courseid(),
2758 'course_module' => $this->task->get_moduleid(),
2759 $this->task->get_modulename() => $this->task->get_activityid());
2760 // Get instance and process log record
2761 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2763 // If we have data, insert it, else something went wrong in the restore_logs_processor
2764 if ($data) {
2765 if (empty($data->url)) {
2766 $data->url = '';
2768 if (empty($data->info)) {
2769 $data->info = '';
2771 // Store the data in the legacy log table if we are still using it.
2772 $manager = get_log_manager();
2773 if (method_exists($manager, 'legacy_add_to_log')) {
2774 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
2775 $data->info, $data->cmid, $data->userid);
2783 * Defines the restore step for advanced grading methods attached to the activity module
2785 class restore_activity_grading_structure_step extends restore_structure_step {
2788 * This step is executed only if the grading file is present
2790 protected function execute_condition() {
2792 $fullpath = $this->task->get_taskbasepath();
2793 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2794 if (!file_exists($fullpath)) {
2795 return false;
2798 return true;
2803 * Declares paths in the grading.xml file we are interested in
2805 protected function define_structure() {
2807 $paths = array();
2808 $userinfo = $this->get_setting_value('userinfo');
2810 $area = new restore_path_element('grading_area', '/areas/area');
2811 $paths[] = $area;
2812 // attach local plugin stucture to $area element
2813 $this->add_plugin_structure('local', $area);
2815 $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
2816 $paths[] = $definition;
2817 $this->add_plugin_structure('gradingform', $definition);
2818 // attach local plugin stucture to $definition element
2819 $this->add_plugin_structure('local', $definition);
2822 if ($userinfo) {
2823 $instance = new restore_path_element('grading_instance',
2824 '/areas/area/definitions/definition/instances/instance');
2825 $paths[] = $instance;
2826 $this->add_plugin_structure('gradingform', $instance);
2827 // attach local plugin stucture to $intance element
2828 $this->add_plugin_structure('local', $instance);
2831 return $paths;
2835 * Processes one grading area element
2837 * @param array $data element data
2839 protected function process_grading_area($data) {
2840 global $DB;
2842 $task = $this->get_task();
2843 $data = (object)$data;
2844 $oldid = $data->id;
2845 $data->component = 'mod_'.$task->get_modulename();
2846 $data->contextid = $task->get_contextid();
2848 $newid = $DB->insert_record('grading_areas', $data);
2849 $this->set_mapping('grading_area', $oldid, $newid);
2853 * Processes one grading definition element
2855 * @param array $data element data
2857 protected function process_grading_definition($data) {
2858 global $DB;
2860 $task = $this->get_task();
2861 $data = (object)$data;
2862 $oldid = $data->id;
2863 $data->areaid = $this->get_new_parentid('grading_area');
2864 $data->copiedfromid = null;
2865 $data->timecreated = time();
2866 $data->usercreated = $task->get_userid();
2867 $data->timemodified = $data->timecreated;
2868 $data->usermodified = $data->usercreated;
2870 $newid = $DB->insert_record('grading_definitions', $data);
2871 $this->set_mapping('grading_definition', $oldid, $newid, true);
2875 * Processes one grading form instance element
2877 * @param array $data element data
2879 protected function process_grading_instance($data) {
2880 global $DB;
2882 $data = (object)$data;
2884 // new form definition id
2885 $newformid = $this->get_new_parentid('grading_definition');
2887 // get the name of the area we are restoring to
2888 $sql = "SELECT ga.areaname
2889 FROM {grading_definitions} gd
2890 JOIN {grading_areas} ga ON gd.areaid = ga.id
2891 WHERE gd.id = ?";
2892 $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
2894 // get the mapped itemid - the activity module is expected to define the mappings
2895 // for each gradable area
2896 $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
2898 $oldid = $data->id;
2899 $data->definitionid = $newformid;
2900 $data->raterid = $this->get_mappingid('user', $data->raterid);
2901 $data->itemid = $newitemid;
2903 $newid = $DB->insert_record('grading_instances', $data);
2904 $this->set_mapping('grading_instance', $oldid, $newid);
2908 * Final operations when the database records are inserted
2910 protected function after_execute() {
2911 // Add files embedded into the definition description
2912 $this->add_related_files('grading', 'description', 'grading_definition');
2918 * This structure step restores the grade items associated with one activity
2919 * All the grade items are made child of the "course" grade item but the original
2920 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
2921 * the complete gradebook (categories and calculations), that information is
2922 * available there
2924 class restore_activity_grades_structure_step extends restore_structure_step {
2926 protected function define_structure() {
2928 $paths = array();
2929 $userinfo = $this->get_setting_value('userinfo');
2931 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
2932 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
2933 if ($userinfo) {
2934 $paths[] = new restore_path_element('grade_grade',
2935 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
2937 return $paths;
2940 protected function process_grade_item($data) {
2941 global $DB;
2943 $data = (object)($data);
2944 $oldid = $data->id; // We'll need these later
2945 $oldparentid = $data->categoryid;
2946 $courseid = $this->get_courseid();
2948 // make sure top course category exists, all grade items will be associated
2949 // to it. Later, if restoring the whole gradebook, categories will be introduced
2950 $coursecat = grade_category::fetch_course_category($courseid);
2951 $coursecatid = $coursecat->id; // Get the categoryid to be used
2953 $idnumber = null;
2954 if (!empty($data->idnumber)) {
2955 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
2956 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
2957 // so the best is to keep the ones already in the gradebook
2958 // Potential problem: duplicates if same items are restored more than once. :-(
2959 // This needs to be fixed in some way (outcomes & activities with multiple items)
2960 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
2961 // In any case, verify always for uniqueness
2962 $sql = "SELECT cm.id
2963 FROM {course_modules} cm
2964 WHERE cm.course = :courseid AND
2965 cm.idnumber = :idnumber AND
2966 cm.id <> :cmid";
2967 $params = array(
2968 'courseid' => $courseid,
2969 'idnumber' => $data->idnumber,
2970 'cmid' => $this->task->get_moduleid()
2972 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
2973 $idnumber = $data->idnumber;
2977 unset($data->id);
2978 $data->categoryid = $coursecatid;
2979 $data->courseid = $this->get_courseid();
2980 $data->iteminstance = $this->task->get_activityid();
2981 $data->idnumber = $idnumber;
2982 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
2983 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
2984 $data->timecreated = $this->apply_date_offset($data->timecreated);
2985 $data->timemodified = $this->apply_date_offset($data->timemodified);
2987 $gradeitem = new grade_item($data, false);
2988 $gradeitem->insert('restore');
2990 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
2991 $gradeitem->sortorder = $data->sortorder;
2992 $gradeitem->update('restore');
2994 // Set mapping, saving the original category id into parentitemid
2995 // gradebook restore (final task) will need it to reorganise items
2996 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
2999 protected function process_grade_grade($data) {
3000 $data = (object)($data);
3001 $olduserid = $data->userid;
3002 $oldid = $data->id;
3003 unset($data->id);
3005 $data->itemid = $this->get_new_parentid('grade_item');
3007 $data->userid = $this->get_mappingid('user', $data->userid, null);
3008 if (!empty($data->userid)) {
3009 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
3010 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
3011 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
3012 $data->overridden = $this->apply_date_offset($data->overridden);
3014 $grade = new grade_grade($data, false);
3015 $grade->insert('restore');
3016 $this->set_mapping('grade_grades', $oldid, $grade->id);
3017 } else {
3018 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
3023 * process activity grade_letters. Note that, while these are possible,
3024 * because grade_letters are contextid based, in practice, only course
3025 * context letters can be defined. So we keep here this method knowing
3026 * it won't be executed ever. gradebook restore will restore course letters.
3028 protected function process_grade_letter($data) {
3029 global $DB;
3031 $data['contextid'] = $this->task->get_contextid();
3032 $gradeletter = (object)$data;
3034 // Check if it exists before adding it
3035 unset($data['id']);
3036 if (!$DB->record_exists('grade_letters', $data)) {
3037 $newitemid = $DB->insert_record('grade_letters', $gradeletter);
3039 // no need to save any grade_letter mapping
3042 public function after_restore() {
3043 // Fix grade item's sortorder after restore, as it might have duplicates.
3044 $courseid = $this->get_task()->get_courseid();
3045 grade_item::fix_duplicate_sortorder($courseid);
3050 * Step in charge of restoring the grade history of an activity.
3052 * This step is added to the task regardless of the setting 'grade_histories'.
3053 * The reason is to allow for a more flexible step in case the logic needs to be
3054 * split accross different settings to control the history of items and/or grades.
3056 class restore_activity_grade_history_structure_step extends restore_structure_step {
3059 * This step is executed only if the grade history file is present.
3061 protected function execute_condition() {
3062 $fullpath = $this->task->get_taskbasepath();
3063 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3064 if (!file_exists($fullpath)) {
3065 return false;
3067 return true;
3070 protected function define_structure() {
3071 $paths = array();
3073 // Settings to use.
3074 $userinfo = $this->get_setting_value('userinfo');
3075 $history = $this->get_setting_value('grade_histories');
3077 if ($userinfo && $history) {
3078 $paths[] = new restore_path_element('grade_grade',
3079 '/grade_history/grade_grades/grade_grade');
3082 return $paths;
3085 protected function process_grade_grade($data) {
3086 global $DB;
3088 $data = (object) $data;
3089 $olduserid = $data->userid;
3090 unset($data->id);
3092 $data->userid = $this->get_mappingid('user', $data->userid, null);
3093 if (!empty($data->userid)) {
3094 // Do not apply the date offsets as this is history.
3095 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
3096 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
3097 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
3098 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
3099 $DB->insert_record('grade_grades_history', $data);
3100 } else {
3101 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
3102 $this->log($message, backup::LOG_DEBUG);
3109 * This structure steps restores one instance + positions of one block
3110 * Note: Positions corresponding to one existing context are restored
3111 * here, but all the ones having unknown contexts are sent to backup_ids
3112 * for a later chance to be restored at the end (final task)
3114 class restore_block_instance_structure_step extends restore_structure_step {
3116 protected function define_structure() {
3118 $paths = array();
3120 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
3121 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
3123 return $paths;
3126 public function process_block($data) {
3127 global $DB, $CFG;
3129 $data = (object)$data; // Handy
3130 $oldcontextid = $data->contextid;
3131 $oldid = $data->id;
3132 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
3134 // Look for the parent contextid
3135 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
3136 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
3139 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
3140 // If there is already one block of that type in the parent context
3141 // and the block is not multiple, stop processing
3142 // Use blockslib loader / method executor
3143 if (!$bi = block_instance($data->blockname)) {
3144 return false;
3147 if (!$bi->instance_allow_multiple()) {
3148 if ($DB->record_exists_sql("SELECT bi.id
3149 FROM {block_instances} bi
3150 JOIN {block} b ON b.name = bi.blockname
3151 WHERE bi.parentcontextid = ?
3152 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
3153 return false;
3157 // If there is already one block of that type in the parent context
3158 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
3159 // stop processing
3160 $params = array(
3161 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
3162 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
3163 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
3164 if ($birecs = $DB->get_records('block_instances', $params)) {
3165 foreach($birecs as $birec) {
3166 if ($birec->configdata == $data->configdata) {
3167 return false;
3172 // Set task old contextid, blockid and blockname once we know them
3173 $this->task->set_old_contextid($oldcontextid);
3174 $this->task->set_old_blockid($oldid);
3175 $this->task->set_blockname($data->blockname);
3177 // Let's look for anything within configdata neededing processing
3178 // (nulls and uses of legacy file.php)
3179 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
3180 $configdata = (array)unserialize(base64_decode($data->configdata));
3181 foreach ($configdata as $attribute => $value) {
3182 if (in_array($attribute, $attrstotransform)) {
3183 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
3186 $data->configdata = base64_encode(serialize((object)$configdata));
3189 // Create the block instance
3190 $newitemid = $DB->insert_record('block_instances', $data);
3191 // Save the mapping (with restorefiles support)
3192 $this->set_mapping('block_instance', $oldid, $newitemid, true);
3193 // Create the block context
3194 $newcontextid = context_block::instance($newitemid)->id;
3195 // Save the block contexts mapping and sent it to task
3196 $this->set_mapping('context', $oldcontextid, $newcontextid);
3197 $this->task->set_contextid($newcontextid);
3198 $this->task->set_blockid($newitemid);
3200 // Restore block fileareas if declared
3201 $component = 'block_' . $this->task->get_blockname();
3202 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
3203 $this->add_related_files($component, $filearea, null);
3206 // Process block positions, creating them or accumulating for final step
3207 foreach($positions as $position) {
3208 $position = (object)$position;
3209 $position->blockinstanceid = $newitemid; // The instance is always the restored one
3210 // If position is for one already mapped (known) contextid
3211 // process it now, creating the position
3212 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
3213 $position->contextid = $newpositionctxid;
3214 // Create the block position
3215 $DB->insert_record('block_positions', $position);
3217 // The position belongs to an unknown context, send it to backup_ids
3218 // to process them as part of the final steps of restore. We send the
3219 // whole $position object there, hence use the low level method.
3220 } else {
3221 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
3228 * Structure step to restore common course_module information
3230 * This step will process the module.xml file for one activity, in order to restore
3231 * the corresponding information to the course_modules table, skipping various bits
3232 * of information based on CFG settings (groupings, completion...) in order to fullfill
3233 * all the reqs to be able to create the context to be used by all the rest of steps
3234 * in the activity restore task
3236 class restore_module_structure_step extends restore_structure_step {
3238 protected function define_structure() {
3239 global $CFG;
3241 $paths = array();
3243 $module = new restore_path_element('module', '/module');
3244 $paths[] = $module;
3245 if ($CFG->enableavailability) {
3246 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
3247 $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
3250 // Apply for 'format' plugins optional paths at module level
3251 $this->add_plugin_structure('format', $module);
3253 // Apply for 'plagiarism' plugins optional paths at module level
3254 $this->add_plugin_structure('plagiarism', $module);
3256 // Apply for 'local' plugins optional paths at module level
3257 $this->add_plugin_structure('local', $module);
3259 return $paths;
3262 protected function process_module($data) {
3263 global $CFG, $DB;
3265 $data = (object)$data;
3266 $oldid = $data->id;
3267 $this->task->set_old_moduleversion($data->version);
3269 $data->course = $this->task->get_courseid();
3270 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
3271 // Map section (first try by course_section mapping match. Useful in course and section restores)
3272 $data->section = $this->get_mappingid('course_section', $data->sectionid);
3273 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
3274 $params = array(
3275 'course' => $this->get_courseid(),
3276 'section' => $data->sectionnumber);
3277 $data->section = $DB->get_field('course_sections', 'id', $params);
3279 if (!$data->section) { // sectionnumber failed, try to get first section in course
3280 $params = array(
3281 'course' => $this->get_courseid());
3282 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
3284 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
3285 $sectionrec = array(
3286 'course' => $this->get_courseid(),
3287 'section' => 0);
3288 $DB->insert_record('course_sections', $sectionrec); // section 0
3289 $sectionrec = array(
3290 'course' => $this->get_courseid(),
3291 'section' => 1);
3292 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
3294 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
3295 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
3296 $data->idnumber = '';
3298 if (empty($CFG->enablecompletion)) { // completion
3299 $data->completion = 0;
3300 $data->completiongradeitemnumber = null;
3301 $data->completionview = 0;
3302 $data->completionexpected = 0;
3303 } else {
3304 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
3306 if (empty($CFG->enableavailability)) {
3307 $data->availability = null;
3309 // Backups that did not include showdescription, set it to default 0
3310 // (this is not totally necessary as it has a db default, but just to
3311 // be explicit).
3312 if (!isset($data->showdescription)) {
3313 $data->showdescription = 0;
3315 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
3317 if (empty($data->availability)) {
3318 // If there are legacy availablility data fields (and no new format data),
3319 // convert the old fields.
3320 $data->availability = \core_availability\info::convert_legacy_fields(
3321 $data, false);
3322 } else if (!empty($data->groupmembersonly)) {
3323 // There is current availability data, but it still has groupmembersonly
3324 // as well (2.7 backups), convert just that part.
3325 require_once($CFG->dirroot . '/lib/db/upgradelib.php');
3326 $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
3329 // course_module record ready, insert it
3330 $newitemid = $DB->insert_record('course_modules', $data);
3331 // save mapping
3332 $this->set_mapping('course_module', $oldid, $newitemid);
3333 // set the new course_module id in the task
3334 $this->task->set_moduleid($newitemid);
3335 // we can now create the context safely
3336 $ctxid = context_module::instance($newitemid)->id;
3337 // set the new context id in the task
3338 $this->task->set_contextid($ctxid);
3339 // update sequence field in course_section
3340 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
3341 $sequence .= ',' . $newitemid;
3342 } else {
3343 $sequence = $newitemid;
3345 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
3347 // If there is the legacy showavailability data, store this for later use.
3348 // (This data is not present when restoring 'new' backups.)
3349 if (isset($data->showavailability)) {
3350 // Cache the showavailability flag using the backup_ids data field.
3351 restore_dbops::set_backup_ids_record($this->get_restoreid(),
3352 'module_showavailability', $newitemid, 0, null,
3353 (object)array('showavailability' => $data->showavailability));
3358 * Process the legacy availability table record. This table does not exist
3359 * in Moodle 2.7+ but we still support restore.
3361 * @param stdClass $data Record data
3363 protected function process_availability($data) {
3364 $data = (object)$data;
3365 // Simply going to store the whole availability record now, we'll process
3366 // all them later in the final task (once all activities have been restored)
3367 // Let's call the low level one to be able to store the whole object
3368 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
3369 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
3373 * Process the legacy availability fields table record. This table does not
3374 * exist in Moodle 2.7+ but we still support restore.
3376 * @param stdClass $data Record data
3378 protected function process_availability_field($data) {
3379 global $DB;
3380 $data = (object)$data;
3381 // Mark it is as passed by default
3382 $passed = true;
3383 $customfieldid = null;
3385 // If a customfield has been used in order to pass we must be able to match an existing
3386 // customfield by name (data->customfield) and type (data->customfieldtype)
3387 if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
3388 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
3389 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
3390 $passed = false;
3391 } else if (!empty($data->customfield)) {
3392 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
3393 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
3394 $passed = ($customfieldid !== false);
3397 if ($passed) {
3398 // Create the object to insert into the database
3399 $availfield = new stdClass();
3400 $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
3401 $availfield->userfield = $data->userfield;
3402 $availfield->customfieldid = $customfieldid;
3403 $availfield->operator = $data->operator;
3404 $availfield->value = $data->value;
3406 // Get showavailability option.
3407 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
3408 'module_showavailability', $availfield->coursemoduleid);
3409 if (!$showrec) {
3410 // Should not happen.
3411 throw new coding_exception('No matching showavailability record');
3413 $show = $showrec->info->showavailability;
3415 // The $availfieldobject is now in the format used in the old
3416 // system. Interpret this and convert to new system.
3417 $currentvalue = $DB->get_field('course_modules', 'availability',
3418 array('id' => $availfield->coursemoduleid), MUST_EXIST);
3419 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
3420 $currentvalue, $availfield, $show);
3421 $DB->set_field('course_modules', 'availability', $newvalue,
3422 array('id' => $availfield->coursemoduleid));
3428 * Structure step that will process the user activity completion
3429 * information if all these conditions are met:
3430 * - Target site has completion enabled ($CFG->enablecompletion)
3431 * - Activity includes completion info (file_exists)
3433 class restore_userscompletion_structure_step extends restore_structure_step {
3435 * To conditionally decide if this step must be executed
3436 * Note the "settings" conditions are evaluated in the
3437 * corresponding task. Here we check for other conditions
3438 * not being restore settings (files, site settings...)
3440 protected function execute_condition() {
3441 global $CFG;
3443 // Completion disabled in this site, don't execute
3444 if (empty($CFG->enablecompletion)) {
3445 return false;
3448 // No user completion info found, don't execute
3449 $fullpath = $this->task->get_taskbasepath();
3450 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3451 if (!file_exists($fullpath)) {
3452 return false;
3455 // Arrived here, execute the step
3456 return true;
3459 protected function define_structure() {
3461 $paths = array();
3463 $paths[] = new restore_path_element('completion', '/completions/completion');
3465 return $paths;
3468 protected function process_completion($data) {
3469 global $DB;
3471 $data = (object)$data;
3473 $data->coursemoduleid = $this->task->get_moduleid();
3474 $data->userid = $this->get_mappingid('user', $data->userid);
3475 $data->timemodified = $this->apply_date_offset($data->timemodified);
3477 // Find the existing record
3478 $existing = $DB->get_record('course_modules_completion', array(
3479 'coursemoduleid' => $data->coursemoduleid,
3480 'userid' => $data->userid), 'id, timemodified');
3481 // Check we didn't already insert one for this cmid and userid
3482 // (there aren't supposed to be duplicates in that field, but
3483 // it was possible until MDL-28021 was fixed).
3484 if ($existing) {
3485 // Update it to these new values, but only if the time is newer
3486 if ($existing->timemodified < $data->timemodified) {
3487 $data->id = $existing->id;
3488 $DB->update_record('course_modules_completion', $data);
3490 } else {
3491 // Normal entry where it doesn't exist already
3492 $DB->insert_record('course_modules_completion', $data);
3498 * Abstract structure step, parent of all the activity structure steps. Used to suuport
3499 * the main <activity ...> tag and process it. Also provides subplugin support for
3500 * activities.
3502 abstract class restore_activity_structure_step extends restore_structure_step {
3504 protected function add_subplugin_structure($subplugintype, $element) {
3506 global $CFG;
3508 // Check the requested subplugintype is a valid one
3509 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
3510 if (!file_exists($subpluginsfile)) {
3511 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
3513 include($subpluginsfile);
3514 if (!array_key_exists($subplugintype, $subplugins)) {
3515 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
3517 // Get all the restore path elements, looking across all the subplugin dirs
3518 $subpluginsdirs = core_component::get_plugin_list($subplugintype);
3519 foreach ($subpluginsdirs as $name => $subpluginsdir) {
3520 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
3521 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
3522 if (file_exists($restorefile)) {
3523 require_once($restorefile);
3524 $restoresubplugin = new $classname($subplugintype, $name, $this);
3525 // Add subplugin paths to the step
3526 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
3532 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
3533 * have the parent task available for wrapping purposes (get course/context....)
3534 * @return restore_task
3536 public function get_task() {
3537 return $this->task;
3541 * Adds support for the 'activity' path that is common to all the activities
3542 * and will be processed globally here
3544 protected function prepare_activity_structure($paths) {
3546 $paths[] = new restore_path_element('activity', '/activity');
3548 return $paths;
3552 * Process the activity path, informing the task about various ids, needed later
3554 protected function process_activity($data) {
3555 $data = (object)$data;
3556 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
3557 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
3558 $this->task->set_old_activityid($data->id); // Save old activityid in task
3562 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
3563 * and will adjust the new activity id (the instance) in various places
3565 protected function apply_activity_instance($newitemid) {
3566 global $DB;
3568 $this->task->set_activityid($newitemid); // Save activity id in task
3569 // Apply the id to course_sections->instanceid
3570 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
3571 // Do the mapping for modulename, preparing it for files by oldcontext
3572 $modulename = $this->task->get_modulename();
3573 $oldid = $this->task->get_old_activityid();
3574 $this->set_mapping($modulename, $oldid, $newitemid, true);
3579 * Structure step in charge of creating/mapping all the qcats and qs
3580 * by parsing the questions.xml file and checking it against the
3581 * results calculated by {@link restore_process_categories_and_questions}
3582 * and stored in backup_ids_temp
3584 class restore_create_categories_and_questions extends restore_structure_step {
3586 /** @var array $cachecategory store a question category */
3587 protected $cachedcategory = null;
3589 protected function define_structure() {
3591 $category = new restore_path_element('question_category', '/question_categories/question_category');
3592 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
3593 $hint = new restore_path_element('question_hint',
3594 '/question_categories/question_category/questions/question/question_hints/question_hint');
3596 $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag');
3598 // Apply for 'qtype' plugins optional paths at question level
3599 $this->add_plugin_structure('qtype', $question);
3601 // Apply for 'local' plugins optional paths at question level
3602 $this->add_plugin_structure('local', $question);
3604 return array($category, $question, $hint, $tag);
3607 protected function process_question_category($data) {
3608 global $DB;
3610 $data = (object)$data;
3611 $oldid = $data->id;
3613 // Check we have one mapping for this category
3614 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
3615 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
3618 // Check we have to create the category (newitemid = 0)
3619 if ($mapping->newitemid) {
3620 return; // newitemid != 0, this category is going to be mapped. Nothing to do
3623 // Arrived here, newitemid = 0, we need to create the category
3624 // we'll do it at parentitemid context, but for CONTEXT_MODULE
3625 // categories, that will be created at CONTEXT_COURSE and moved
3626 // to module context later when the activity is created
3627 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
3628 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
3630 $data->contextid = $mapping->parentitemid;
3632 // Let's create the question_category and save mapping
3633 $newitemid = $DB->insert_record('question_categories', $data);
3634 $this->set_mapping('question_category', $oldid, $newitemid);
3635 // Also annotate them as question_category_created, we need
3636 // that later when remapping parents
3637 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
3640 protected function process_question($data) {
3641 global $DB;
3643 $data = (object)$data;
3644 $oldid = $data->id;
3646 // Check we have one mapping for this question
3647 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
3648 return; // No mapping = this question doesn't need to be created/mapped
3651 // Get the mapped category (cannot use get_new_parentid() because not
3652 // all the categories have been created, so it is not always available
3653 // Instead we get the mapping for the question->parentitemid because
3654 // we have loaded qcatids there for all parsed questions
3655 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
3657 // In the past, there were some very sloppy values of penalty. Fix them.
3658 if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
3659 $data->penalty = 0.3333333;
3661 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
3662 $data->penalty = 0.6666667;
3664 if ($data->penalty >= 1) {
3665 $data->penalty = 1;
3668 $userid = $this->get_mappingid('user', $data->createdby);
3669 $data->createdby = $userid ? $userid : $this->task->get_userid();
3671 $userid = $this->get_mappingid('user', $data->modifiedby);
3672 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
3674 // With newitemid = 0, let's create the question
3675 if (!$questionmapping->newitemid) {
3676 $newitemid = $DB->insert_record('question', $data);
3677 $this->set_mapping('question', $oldid, $newitemid);
3678 // Also annotate them as question_created, we need
3679 // that later when remapping parents (keeping the old categoryid as parentid)
3680 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
3681 } else {
3682 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
3683 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
3684 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
3687 // Note, we don't restore any question files yet
3688 // as far as the CONTEXT_MODULE categories still
3689 // haven't their contexts to be restored to
3690 // The {@link restore_create_question_files}, executed in the final step
3691 // step will be in charge of restoring all the question files
3694 protected function process_question_hint($data) {
3695 global $DB;
3697 $data = (object)$data;
3698 $oldid = $data->id;
3700 // Detect if the question is created or mapped
3701 $oldquestionid = $this->get_old_parentid('question');
3702 $newquestionid = $this->get_new_parentid('question');
3703 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
3705 // If the question has been created by restore, we need to create its question_answers too
3706 if ($questioncreated) {
3707 // Adjust some columns
3708 $data->questionid = $newquestionid;
3709 // Insert record
3710 $newitemid = $DB->insert_record('question_hints', $data);
3712 // The question existed, we need to map the existing question_hints
3713 } else {
3714 // Look in question_hints by hint text matching
3715 $sql = 'SELECT id
3716 FROM {question_hints}
3717 WHERE questionid = ?
3718 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
3719 $params = array($newquestionid, $data->hint);
3720 $newitemid = $DB->get_field_sql($sql, $params);
3722 // Not able to find the hint, let's try cleaning the hint text
3723 // of all the question's hints in DB as slower fallback. MDL-33863.
3724 if (!$newitemid) {
3725 $potentialhints = $DB->get_records('question_hints',
3726 array('questionid' => $newquestionid), '', 'id, hint');
3727 foreach ($potentialhints as $potentialhint) {
3728 // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
3729 $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
3730 $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
3731 if ($cleanhint === $data->hint) {
3732 $newitemid = $data->id;
3737 // If we haven't found the newitemid, something has gone really wrong, question in DB
3738 // is missing hints, exception
3739 if (!$newitemid) {
3740 $info = new stdClass();
3741 $info->filequestionid = $oldquestionid;
3742 $info->dbquestionid = $newquestionid;
3743 $info->hint = $data->hint;
3744 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
3747 // Create mapping (I'm not sure if this is really needed?)
3748 $this->set_mapping('question_hint', $oldid, $newitemid);
3751 protected function process_tag($data) {
3752 global $CFG, $DB;
3754 $data = (object)$data;
3755 $newquestion = $this->get_new_parentid('question');
3757 if (!empty($CFG->usetags)) { // if enabled in server
3758 // TODO: This is highly inefficient. Each time we add one tag
3759 // we fetch all the existing because tag_set() deletes them
3760 // so everything must be reinserted on each call
3761 $tags = array();
3762 $existingtags = tag_get_tags('question', $newquestion);
3763 // Re-add all the existitng tags
3764 foreach ($existingtags as $existingtag) {
3765 $tags[] = $existingtag->rawname;
3767 // Add the one being restored
3768 $tags[] = $data->rawname;
3769 // Get the category, so we can then later get the context.
3770 $categoryid = $this->get_new_parentid('question_category');
3771 if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
3772 $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
3774 // Send all the tags back to the question
3775 tag_set('question', $newquestion, $tags, 'core_question', $this->cachedcategory->contextid);
3779 protected function after_execute() {
3780 global $DB;
3782 // First of all, recode all the created question_categories->parent fields
3783 $qcats = $DB->get_records('backup_ids_temp', array(
3784 'backupid' => $this->get_restoreid(),
3785 'itemname' => 'question_category_created'));
3786 foreach ($qcats as $qcat) {
3787 $newparent = 0;
3788 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
3789 // Get new parent (mapped or created, so we look in quesiton_category mappings)
3790 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
3791 'backupid' => $this->get_restoreid(),
3792 'itemname' => 'question_category',
3793 'itemid' => $dbcat->parent))) {
3794 // contextids must match always, as far as we always include complete qbanks, just check it
3795 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
3796 if ($dbcat->contextid == $newparentctxid) {
3797 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
3798 } else {
3799 $newparent = 0; // No ctx match for both cats, no parent relationship
3802 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
3803 if (!$newparent) {
3804 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
3808 // Now, recode all the created question->parent fields
3809 $qs = $DB->get_records('backup_ids_temp', array(
3810 'backupid' => $this->get_restoreid(),
3811 'itemname' => 'question_created'));
3812 foreach ($qs as $q) {
3813 $newparent = 0;
3814 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
3815 // Get new parent (mapped or created, so we look in question mappings)
3816 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
3817 'backupid' => $this->get_restoreid(),
3818 'itemname' => 'question',
3819 'itemid' => $dbq->parent))) {
3820 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
3824 // Note, we don't restore any question files yet
3825 // as far as the CONTEXT_MODULE categories still
3826 // haven't their contexts to be restored to
3827 // The {@link restore_create_question_files}, executed in the final step
3828 // step will be in charge of restoring all the question files
3833 * Execution step that will move all the CONTEXT_MODULE question categories
3834 * created at early stages of restore in course context (because modules weren't
3835 * created yet) to their target module (matching by old-new-contextid mapping)
3837 class restore_move_module_questions_categories extends restore_execution_step {
3839 protected function define_execution() {
3840 global $DB;
3842 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
3843 foreach ($contexts as $contextid => $contextlevel) {
3844 // Only if context mapping exists (i.e. the module has been restored)
3845 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
3846 // Update all the qcats having their parentitemid set to the original contextid
3847 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
3848 FROM {backup_ids_temp}
3849 WHERE backupid = ?
3850 AND itemname = 'question_category'
3851 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
3852 foreach ($modulecats as $modulecat) {
3853 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
3854 // And set new contextid also in question_category mapping (will be
3855 // used by {@link restore_create_question_files} later
3856 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
3864 * Execution step that will create all the question/answers/qtype-specific files for the restored
3865 * questions. It must be executed after {@link restore_move_module_questions_categories}
3866 * because only then each question is in its final category and only then the
3867 * contexts can be determined.
3869 class restore_create_question_files extends restore_execution_step {
3871 /** @var array Question-type specific component items cache. */
3872 private $qtypecomponentscache = array();
3875 * Preform the restore_create_question_files step.
3877 protected function define_execution() {
3878 global $DB;
3880 // Track progress, as this task can take a long time.
3881 $progress = $this->task->get_progress();
3882 $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
3884 // Parentitemids of question_createds in backup_ids_temp are the category it is in.
3885 // MUST use a recordset, as there is no unique key in the first (or any) column.
3886 $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
3887 FROM {backup_ids_temp} bi
3888 JOIN {question} q ON q.id = bi.newitemid
3889 WHERE bi.backupid = ?
3890 AND bi.itemname = 'question_created'
3891 ORDER BY categoryid ASC", array($this->get_restoreid()));
3893 $currentcatid = -1;
3894 foreach ($catqtypes as $categoryid => $row) {
3895 $qtype = $row->qtype;
3897 // Check if we are in a new category.
3898 if ($currentcatid !== $categoryid) {
3899 // Report progress for each category.
3900 $progress->progress();
3902 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
3903 'question_category', $categoryid)) {
3904 // Something went really wrong, cannot find the question_category for the question_created records.
3905 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
3906 continue;
3909 // Calculate source and target contexts.
3910 $oldctxid = $qcatmapping->info->contextid;
3911 $newctxid = $qcatmapping->parentitemid;
3913 $this->send_common_files($oldctxid, $newctxid, $progress);
3914 $currentcatid = $categoryid;
3917 $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
3919 $catqtypes->close();
3920 $progress->end_progress();
3924 * Send the common question files to a new context.
3926 * @param int $oldctxid Old context id.
3927 * @param int $newctxid New context id.
3928 * @param \core\progress $progress Progress object to use.
3930 private function send_common_files($oldctxid, $newctxid, $progress) {
3931 // Add common question files (question and question_answer ones).
3932 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
3933 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3934 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
3935 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3936 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
3937 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
3938 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
3939 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
3940 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
3941 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
3942 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
3943 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3944 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
3945 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3946 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
3947 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3951 * Send the question type specific files to a new context.
3953 * @param text $qtype The qtype name to send.
3954 * @param int $oldctxid Old context id.
3955 * @param int $newctxid New context id.
3956 * @param \core\progress $progress Progress object to use.
3958 private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
3959 if (!isset($this->qtypecomponentscache[$qtype])) {
3960 $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
3962 $components = $this->qtypecomponentscache[$qtype];
3963 foreach ($components as $component => $fileareas) {
3964 foreach ($fileareas as $filearea => $mapping) {
3965 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
3966 $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
3973 * Try to restore aliases and references to external files.
3975 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
3976 * We expect that all regular (non-alias) files have already been restored. Make sure
3977 * there is no restore step executed after this one that would call send_files_to_pool() again.
3979 * You may notice we have hardcoded support for Server files, Legacy course files
3980 * and user Private files here at the moment. This could be eventually replaced with a set of
3981 * callbacks in the future if needed.
3983 * @copyright 2012 David Mudrak <david@moodle.com>
3984 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3986 class restore_process_file_aliases_queue extends restore_execution_step {
3988 /** @var array internal cache for {@link choose_repository()} */
3989 private $cachereposbyid = array();
3991 /** @var array internal cache for {@link choose_repository()} */
3992 private $cachereposbytype = array();
3995 * What to do when this step is executed.
3997 protected function define_execution() {
3998 global $DB;
4000 $this->log('processing file aliases queue', backup::LOG_DEBUG);
4002 $fs = get_file_storage();
4004 // Load the queue.
4005 $rs = $DB->get_recordset('backup_ids_temp',
4006 array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'),
4007 '', 'info');
4009 // Iterate over aliases in the queue.
4010 foreach ($rs as $record) {
4011 $info = backup_controller_dbops::decode_backup_temp_info($record->info);
4013 // Try to pick a repository instance that should serve the alias.
4014 $repository = $this->choose_repository($info);
4016 if (is_null($repository)) {
4017 $this->notify_failure($info, 'unable to find a matching repository instance');
4018 continue;
4021 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
4022 // Aliases to Server files and Legacy course files may refer to a file
4023 // contained in the backup file or to some existing file (if we are on the
4024 // same site).
4025 try {
4026 $reference = file_storage::unpack_reference($info->oldfile->reference);
4027 } catch (Exception $e) {
4028 $this->notify_failure($info, 'invalid reference field format');
4029 continue;
4032 // Let's see if the referred source file was also included in the backup.
4033 $candidates = $DB->get_recordset('backup_files_temp', array(
4034 'backupid' => $this->get_restoreid(),
4035 'contextid' => $reference['contextid'],
4036 'component' => $reference['component'],
4037 'filearea' => $reference['filearea'],
4038 'itemid' => $reference['itemid'],
4039 ), '', 'info, newcontextid, newitemid');
4041 $source = null;
4043 foreach ($candidates as $candidate) {
4044 $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
4045 if ($candidateinfo->filename === $reference['filename']
4046 and $candidateinfo->filepath === $reference['filepath']
4047 and !is_null($candidate->newcontextid)
4048 and !is_null($candidate->newitemid) ) {
4049 $source = $candidateinfo;
4050 $source->contextid = $candidate->newcontextid;
4051 $source->itemid = $candidate->newitemid;
4052 break;
4055 $candidates->close();
4057 if ($source) {
4058 // We have an alias that refers to another file also included in
4059 // the backup. Let us change the reference field so that it refers
4060 // to the restored copy of the original file.
4061 $reference = file_storage::pack_reference($source);
4063 // Send the new alias to the filepool.
4064 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4065 $this->notify_success($info);
4066 continue;
4068 } else {
4069 // This is a reference to some moodle file that was not contained in the backup
4070 // file. If we are restoring to the same site, keep the reference untouched
4071 // and restore the alias as is if the referenced file exists.
4072 if ($this->task->is_samesite()) {
4073 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
4074 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
4075 $reference = file_storage::pack_reference($reference);
4076 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4077 $this->notify_success($info);
4078 continue;
4079 } else {
4080 $this->notify_failure($info, 'referenced file not found');
4081 continue;
4084 // If we are at other site, we can't restore this alias.
4085 } else {
4086 $this->notify_failure($info, 'referenced file not included');
4087 continue;
4091 } else if ($info->oldfile->repositorytype === 'user') {
4092 if ($this->task->is_samesite()) {
4093 // For aliases to user Private files at the same site, we have a chance to check
4094 // if the referenced file still exists.
4095 try {
4096 $reference = file_storage::unpack_reference($info->oldfile->reference);
4097 } catch (Exception $e) {
4098 $this->notify_failure($info, 'invalid reference field format');
4099 continue;
4101 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
4102 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
4103 $reference = file_storage::pack_reference($reference);
4104 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
4105 $this->notify_success($info);
4106 continue;
4107 } else {
4108 $this->notify_failure($info, 'referenced file not found');
4109 continue;
4112 // If we are at other site, we can't restore this alias.
4113 } else {
4114 $this->notify_failure($info, 'restoring at another site');
4115 continue;
4118 } else {
4119 // This is a reference to some external file such as in boxnet or dropbox.
4120 // If we are restoring to the same site, keep the reference untouched and
4121 // restore the alias as is.
4122 if ($this->task->is_samesite()) {
4123 $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
4124 $this->notify_success($info);
4125 continue;
4127 // If we are at other site, we can't restore this alias.
4128 } else {
4129 $this->notify_failure($info, 'restoring at another site');
4130 continue;
4134 $rs->close();
4138 * Choose the repository instance that should handle the alias.
4140 * At the same site, we can rely on repository instance id and we just
4141 * check it still exists. On other site, try to find matching Server files or
4142 * Legacy course files repository instance. Return null if no matching
4143 * repository instance can be found.
4145 * @param stdClass $info
4146 * @return repository|null
4148 private function choose_repository(stdClass $info) {
4149 global $DB, $CFG;
4150 require_once($CFG->dirroot.'/repository/lib.php');
4152 if ($this->task->is_samesite()) {
4153 // We can rely on repository instance id.
4155 if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
4156 return $this->cachereposbyid[$info->oldfile->repositoryid];
4159 $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
4161 try {
4162 $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
4163 return $this->cachereposbyid[$info->oldfile->repositoryid];
4164 } catch (Exception $e) {
4165 $this->cachereposbyid[$info->oldfile->repositoryid] = null;
4166 return null;
4169 } else {
4170 // We can rely on repository type only.
4172 if (empty($info->oldfile->repositorytype)) {
4173 return null;
4176 if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
4177 return $this->cachereposbytype[$info->oldfile->repositorytype];
4180 $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
4182 // Both Server files and Legacy course files repositories have a single
4183 // instance at the system context to use. Let us try to find it.
4184 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
4185 $sql = "SELECT ri.id
4186 FROM {repository} r
4187 JOIN {repository_instances} ri ON ri.typeid = r.id
4188 WHERE r.type = ? AND ri.contextid = ?";
4189 $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
4190 if (empty($ris)) {
4191 return null;
4193 $repoids = array_keys($ris);
4194 $repoid = reset($repoids);
4195 try {
4196 $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
4197 return $this->cachereposbytype[$info->oldfile->repositorytype];
4198 } catch (Exception $e) {
4199 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
4200 return null;
4204 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
4205 return null;
4210 * Let the user know that the given alias was successfully restored
4212 * @param stdClass $info
4214 private function notify_success(stdClass $info) {
4215 $filedesc = $this->describe_alias($info);
4216 $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
4220 * Let the user know that the given alias can't be restored
4222 * @param stdClass $info
4223 * @param string $reason detailed reason to be logged
4225 private function notify_failure(stdClass $info, $reason = '') {
4226 $filedesc = $this->describe_alias($info);
4227 if ($reason) {
4228 $reason = ' ('.$reason.')';
4230 $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
4231 $this->add_result_item('file_aliases_restore_failures', $filedesc);
4235 * Return a human readable description of the alias file
4237 * @param stdClass $info
4238 * @return string
4240 private function describe_alias(stdClass $info) {
4242 $filedesc = $this->expected_alias_location($info->newfile);
4244 if (!is_null($info->oldfile->source)) {
4245 $filedesc .= ' ('.$info->oldfile->source.')';
4248 return $filedesc;
4252 * Return the expected location of a file
4254 * Please note this may and may not work as a part of URL to pluginfile.php
4255 * (depends on how the given component/filearea deals with the itemid).
4257 * @param stdClass $filerecord
4258 * @return string
4260 private function expected_alias_location($filerecord) {
4262 $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
4263 if (!is_null($filerecord->itemid)) {
4264 $filedesc .= '/'.$filerecord->itemid;
4266 $filedesc .= $filerecord->filepath.$filerecord->filename;
4268 return $filedesc;
4272 * Append a value to the given resultset
4274 * @param string $name name of the result containing a list of values
4275 * @param mixed $value value to add as another item in that result
4277 private function add_result_item($name, $value) {
4279 $results = $this->task->get_results();
4281 if (isset($results[$name])) {
4282 if (!is_array($results[$name])) {
4283 throw new coding_exception('Unable to append a result item into a non-array structure.');
4285 $current = $results[$name];
4286 $current[] = $value;
4287 $this->task->add_result(array($name => $current));
4289 } else {
4290 $this->task->add_result(array($name => array($value)));
4297 * Abstract structure step, to be used by all the activities using core questions stuff
4298 * (like the quiz module), to support qtype plugins, states and sessions
4300 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
4301 /** @var array question_attempt->id to qtype. */
4302 protected $qtypes = array();
4303 /** @var array question_attempt->id to questionid. */
4304 protected $newquestionids = array();
4307 * Attach below $element (usually attempts) the needed restore_path_elements
4308 * to restore question_usages and all they contain.
4310 * If you use the $nameprefix parameter, then you will need to implement some
4311 * extra methods in your class, like
4313 * protected function process_{nameprefix}question_attempt($data) {
4314 * $this->restore_question_usage_worker($data, '{nameprefix}');
4316 * protected function process_{nameprefix}question_attempt($data) {
4317 * $this->restore_question_attempt_worker($data, '{nameprefix}');
4319 * protected function process_{nameprefix}question_attempt_step($data) {
4320 * $this->restore_question_attempt_step_worker($data, '{nameprefix}');
4323 * @param restore_path_element $element the parent element that the usages are stored inside.
4324 * @param array $paths the paths array that is being built.
4325 * @param string $nameprefix should match the prefix passed to the corresponding
4326 * backup_questions_activity_structure_step::add_question_usages call.
4328 protected function add_question_usages($element, &$paths, $nameprefix = '') {
4329 // Check $element is restore_path_element
4330 if (! $element instanceof restore_path_element) {
4331 throw new restore_step_exception('element_must_be_restore_path_element', $element);
4334 // Check $paths is one array
4335 if (!is_array($paths)) {
4336 throw new restore_step_exception('paths_must_be_array', $paths);
4338 $paths[] = new restore_path_element($nameprefix . 'question_usage',
4339 $element->get_path() . "/{$nameprefix}question_usage");
4340 $paths[] = new restore_path_element($nameprefix . 'question_attempt',
4341 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
4342 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
4343 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
4344 true);
4345 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
4346 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
4350 * Process question_usages
4352 protected function process_question_usage($data) {
4353 $this->restore_question_usage_worker($data, '');
4357 * Process question_attempts
4359 protected function process_question_attempt($data) {
4360 $this->restore_question_attempt_worker($data, '');
4364 * Process question_attempt_steps
4366 protected function process_question_attempt_step($data) {
4367 $this->restore_question_attempt_step_worker($data, '');
4371 * This method does the acutal work for process_question_usage or
4372 * process_{nameprefix}_question_usage.
4373 * @param array $data the data from the XML file.
4374 * @param string $nameprefix the element name prefix.
4376 protected function restore_question_usage_worker($data, $nameprefix) {
4377 global $DB;
4379 // Clear our caches.
4380 $this->qtypes = array();
4381 $this->newquestionids = array();
4383 $data = (object)$data;
4384 $oldid = $data->id;
4386 $oldcontextid = $this->get_task()->get_old_contextid();
4387 $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
4389 // Everything ready, insert (no mapping needed)
4390 $newitemid = $DB->insert_record('question_usages', $data);
4392 $this->inform_new_usage_id($newitemid);
4394 $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
4398 * When process_question_usage creates the new usage, it calls this method
4399 * to let the activity link to the new usage. For example, the quiz uses
4400 * this method to set quiz_attempts.uniqueid to the new usage id.
4401 * @param integer $newusageid
4403 abstract protected function inform_new_usage_id($newusageid);
4406 * This method does the acutal work for process_question_attempt or
4407 * process_{nameprefix}_question_attempt.
4408 * @param array $data the data from the XML file.
4409 * @param string $nameprefix the element name prefix.
4411 protected function restore_question_attempt_worker($data, $nameprefix) {
4412 global $DB;
4414 $data = (object)$data;
4415 $oldid = $data->id;
4416 $question = $this->get_mapping('question', $data->questionid);
4418 $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
4419 $data->questionid = $question->newitemid;
4420 if (!property_exists($data, 'variant')) {
4421 $data->variant = 1;
4423 $data->timemodified = $this->apply_date_offset($data->timemodified);
4425 if (!property_exists($data, 'maxfraction')) {
4426 $data->maxfraction = 1;
4429 $newitemid = $DB->insert_record('question_attempts', $data);
4431 $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
4432 $this->qtypes[$newitemid] = $question->info->qtype;
4433 $this->newquestionids[$newitemid] = $data->questionid;
4437 * This method does the acutal work for process_question_attempt_step or
4438 * process_{nameprefix}_question_attempt_step.
4439 * @param array $data the data from the XML file.
4440 * @param string $nameprefix the element name prefix.
4442 protected function restore_question_attempt_step_worker($data, $nameprefix) {
4443 global $DB;
4445 $data = (object)$data;
4446 $oldid = $data->id;
4448 // Pull out the response data.
4449 $response = array();
4450 if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
4451 foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
4452 $response[$variable['name']] = $variable['value'];
4455 unset($data->response);
4457 $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
4458 $data->timecreated = $this->apply_date_offset($data->timecreated);
4459 $data->userid = $this->get_mappingid('user', $data->userid);
4461 // Everything ready, insert and create mapping (needed by question_sessions)
4462 $newitemid = $DB->insert_record('question_attempt_steps', $data);
4463 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
4465 // Now process the response data.
4466 $response = $this->questions_recode_response_data(
4467 $this->qtypes[$data->questionattemptid],
4468 $this->newquestionids[$data->questionattemptid],
4469 $data->sequencenumber, $response);
4471 foreach ($response as $name => $value) {
4472 $row = new stdClass();
4473 $row->attemptstepid = $newitemid;
4474 $row->name = $name;
4475 $row->value = $value;
4476 $DB->insert_record('question_attempt_step_data', $row, false);
4481 * Recode the respones data for a particular step of an attempt at at particular question.
4482 * @param string $qtype the question type.
4483 * @param int $newquestionid the question id.
4484 * @param int $sequencenumber the sequence number.
4485 * @param array $response the response data to recode.
4487 public function questions_recode_response_data(
4488 $qtype, $newquestionid, $sequencenumber, array $response) {
4489 $qtyperestorer = $this->get_qtype_restorer($qtype);
4490 if ($qtyperestorer) {
4491 $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
4493 return $response;
4497 * Given a list of question->ids, separated by commas, returns the
4498 * recoded list, with all the restore question mappings applied.
4499 * Note: Used by quiz->questions and quiz_attempts->layout
4500 * Note: 0 = page break (unconverted)
4502 protected function questions_recode_layout($layout) {
4503 // Extracts question id from sequence
4504 if ($questionids = explode(',', $layout)) {
4505 foreach ($questionids as $id => $questionid) {
4506 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
4507 $newquestionid = $this->get_mappingid('question', $questionid);
4508 $questionids[$id] = $newquestionid;
4512 return implode(',', $questionids);
4516 * Get the restore_qtype_plugin subclass for a specific question type.
4517 * @param string $qtype e.g. multichoice.
4518 * @return restore_qtype_plugin instance.
4520 protected function get_qtype_restorer($qtype) {
4521 // Build one static cache to store {@link restore_qtype_plugin}
4522 // while we are needing them, just to save zillions of instantiations
4523 // or using static stuff that will break our nice API
4524 static $qtypeplugins = array();
4526 if (!isset($qtypeplugins[$qtype])) {
4527 $classname = 'restore_qtype_' . $qtype . '_plugin';
4528 if (class_exists($classname)) {
4529 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
4530 } else {
4531 $qtypeplugins[$qtype] = null;
4534 return $qtypeplugins[$qtype];
4537 protected function after_execute() {
4538 parent::after_execute();
4540 // Restore any files belonging to responses.
4541 foreach (question_engine::get_all_response_file_areas() as $filearea) {
4542 $this->add_related_files('question', $filearea, 'question_attempt_step');
4547 * Attach below $element (usually attempts) the needed restore_path_elements
4548 * to restore question attempt data from Moodle 2.0.
4550 * When using this method, the parent element ($element) must be defined with
4551 * $grouped = true. Then, in that elements process method, you must call
4552 * {@link process_legacy_attempt_data()} with the groupded data. See, for
4553 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
4554 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
4555 * @param array $paths the paths array that is being built to describe the
4556 * structure.
4558 protected function add_legacy_question_attempt_data($element, &$paths) {
4559 global $CFG;
4560 require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
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);
4566 // Check $paths is one array
4567 if (!is_array($paths)) {
4568 throw new restore_step_exception('paths_must_be_array', $paths);
4571 $paths[] = new restore_path_element('question_state',
4572 $element->get_path() . '/states/state');
4573 $paths[] = new restore_path_element('question_session',
4574 $element->get_path() . '/sessions/session');
4577 protected function get_attempt_upgrader() {
4578 if (empty($this->attemptupgrader)) {
4579 $this->attemptupgrader = new question_engine_attempt_upgrader();
4580 $this->attemptupgrader->prepare_to_restore();
4582 return $this->attemptupgrader;
4586 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
4587 * @param object $data contains all the grouped attempt data to process.
4588 * @param pbject $quiz data about the activity the attempts belong to. Required
4589 * fields are (basically this only works for the quiz module):
4590 * oldquestions => list of question ids in this activity - using old ids.
4591 * preferredbehaviour => the behaviour to use for questionattempts.
4593 protected function process_legacy_quiz_attempt_data($data, $quiz) {
4594 global $DB;
4595 $upgrader = $this->get_attempt_upgrader();
4597 $data = (object)$data;
4599 $layout = explode(',', $data->layout);
4600 $newlayout = $layout;
4602 // Convert each old question_session into a question_attempt.
4603 $qas = array();
4604 foreach (explode(',', $quiz->oldquestions) as $questionid) {
4605 if ($questionid == 0) {
4606 continue;
4609 $newquestionid = $this->get_mappingid('question', $questionid);
4610 if (!$newquestionid) {
4611 throw new restore_step_exception('questionattemptreferstomissingquestion',
4612 $questionid, $questionid);
4615 $question = $upgrader->load_question($newquestionid, $quiz->id);
4617 foreach ($layout as $key => $qid) {
4618 if ($qid == $questionid) {
4619 $newlayout[$key] = $newquestionid;
4623 list($qsession, $qstates) = $this->find_question_session_and_states(
4624 $data, $questionid);
4626 if (empty($qsession) || empty($qstates)) {
4627 throw new restore_step_exception('questionattemptdatamissing',
4628 $questionid, $questionid);
4631 list($qsession, $qstates) = $this->recode_legacy_response_data(
4632 $question, $qsession, $qstates);
4634 $data->layout = implode(',', $newlayout);
4635 $qas[$newquestionid] = $upgrader->convert_question_attempt(
4636 $quiz, $data, $question, $qsession, $qstates);
4639 // Now create a new question_usage.
4640 $usage = new stdClass();
4641 $usage->component = 'mod_quiz';
4642 $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
4643 $usage->preferredbehaviour = $quiz->preferredbehaviour;
4644 $usage->id = $DB->insert_record('question_usages', $usage);
4646 $this->inform_new_usage_id($usage->id);
4648 $data->uniqueid = $usage->id;
4649 $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
4650 $this->questions_recode_layout($quiz->oldquestions));
4653 protected function find_question_session_and_states($data, $questionid) {
4654 $qsession = null;
4655 foreach ($data->sessions['session'] as $session) {
4656 if ($session['questionid'] == $questionid) {
4657 $qsession = (object) $session;
4658 break;
4662 $qstates = array();
4663 foreach ($data->states['state'] as $state) {
4664 if ($state['question'] == $questionid) {
4665 // It would be natural to use $state['seq_number'] as the array-key
4666 // here, but it seems that buggy behaviour in 2.0 and early can
4667 // mean that that is not unique, so we use id, which is guaranteed
4668 // to be unique.
4669 $qstates[$state['id']] = (object) $state;
4672 ksort($qstates);
4673 $qstates = array_values($qstates);
4675 return array($qsession, $qstates);
4679 * Recode any ids in the response data
4680 * @param object $question the question data
4681 * @param object $qsession the question sessions.
4682 * @param array $qstates the question states.
4684 protected function recode_legacy_response_data($question, $qsession, $qstates) {
4685 $qsession->questionid = $question->id;
4687 foreach ($qstates as &$state) {
4688 $state->question = $question->id;
4689 $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
4692 return array($qsession, $qstates);
4696 * Recode the legacy answer field.
4697 * @param object $state the state to recode the answer of.
4698 * @param string $qtype the question type.
4700 public function restore_recode_legacy_answer($state, $qtype) {
4701 $restorer = $this->get_qtype_restorer($qtype);
4702 if ($restorer) {
4703 return $restorer->recode_legacy_state_answer($state);
4704 } else {
4705 return $state->answer;