MDL-47214 core: IPs should be cleaned
[moodle.git] / backup / moodle2 / restore_stepslib.php
blob7f05bb13dc7826190584905782db84c1aa0ae7cd
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 $olduserid = $data->userid;
229 $data->itemid = $this->get_new_parentid('grade_item');
231 $data->userid = $this->get_mappingid('user', $data->userid, null);
232 if (!empty($data->userid)) {
233 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
234 $data->locktime = $this->apply_date_offset($data->locktime);
235 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
236 $data->overridden = $this->apply_date_offset($data->overridden);
237 $data->timecreated = $this->apply_date_offset($data->timecreated);
238 $data->timemodified = $this->apply_date_offset($data->timemodified);
240 $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
241 if ($gradeexists) {
242 $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
243 $this->log($message, backup::LOG_DEBUG);
244 } else {
245 $newitemid = $DB->insert_record('grade_grades', $data);
247 } else {
248 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
249 $this->log($message, backup::LOG_DEBUG);
253 protected function process_grade_category($data) {
254 global $DB;
256 $data = (object)$data;
257 $oldid = $data->id;
259 $data->course = $this->get_courseid();
260 $data->courseid = $data->course;
262 $data->timecreated = $this->apply_date_offset($data->timecreated);
263 $data->timemodified = $this->apply_date_offset($data->timemodified);
265 $newitemid = null;
266 //no parent means a course level grade category. That may have been created when the course was created
267 if(empty($data->parent)) {
268 //parent was being saved as 0 when it should be null
269 $data->parent = null;
271 //get the already created course level grade category
272 $category = new stdclass();
273 $category->courseid = $this->get_courseid();
274 $category->parent = null;
276 $coursecategory = $DB->get_record('grade_categories', (array)$category);
277 if (!empty($coursecategory)) {
278 $data->id = $newitemid = $coursecategory->id;
279 $DB->update_record('grade_categories', $data);
283 //need to insert a course category
284 if (empty($newitemid)) {
285 $newitemid = $DB->insert_record('grade_categories', $data);
287 $this->set_mapping('grade_category', $oldid, $newitemid);
289 protected function process_grade_letter($data) {
290 global $DB;
292 $data = (object)$data;
293 $oldid = $data->id;
295 $data->contextid = context_course::instance($this->get_courseid())->id;
297 $gradeletter = (array)$data;
298 unset($gradeletter['id']);
299 if (!$DB->record_exists('grade_letters', $gradeletter)) {
300 $newitemid = $DB->insert_record('grade_letters', $data);
301 } else {
302 $newitemid = $data->id;
305 $this->set_mapping('grade_letter', $oldid, $newitemid);
307 protected function process_grade_setting($data) {
308 global $DB;
310 $data = (object)$data;
311 $oldid = $data->id;
313 $data->courseid = $this->get_courseid();
315 if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
316 $newitemid = $DB->insert_record('grade_settings', $data);
317 } else {
318 $newitemid = $data->id;
321 $this->set_mapping('grade_setting', $oldid, $newitemid);
325 * put all activity grade items in the correct grade category and mark all for recalculation
327 protected function after_execute() {
328 global $DB;
330 $conditions = array(
331 'backupid' => $this->get_restoreid(),
332 'itemname' => 'grade_item'//,
333 //'itemid' => $itemid
335 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
337 // We need this for calculation magic later on.
338 $mappings = array();
340 if (!empty($rs)) {
341 foreach($rs as $grade_item_backup) {
343 // Store the oldid with the new id.
344 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
346 $updateobj = new stdclass();
347 $updateobj->id = $grade_item_backup->newitemid;
349 //if this is an activity grade item that needs to be put back in its correct category
350 if (!empty($grade_item_backup->parentitemid)) {
351 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
352 if (!is_null($oldcategoryid)) {
353 $updateobj->categoryid = $oldcategoryid;
354 $DB->update_record('grade_items', $updateobj);
356 } else {
357 //mark course and category items as needing to be recalculated
358 $updateobj->needsupdate=1;
359 $DB->update_record('grade_items', $updateobj);
363 $rs->close();
365 // We need to update the calculations for calculated grade items that may reference old
366 // grade item ids using ##gi\d+##.
367 // $mappings can be empty, use 0 if so (won't match ever)
368 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
369 $sql = "SELECT gi.id, gi.calculation
370 FROM {grade_items} gi
371 WHERE gi.id {$sql} AND
372 calculation IS NOT NULL";
373 $rs = $DB->get_recordset_sql($sql, $params);
374 foreach ($rs as $gradeitem) {
375 // Collect all of the used grade item id references
376 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
377 // This calculation doesn't reference any other grade items... EASY!
378 continue;
380 // For this next bit we are going to do the replacement of id's in two steps:
381 // 1. We will replace all old id references with a special mapping reference.
382 // 2. We will replace all mapping references with id's
383 // Why do we do this?
384 // Because there potentially there will be an overlap of ids within the query and we
385 // we substitute the wrong id.. safest way around this is the two step system
386 $calculationmap = array();
387 $mapcount = 0;
388 foreach ($matches[1] as $match) {
389 // Check that the old id is known to us, if not it was broken to begin with and will
390 // continue to be broken.
391 if (!array_key_exists($match, $mappings)) {
392 continue;
394 // Our special mapping key
395 $mapping = '##MAPPING'.$mapcount.'##';
396 // The old id that exists within the calculation now
397 $oldid = '##gi'.$match.'##';
398 // The new id that we want to replace the old one with.
399 $newid = '##gi'.$mappings[$match].'##';
400 // Replace in the special mapping key
401 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
402 // And record the mapping
403 $calculationmap[$mapping] = $newid;
404 $mapcount++;
406 // Iterate all special mappings for this calculation and replace in the new id's
407 foreach ($calculationmap as $mapping => $newid) {
408 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
410 // Update the calculation now that its being remapped
411 $DB->update_record('grade_items', $gradeitem);
413 $rs->close();
415 // Need to correct the grade category path and parent
416 $conditions = array(
417 'courseid' => $this->get_courseid()
420 $rs = $DB->get_recordset('grade_categories', $conditions);
421 // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
422 foreach ($rs as $gc) {
423 if (!empty($gc->parent)) {
424 $grade_category = new stdClass();
425 $grade_category->id = $gc->id;
426 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
427 $DB->update_record('grade_categories', $grade_category);
430 $rs->close();
432 // Now we can rebuild all the paths
433 $rs = $DB->get_recordset('grade_categories', $conditions);
434 foreach ($rs as $gc) {
435 $grade_category = new stdClass();
436 $grade_category->id = $gc->id;
437 $grade_category->path = grade_category::build_path($gc);
438 $grade_category->depth = substr_count($grade_category->path, '/') - 1;
439 $DB->update_record('grade_categories', $grade_category);
441 $rs->close();
443 // Restore marks items as needing update. Update everything now.
444 grade_regrade_final_grades($this->get_courseid());
449 * decode all the interlinks present in restored content
450 * relying 100% in the restore_decode_processor that handles
451 * both the contents to modify and the rules to be applied
453 class restore_decode_interlinks extends restore_execution_step {
455 protected function define_execution() {
456 // Get the decoder (from the plan)
457 $decoder = $this->task->get_decoder();
458 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
459 // And launch it, everything will be processed
460 $decoder->execute();
465 * first, ensure that we have no gaps in section numbers
466 * and then, rebuid the course cache
468 class restore_rebuild_course_cache extends restore_execution_step {
470 protected function define_execution() {
471 global $DB;
473 // Although there is some sort of auto-recovery of missing sections
474 // present in course/formats... here we check that all the sections
475 // from 0 to MAX(section->section) exist, creating them if necessary
476 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
477 // Iterate over all sections
478 for ($i = 0; $i <= $maxsection; $i++) {
479 // If the section $i doesn't exist, create it
480 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
481 $sectionrec = array(
482 'course' => $this->get_courseid(),
483 'section' => $i);
484 $DB->insert_record('course_sections', $sectionrec); // missing section created
488 // Rebuild cache now that all sections are in place
489 rebuild_course_cache($this->get_courseid());
490 cache_helper::purge_by_event('changesincourse');
491 cache_helper::purge_by_event('changesincoursecat');
496 * Review all the tasks having one after_restore method
497 * executing it to perform some final adjustments of information
498 * not available when the task was executed.
500 class restore_execute_after_restore extends restore_execution_step {
502 protected function define_execution() {
504 // Simply call to the execute_after_restore() method of the task
505 // that always is the restore_final_task
506 $this->task->launch_execute_after_restore();
512 * Review all the (pending) block positions in backup_ids, matching by
513 * contextid, creating positions as needed. This is executed by the
514 * final task, once all the contexts have been created
516 class restore_review_pending_block_positions extends restore_execution_step {
518 protected function define_execution() {
519 global $DB;
521 // Get all the block_position objects pending to match
522 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
523 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
524 // Process block positions, creating them or accumulating for final step
525 foreach($rs as $posrec) {
526 // Get the complete position object out of the info field.
527 $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
528 // If position is for one already mapped (known) contextid
529 // process it now, creating the position, else nothing to
530 // do, position finally discarded
531 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
532 $position->contextid = $newctx->newitemid;
533 // Create the block position
534 $DB->insert_record('block_positions', $position);
537 $rs->close();
543 * Updates the availability data for course modules and sections.
545 * Runs after the restore of all course modules, sections, and grade items has
546 * completed. This is necessary in order to update IDs that have changed during
547 * restore.
549 * @package core_backup
550 * @copyright 2014 The Open University
551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
553 class restore_update_availability extends restore_execution_step {
555 protected function define_execution() {
556 global $CFG, $DB;
558 // Note: This code runs even if availability is disabled when restoring.
559 // That will ensure that if you later turn availability on for the site,
560 // there will be no incorrect IDs. (It doesn't take long if the restored
561 // data does not contain any availability information.)
563 // Get modinfo with all data after resetting cache.
564 rebuild_course_cache($this->get_courseid(), true);
565 $modinfo = get_fast_modinfo($this->get_courseid());
567 // Get the date offset for this restore.
568 $dateoffset = $this->apply_date_offset(1) - 1;
570 // Update all sections that were restored.
571 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
572 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
573 $sectionsbyid = null;
574 foreach ($rs as $rec) {
575 if (is_null($sectionsbyid)) {
576 $sectionsbyid = array();
577 foreach ($modinfo->get_section_info_all() as $section) {
578 $sectionsbyid[$section->id] = $section;
581 if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
582 // If the section was not fully restored for some reason
583 // (e.g. due to an earlier error), skip it.
584 $this->get_logger()->process('Section not fully restored: id ' .
585 $rec->newitemid, backup::LOG_WARNING);
586 continue;
588 $section = $sectionsbyid[$rec->newitemid];
589 if (!is_null($section->availability)) {
590 $info = new \core_availability\info_section($section);
591 $info->update_after_restore($this->get_restoreid(),
592 $this->get_courseid(), $this->get_logger(), $dateoffset);
595 $rs->close();
597 // Update all modules that were restored.
598 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
599 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
600 foreach ($rs as $rec) {
601 if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
602 // If the module was not fully restored for some reason
603 // (e.g. due to an earlier error), skip it.
604 $this->get_logger()->process('Module not fully restored: id ' .
605 $rec->newitemid, backup::LOG_WARNING);
606 continue;
608 $cm = $modinfo->get_cm($rec->newitemid);
609 if (!is_null($cm->availability)) {
610 $info = new \core_availability\info_module($cm);
611 $info->update_after_restore($this->get_restoreid(),
612 $this->get_courseid(), $this->get_logger(), $dateoffset);
615 $rs->close();
621 * Process legacy module availability records in backup_ids.
623 * Matches course modules and grade item id once all them have been already restored.
624 * Only if all matchings are satisfied the availability condition will be created.
625 * At the same time, it is required for the site to have that functionality enabled.
627 * This step is included only to handle legacy backups (2.6 and before). It does not
628 * do anything for newer backups.
630 * @copyright 2014 The Open University
631 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
633 class restore_process_course_modules_availability extends restore_execution_step {
635 protected function define_execution() {
636 global $CFG, $DB;
638 // Site hasn't availability enabled
639 if (empty($CFG->enableavailability)) {
640 return;
643 // Do both modules and sections.
644 foreach (array('module', 'section') as $table) {
645 // Get all the availability objects to process.
646 $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
647 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
648 // Process availabilities, creating them if everything matches ok.
649 foreach ($rs as $availrec) {
650 $allmatchesok = true;
651 // Get the complete legacy availability object.
652 $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
654 // Note: This code used to update IDs, but that is now handled by the
655 // current code (after restore) instead of this legacy code.
657 // Get showavailability option.
658 $thingid = ($table === 'module') ? $availability->coursemoduleid :
659 $availability->coursesectionid;
660 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
661 $table . '_showavailability', $thingid);
662 if (!$showrec) {
663 // Should not happen.
664 throw new coding_exception('No matching showavailability record');
666 $show = $showrec->info->showavailability;
668 // The $availability object is now in the format used in the old
669 // system. Interpret this and convert to new system.
670 $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
671 array('id' => $thingid), MUST_EXIST);
672 $newvalue = \core_availability\info::add_legacy_availability_condition(
673 $currentvalue, $availability, $show);
674 $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
675 array('id' => $thingid));
678 $rs->close();
684 * Execution step that, *conditionally* (if there isn't preloaded information)
685 * will load the inforef files for all the included course/section/activity tasks
686 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
688 class restore_load_included_inforef_records extends restore_execution_step {
690 protected function define_execution() {
692 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
693 return;
696 // Get all the included tasks
697 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
698 $progress = $this->task->get_progress();
699 $progress->start_progress($this->get_name(), count($tasks));
700 foreach ($tasks as $task) {
701 // Load the inforef.xml file if exists
702 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
703 if (file_exists($inforefpath)) {
704 // Load each inforef file to temp_ids.
705 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
708 $progress->end_progress();
713 * Execution step that will load all the needed files into backup_files_temp
714 * - info: contains the whole original object (times, names...)
715 * (all them being original ids as loaded from xml)
717 class restore_load_included_files extends restore_structure_step {
719 protected function define_structure() {
721 $file = new restore_path_element('file', '/files/file');
723 return array($file);
727 * Process one <file> element from files.xml
729 * @param array $data the element data
731 public function process_file($data) {
733 $data = (object)$data; // handy
735 // load it if needed:
736 // - it it is one of the annotated inforef files (course/section/activity/block)
737 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
738 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
739 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
740 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
741 $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
742 $data->component == 'grouping' || $data->component == 'grade' ||
743 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
744 if ($isfileref || $iscomponent) {
745 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
751 * Execution step that, *conditionally* (if there isn't preloaded information),
752 * will load all the needed roles to backup_temp_ids. They will be stored with
753 * "role" itemname. Also it will perform one automatic mapping to roles existing
754 * in the target site, based in permissions of the user performing the restore,
755 * archetypes and other bits. At the end, each original role will have its associated
756 * target role or 0 if it's going to be skipped. Note we wrap everything over one
757 * restore_dbops method, as far as the same stuff is going to be also executed
758 * by restore prechecks
760 class restore_load_and_map_roles extends restore_execution_step {
762 protected function define_execution() {
763 if ($this->task->get_preloaded_information()) { // if info is already preloaded
764 return;
767 $file = $this->get_basepath() . '/roles.xml';
768 // Load needed toles to temp_ids
769 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
771 // Process roles, mapping/skipping. Any error throws exception
772 // Note we pass controller's info because it can contain role mapping information
773 // about manual mappings performed by UI
774 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);
779 * Execution step that, *conditionally* (if there isn't preloaded information
780 * and users have been selected in settings, will load all the needed users
781 * to backup_temp_ids. They will be stored with "user" itemname and with
782 * their original contextid as paremitemid
784 class restore_load_included_users extends restore_execution_step {
786 protected function define_execution() {
788 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
789 return;
791 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
792 return;
794 $file = $this->get_basepath() . '/users.xml';
795 // Load needed users to temp_ids.
796 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
801 * Execution step that, *conditionally* (if there isn't preloaded information
802 * and users have been selected in settings, will process all the needed users
803 * in order to decide and perform any action with them (create / map / error)
804 * Note: Any error will cause exception, as far as this is the same processing
805 * than the one into restore prechecks (that should have stopped process earlier)
807 class restore_process_included_users extends restore_execution_step {
809 protected function define_execution() {
811 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
812 return;
814 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
815 return;
817 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
818 $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
823 * Execution step that will create all the needed users as calculated
824 * by @restore_process_included_users (those having newiteind = 0)
826 class restore_create_included_users extends restore_execution_step {
828 protected function define_execution() {
830 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
831 $this->task->get_userid(), $this->task->get_progress());
836 * Structure step that will create all the needed groups and groupings
837 * by loading them from the groups.xml file performing the required matches.
838 * Note group members only will be added if restoring user info
840 class restore_groups_structure_step extends restore_structure_step {
842 protected function define_structure() {
844 $paths = array(); // Add paths here
846 $paths[] = new restore_path_element('group', '/groups/group');
847 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
848 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
850 return $paths;
853 // Processing functions go here
854 public function process_group($data) {
855 global $DB;
857 $data = (object)$data; // handy
858 $data->courseid = $this->get_courseid();
860 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
861 // another a group in the same course
862 $context = context_course::instance($data->courseid);
863 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
864 if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
865 unset($data->idnumber);
867 } else {
868 unset($data->idnumber);
871 $oldid = $data->id; // need this saved for later
873 $restorefiles = false; // Only if we end creating the group
875 // Search if the group already exists (by name & description) in the target course
876 $description_clause = '';
877 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
878 if (!empty($data->description)) {
879 $description_clause = ' AND ' .
880 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
881 $params['description'] = $data->description;
883 if (!$groupdb = $DB->get_record_sql("SELECT *
884 FROM {groups}
885 WHERE courseid = :courseid
886 AND name = :grname $description_clause", $params)) {
887 // group doesn't exist, create
888 $newitemid = $DB->insert_record('groups', $data);
889 $restorefiles = true; // We'll restore the files
890 } else {
891 // group exists, use it
892 $newitemid = $groupdb->id;
894 // Save the id mapping
895 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
896 // Invalidate the course group data cache just in case.
897 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
900 public function process_grouping($data) {
901 global $DB;
903 $data = (object)$data; // handy
904 $data->courseid = $this->get_courseid();
906 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
907 // another a grouping in the same course
908 $context = context_course::instance($data->courseid);
909 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
910 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
911 unset($data->idnumber);
913 } else {
914 unset($data->idnumber);
917 $oldid = $data->id; // need this saved for later
918 $restorefiles = false; // Only if we end creating the grouping
920 // Search if the grouping already exists (by name & description) in the target course
921 $description_clause = '';
922 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
923 if (!empty($data->description)) {
924 $description_clause = ' AND ' .
925 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
926 $params['description'] = $data->description;
928 if (!$groupingdb = $DB->get_record_sql("SELECT *
929 FROM {groupings}
930 WHERE courseid = :courseid
931 AND name = :grname $description_clause", $params)) {
932 // grouping doesn't exist, create
933 $newitemid = $DB->insert_record('groupings', $data);
934 $restorefiles = true; // We'll restore the files
935 } else {
936 // grouping exists, use it
937 $newitemid = $groupingdb->id;
939 // Save the id mapping
940 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
941 // Invalidate the course group data cache just in case.
942 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
945 public function process_grouping_group($data) {
946 global $CFG;
948 require_once($CFG->dirroot.'/group/lib.php');
950 $data = (object)$data;
951 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
954 protected function after_execute() {
955 // Add group related files, matching with "group" mappings
956 $this->add_related_files('group', 'icon', 'group');
957 $this->add_related_files('group', 'description', 'group');
958 // Add grouping related files, matching with "grouping" mappings
959 $this->add_related_files('grouping', 'description', 'grouping');
960 // Invalidate the course group data.
961 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
967 * Structure step that will create all the needed group memberships
968 * by loading them from the groups.xml file performing the required matches.
970 class restore_groups_members_structure_step extends restore_structure_step {
972 protected $plugins = null;
974 protected function define_structure() {
976 $paths = array(); // Add paths here
978 if ($this->get_setting_value('users')) {
979 $paths[] = new restore_path_element('group', '/groups/group');
980 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
983 return $paths;
986 public function process_group($data) {
987 $data = (object)$data; // handy
989 // HACK ALERT!
990 // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
991 // Let's fake internal state to make $this->get_new_parentid('group') work.
993 $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
996 public function process_member($data) {
997 global $DB, $CFG;
998 require_once("$CFG->dirroot/group/lib.php");
1000 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1002 $data = (object)$data; // handy
1004 // get parent group->id
1005 $data->groupid = $this->get_new_parentid('group');
1007 // map user newitemid and insert if not member already
1008 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1009 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1010 // Check the component, if any, exists.
1011 if (empty($data->component)) {
1012 groups_add_member($data->groupid, $data->userid);
1014 } else if ((strpos($data->component, 'enrol_') === 0)) {
1015 // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1016 // it is possible that enrolment was restored using different plugin type.
1017 if (!isset($this->plugins)) {
1018 $this->plugins = enrol_get_plugins(true);
1020 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1021 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1022 if (isset($this->plugins[$instance->enrol])) {
1023 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1028 } else {
1029 $dir = core_component::get_component_directory($data->component);
1030 if ($dir and is_dir($dir)) {
1031 if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1032 return;
1035 // Bad luck, plugin could not restore the data, let's add normal membership.
1036 groups_add_member($data->groupid, $data->userid);
1037 $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1038 $this->log($message, backup::LOG_WARNING);
1046 * Structure step that will create all the needed scales
1047 * by loading them from the scales.xml
1049 class restore_scales_structure_step extends restore_structure_step {
1051 protected function define_structure() {
1053 $paths = array(); // Add paths here
1054 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1055 return $paths;
1058 protected function process_scale($data) {
1059 global $DB;
1061 $data = (object)$data;
1063 $restorefiles = false; // Only if we end creating the group
1065 $oldid = $data->id; // need this saved for later
1067 // Look for scale (by 'scale' both in standard (course=0) and current course
1068 // with priority to standard scales (ORDER clause)
1069 // scale is not course unique, use get_record_sql to suppress warning
1070 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1071 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
1072 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1073 if (!$scadb = $DB->get_record_sql("SELECT *
1074 FROM {scale}
1075 WHERE courseid IN (0, :courseid)
1076 AND $compare_scale_clause
1077 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1078 // Remap the user if possible, defaut to user performing the restore if not
1079 $userid = $this->get_mappingid('user', $data->userid);
1080 $data->userid = $userid ? $userid : $this->task->get_userid();
1081 // Remap the course if course scale
1082 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1083 // If global scale (course=0), check the user has perms to create it
1084 // falling to course scale if not
1085 $systemctx = context_system::instance();
1086 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1087 $data->courseid = $this->get_courseid();
1089 // scale doesn't exist, create
1090 $newitemid = $DB->insert_record('scale', $data);
1091 $restorefiles = true; // We'll restore the files
1092 } else {
1093 // scale exists, use it
1094 $newitemid = $scadb->id;
1096 // Save the id mapping (with files support at system context)
1097 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1100 protected function after_execute() {
1101 // Add scales related files, matching with "scale" mappings
1102 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1108 * Structure step that will create all the needed outocomes
1109 * by loading them from the outcomes.xml
1111 class restore_outcomes_structure_step extends restore_structure_step {
1113 protected function define_structure() {
1115 $paths = array(); // Add paths here
1116 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1117 return $paths;
1120 protected function process_outcome($data) {
1121 global $DB;
1123 $data = (object)$data;
1125 $restorefiles = false; // Only if we end creating the group
1127 $oldid = $data->id; // need this saved for later
1129 // Look for outcome (by shortname both in standard (courseid=null) and current course
1130 // with priority to standard outcomes (ORDER clause)
1131 // outcome is not course unique, use get_record_sql to suppress warning
1132 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1133 if (!$outdb = $DB->get_record_sql('SELECT *
1134 FROM {grade_outcomes}
1135 WHERE shortname = :shortname
1136 AND (courseid = :courseid OR courseid IS NULL)
1137 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1138 // Remap the user
1139 $userid = $this->get_mappingid('user', $data->usermodified);
1140 $data->usermodified = $userid ? $userid : $this->task->get_userid();
1141 // Remap the scale
1142 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1143 // Remap the course if course outcome
1144 $data->courseid = $data->courseid ? $this->get_courseid() : null;
1145 // If global outcome (course=null), check the user has perms to create it
1146 // falling to course outcome if not
1147 $systemctx = context_system::instance();
1148 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1149 $data->courseid = $this->get_courseid();
1151 // outcome doesn't exist, create
1152 $newitemid = $DB->insert_record('grade_outcomes', $data);
1153 $restorefiles = true; // We'll restore the files
1154 } else {
1155 // scale exists, use it
1156 $newitemid = $outdb->id;
1158 // Set the corresponding grade_outcomes_courses record
1159 $outcourserec = new stdclass();
1160 $outcourserec->courseid = $this->get_courseid();
1161 $outcourserec->outcomeid = $newitemid;
1162 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1163 $DB->insert_record('grade_outcomes_courses', $outcourserec);
1165 // Save the id mapping (with files support at system context)
1166 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1169 protected function after_execute() {
1170 // Add outcomes related files, matching with "outcome" mappings
1171 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1176 * Execution step that, *conditionally* (if there isn't preloaded information
1177 * will load all the question categories and questions (header info only)
1178 * to backup_temp_ids. They will be stored with "question_category" and
1179 * "question" itemnames and with their original contextid and question category
1180 * id as paremitemids
1182 class restore_load_categories_and_questions extends restore_execution_step {
1184 protected function define_execution() {
1186 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1187 return;
1189 $file = $this->get_basepath() . '/questions.xml';
1190 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1195 * Execution step that, *conditionally* (if there isn't preloaded information)
1196 * will process all the needed categories and questions
1197 * in order to decide and perform any action with them (create / map / error)
1198 * Note: Any error will cause exception, as far as this is the same processing
1199 * than the one into restore prechecks (that should have stopped process earlier)
1201 class restore_process_categories_and_questions extends restore_execution_step {
1203 protected function define_execution() {
1205 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1206 return;
1208 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1213 * Structure step that will read the section.xml creating/updating sections
1214 * as needed, rebuilding course cache and other friends
1216 class restore_section_structure_step extends restore_structure_step {
1218 protected function define_structure() {
1219 global $CFG;
1221 $paths = array();
1223 $section = new restore_path_element('section', '/section');
1224 $paths[] = $section;
1225 if ($CFG->enableavailability) {
1226 $paths[] = new restore_path_element('availability', '/section/availability');
1227 $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1229 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1231 // Apply for 'format' plugins optional paths at section level
1232 $this->add_plugin_structure('format', $section);
1234 // Apply for 'local' plugins optional paths at section level
1235 $this->add_plugin_structure('local', $section);
1237 return $paths;
1240 public function process_section($data) {
1241 global $CFG, $DB;
1242 $data = (object)$data;
1243 $oldid = $data->id; // We'll need this later
1245 $restorefiles = false;
1247 // Look for the section
1248 $section = new stdclass();
1249 $section->course = $this->get_courseid();
1250 $section->section = $data->number;
1251 // Section doesn't exist, create it with all the info from backup
1252 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1253 $section->name = $data->name;
1254 $section->summary = $data->summary;
1255 $section->summaryformat = $data->summaryformat;
1256 $section->sequence = '';
1257 $section->visible = $data->visible;
1258 if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1259 $section->availability = null;
1260 } else {
1261 $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1262 // Include legacy [<2.7] availability data if provided.
1263 if (is_null($section->availability)) {
1264 $section->availability = \core_availability\info::convert_legacy_fields(
1265 $data, true);
1268 $newitemid = $DB->insert_record('course_sections', $section);
1269 $restorefiles = true;
1271 // Section exists, update non-empty information
1272 } else {
1273 $section->id = $secrec->id;
1274 if ((string)$secrec->name === '') {
1275 $section->name = $data->name;
1277 if (empty($secrec->summary)) {
1278 $section->summary = $data->summary;
1279 $section->summaryformat = $data->summaryformat;
1280 $restorefiles = true;
1283 // Don't update availability (I didn't see a useful way to define
1284 // whether existing or new one should take precedence).
1286 $DB->update_record('course_sections', $section);
1287 $newitemid = $secrec->id;
1290 // Annotate the section mapping, with restorefiles option if needed
1291 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1293 // set the new course_section id in the task
1294 $this->task->set_sectionid($newitemid);
1296 // If there is the legacy showavailability data, store this for later use.
1297 // (This data is not present when restoring 'new' backups.)
1298 if (isset($data->showavailability)) {
1299 // Cache the showavailability flag using the backup_ids data field.
1300 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1301 'section_showavailability', $newitemid, 0, null,
1302 (object)array('showavailability' => $data->showavailability));
1305 // Commented out. We never modify course->numsections as far as that is used
1306 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1307 // Note: We keep the code here, to know about and because of the possibility of making this
1308 // optional based on some setting/attribute in the future
1309 // If needed, adjust course->numsections
1310 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1311 // if ($numsections < $section->section) {
1312 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1313 // }
1318 * Process the legacy availability table record. This table does not exist
1319 * in Moodle 2.7+ but we still support restore.
1321 * @param stdClass $data Record data
1323 public function process_availability($data) {
1324 $data = (object)$data;
1325 // Simply going to store the whole availability record now, we'll process
1326 // all them later in the final task (once all activities have been restored)
1327 // Let's call the low level one to be able to store the whole object.
1328 $data->coursesectionid = $this->task->get_sectionid();
1329 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1330 'section_availability', $data->id, 0, null, $data);
1334 * Process the legacy availability fields table record. This table does not
1335 * exist in Moodle 2.7+ but we still support restore.
1337 * @param stdClass $data Record data
1339 public function process_availability_field($data) {
1340 global $DB;
1341 $data = (object)$data;
1342 // Mark it is as passed by default
1343 $passed = true;
1344 $customfieldid = null;
1346 // If a customfield has been used in order to pass we must be able to match an existing
1347 // customfield by name (data->customfield) and type (data->customfieldtype)
1348 if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1349 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1350 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1351 $passed = false;
1352 } else if (!is_null($data->customfield)) {
1353 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1354 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1355 $passed = ($customfieldid !== false);
1358 if ($passed) {
1359 // Create the object to insert into the database
1360 $availfield = new stdClass();
1361 $availfield->coursesectionid = $this->task->get_sectionid();
1362 $availfield->userfield = $data->userfield;
1363 $availfield->customfieldid = $customfieldid;
1364 $availfield->operator = $data->operator;
1365 $availfield->value = $data->value;
1367 // Get showavailability option.
1368 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1369 'section_showavailability', $availfield->coursesectionid);
1370 if (!$showrec) {
1371 // Should not happen.
1372 throw new coding_exception('No matching showavailability record');
1374 $show = $showrec->info->showavailability;
1376 // The $availfield object is now in the format used in the old
1377 // system. Interpret this and convert to new system.
1378 $currentvalue = $DB->get_field('course_sections', 'availability',
1379 array('id' => $availfield->coursesectionid), MUST_EXIST);
1380 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1381 $currentvalue, $availfield, $show);
1382 $DB->set_field('course_sections', 'availability', $newvalue,
1383 array('id' => $availfield->coursesectionid));
1387 public function process_course_format_options($data) {
1388 global $DB;
1389 $data = (object)$data;
1390 $oldid = $data->id;
1391 unset($data->id);
1392 $data->sectionid = $this->task->get_sectionid();
1393 $data->courseid = $this->get_courseid();
1394 $newid = $DB->insert_record('course_format_options', $data);
1395 $this->set_mapping('course_format_options', $oldid, $newid);
1398 protected function after_execute() {
1399 // Add section related files, with 'course_section' itemid to match
1400 $this->add_related_files('course', 'section', 'course_section');
1405 * Structure step that will read the course.xml file, loading it and performing
1406 * various actions depending of the site/restore settings. Note that target
1407 * course always exist before arriving here so this step will be updating
1408 * the course record (never inserting)
1410 class restore_course_structure_step extends restore_structure_step {
1412 * @var bool this gets set to true by {@link process_course()} if we are
1413 * restoring an old coures that used the legacy 'module security' feature.
1414 * If so, we have to do more work in {@link after_execute()}.
1416 protected $legacyrestrictmodules = false;
1419 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1420 * array with array keys the module names ('forum', 'quiz', etc.). These are
1421 * the modules that are allowed according to the data in the backup file.
1422 * In {@link after_execute()} we then have to prevent adding of all the other
1423 * types of activity.
1425 protected $legacyallowedmodules = array();
1427 protected function define_structure() {
1429 $course = new restore_path_element('course', '/course');
1430 $category = new restore_path_element('category', '/course/category');
1431 $tag = new restore_path_element('tag', '/course/tags/tag');
1432 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1434 // Apply for 'format' plugins optional paths at course level
1435 $this->add_plugin_structure('format', $course);
1437 // Apply for 'theme' plugins optional paths at course level
1438 $this->add_plugin_structure('theme', $course);
1440 // Apply for 'report' plugins optional paths at course level
1441 $this->add_plugin_structure('report', $course);
1443 // Apply for 'course report' plugins optional paths at course level
1444 $this->add_plugin_structure('coursereport', $course);
1446 // Apply for plagiarism plugins optional paths at course level
1447 $this->add_plugin_structure('plagiarism', $course);
1449 // Apply for local plugins optional paths at course level
1450 $this->add_plugin_structure('local', $course);
1452 return array($course, $category, $tag, $allowed_module);
1456 * Processing functions go here
1458 * @global moodledatabase $DB
1459 * @param stdClass $data
1461 public function process_course($data) {
1462 global $CFG, $DB;
1464 $data = (object)$data;
1466 $fullname = $this->get_setting_value('course_fullname');
1467 $shortname = $this->get_setting_value('course_shortname');
1468 $startdate = $this->get_setting_value('course_startdate');
1470 // Calculate final course names, to avoid dupes
1471 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1473 // Need to change some fields before updating the course record
1474 $data->id = $this->get_courseid();
1475 $data->fullname = $fullname;
1476 $data->shortname= $shortname;
1478 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1479 // another course on this site.
1480 $context = context::instance_by_id($this->task->get_contextid());
1481 if (!empty($data->idnumber) && has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid()) &&
1482 $this->task->is_samesite() && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1483 // Do not reset idnumber.
1484 } else {
1485 $data->idnumber = '';
1488 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1489 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1490 if (empty($data->hiddensections)) {
1491 $data->hiddensections = 0;
1494 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1495 // then we will need to process restricted modules after execution.
1496 $this->legacyrestrictmodules = !empty($data->restrictmodules);
1498 $data->startdate= $this->apply_date_offset($data->startdate);
1499 if ($data->defaultgroupingid) {
1500 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1502 if (empty($CFG->enablecompletion)) {
1503 $data->enablecompletion = 0;
1504 $data->completionstartonenrol = 0;
1505 $data->completionnotify = 0;
1507 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1508 if (!array_key_exists($data->lang, $languages)) {
1509 $data->lang = '';
1512 $themes = get_list_of_themes(); // Get themes for quick search later
1513 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1514 $data->theme = '';
1517 // Check if this is an old SCORM course format.
1518 if ($data->format == 'scorm') {
1519 $data->format = 'singleactivity';
1520 $data->activitytype = 'scorm';
1523 // Course record ready, update it
1524 $DB->update_record('course', $data);
1526 course_get_format($data)->update_course_format_options($data);
1528 // Role name aliases
1529 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1532 public function process_category($data) {
1533 // Nothing to do with the category. UI sets it before restore starts
1536 public function process_tag($data) {
1537 global $CFG, $DB;
1539 $data = (object)$data;
1541 if (!empty($CFG->usetags)) { // if enabled in server
1542 // TODO: This is highly inneficient. Each time we add one tag
1543 // we fetch all the existing because tag_set() deletes them
1544 // so everything must be reinserted on each call
1545 $tags = array();
1546 $existingtags = tag_get_tags('course', $this->get_courseid());
1547 // Re-add all the existitng tags
1548 foreach ($existingtags as $existingtag) {
1549 $tags[] = $existingtag->rawname;
1551 // Add the one being restored
1552 $tags[] = $data->rawname;
1553 // Send all the tags back to the course
1554 tag_set('course', $this->get_courseid(), $tags, 'core',
1555 context_course::instance($this->get_courseid())->id);
1559 public function process_allowed_module($data) {
1560 $data = (object)$data;
1562 // Backwards compatiblity support for the data that used to be in the
1563 // course_allowed_modules table.
1564 if ($this->legacyrestrictmodules) {
1565 $this->legacyallowedmodules[$data->modulename] = 1;
1569 protected function after_execute() {
1570 global $DB;
1572 // Add course related files, without itemid to match
1573 $this->add_related_files('course', 'summary', null);
1574 $this->add_related_files('course', 'overviewfiles', null);
1576 // Deal with legacy allowed modules.
1577 if ($this->legacyrestrictmodules) {
1578 $context = context_course::instance($this->get_courseid());
1580 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1581 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1582 foreach ($managerroleids as $roleid) {
1583 unset($roleids[$roleid]);
1586 foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1587 if (isset($this->legacyallowedmodules[$modname])) {
1588 // Module is allowed, no worries.
1589 continue;
1592 $capability = 'mod/' . $modname . ':addinstance';
1593 foreach ($roleids as $roleid) {
1594 assign_capability($capability, CAP_PREVENT, $roleid, $context);
1602 * Execution step that will migrate legacy files if present.
1604 class restore_course_legacy_files_step extends restore_execution_step {
1605 public function define_execution() {
1606 global $DB;
1608 // Do a check for legacy files and skip if there are none.
1609 $sql = 'SELECT count(*)
1610 FROM {backup_files_temp}
1611 WHERE backupid = ?
1612 AND contextid = ?
1613 AND component = ?
1614 AND filearea = ?';
1615 $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
1617 if ($DB->count_records_sql($sql, $params)) {
1618 $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
1619 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
1620 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
1626 * Structure step that will read the roles.xml file (at course/activity/block levels)
1627 * containing all the role_assignments and overrides for that context. If corresponding to
1628 * one mapped role, they will be applied to target context. Will observe the role_assignments
1629 * setting to decide if ras are restored.
1631 * Note: this needs to be executed after all users are enrolled.
1633 class restore_ras_and_caps_structure_step extends restore_structure_step {
1634 protected $plugins = null;
1636 protected function define_structure() {
1638 $paths = array();
1640 // Observe the role_assignments setting
1641 if ($this->get_setting_value('role_assignments')) {
1642 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1644 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1646 return $paths;
1650 * Assign roles
1652 * This has to be called after enrolments processing.
1654 * @param mixed $data
1655 * @return void
1657 public function process_assignment($data) {
1658 global $DB;
1660 $data = (object)$data;
1662 // Check roleid, userid are one of the mapped ones
1663 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1664 return;
1666 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1667 return;
1669 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1670 // Only assign roles to not deleted users
1671 return;
1673 if (!$contextid = $this->task->get_contextid()) {
1674 return;
1677 if (empty($data->component)) {
1678 // assign standard manual roles
1679 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1680 role_assign($newroleid, $newuserid, $contextid);
1682 } else if ((strpos($data->component, 'enrol_') === 0)) {
1683 // Deal with enrolment roles - ignore the component and just find out the instance via new id,
1684 // it is possible that enrolment was restored using different plugin type.
1685 if (!isset($this->plugins)) {
1686 $this->plugins = enrol_get_plugins(true);
1688 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1689 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1690 if (isset($this->plugins[$instance->enrol])) {
1691 $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
1696 } else {
1697 $data->roleid = $newroleid;
1698 $data->userid = $newuserid;
1699 $data->contextid = $contextid;
1700 $dir = core_component::get_component_directory($data->component);
1701 if ($dir and is_dir($dir)) {
1702 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
1703 return;
1706 // Bad luck, plugin could not restore the data, let's add normal membership.
1707 role_assign($data->roleid, $data->userid, $data->contextid);
1708 $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
1709 $this->log($message, backup::LOG_WARNING);
1713 public function process_override($data) {
1714 $data = (object)$data;
1716 // Check roleid is one of the mapped ones
1717 $newroleid = $this->get_mappingid('role', $data->roleid);
1718 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1719 if ($newroleid && $this->task->get_contextid()) {
1720 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1721 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1722 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1728 * If no instances yet add default enrol methods the same way as when creating new course in UI.
1730 class restore_default_enrolments_step extends restore_execution_step {
1731 public function define_execution() {
1732 global $DB;
1734 $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
1736 if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
1737 // Something already added instances, do not add default instances.
1738 $plugins = enrol_get_plugins(true);
1739 foreach ($plugins as $plugin) {
1740 $plugin->restore_sync_course($course);
1743 } else {
1744 // Looks like a newly created course.
1745 enrol_course_updated(true, $course, null);
1751 * This structure steps restores the enrol plugins and their underlying
1752 * enrolments, performing all the mappings and/or movements required
1754 class restore_enrolments_structure_step extends restore_structure_step {
1755 protected $enrolsynced = false;
1756 protected $plugins = null;
1757 protected $originalstatus = array();
1760 * Conditionally decide if this step should be executed.
1762 * This function checks the following parameter:
1764 * 1. the course/enrolments.xml file exists
1766 * @return bool true is safe to execute, false otherwise
1768 protected function execute_condition() {
1770 // Check it is included in the backup
1771 $fullpath = $this->task->get_taskbasepath();
1772 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1773 if (!file_exists($fullpath)) {
1774 // Not found, can't restore enrolments info
1775 return false;
1778 return true;
1781 protected function define_structure() {
1783 $paths = array();
1785 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1786 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1788 return $paths;
1792 * Create enrolment instances.
1794 * This has to be called after creation of roles
1795 * and before adding of role assignments.
1797 * @param mixed $data
1798 * @return void
1800 public function process_enrol($data) {
1801 global $DB;
1803 $data = (object)$data;
1804 $oldid = $data->id; // We'll need this later.
1805 unset($data->id);
1807 $this->originalstatus[$oldid] = $data->status;
1809 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
1810 $this->set_mapping('enrol', $oldid, 0);
1811 return;
1814 if (!isset($this->plugins)) {
1815 $this->plugins = enrol_get_plugins(true);
1818 if (!$this->enrolsynced) {
1819 // Make sure that all plugin may create instances and enrolments automatically
1820 // before the first instance restore - this is suitable especially for plugins
1821 // that synchronise data automatically using course->idnumber or by course categories.
1822 foreach ($this->plugins as $plugin) {
1823 $plugin->restore_sync_course($courserec);
1825 $this->enrolsynced = true;
1828 // Map standard fields - plugin has to process custom fields manually.
1829 $data->roleid = $this->get_mappingid('role', $data->roleid);
1830 $data->courseid = $courserec->id;
1832 if ($this->get_setting_value('enrol_migratetomanual')) {
1833 unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
1834 if (!enrol_is_enabled('manual')) {
1835 $this->set_mapping('enrol', $oldid, 0);
1836 return;
1838 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
1839 $instance = reset($instances);
1840 $this->set_mapping('enrol', $oldid, $instance->id);
1841 } else {
1842 if ($data->enrol === 'manual') {
1843 $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
1844 } else {
1845 $instanceid = $this->plugins['manual']->add_default_instance($courserec);
1847 $this->set_mapping('enrol', $oldid, $instanceid);
1850 } else {
1851 if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
1852 $this->set_mapping('enrol', $oldid, 0);
1853 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments";
1854 $this->log($message, backup::LOG_WARNING);
1855 return;
1857 if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
1858 // Let's keep the sortorder in old backups.
1859 } else {
1860 // Prevent problems with colliding sortorders in old backups,
1861 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
1862 unset($data->sortorder);
1864 // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
1865 $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
1870 * Create user enrolments.
1872 * This has to be called after creation of enrolment instances
1873 * and before adding of role assignments.
1875 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
1877 * @param mixed $data
1878 * @return void
1880 public function process_enrolment($data) {
1881 global $DB;
1883 if (!isset($this->plugins)) {
1884 $this->plugins = enrol_get_plugins(true);
1887 $data = (object)$data;
1889 // Process only if parent instance have been mapped.
1890 if ($enrolid = $this->get_new_parentid('enrol')) {
1891 $oldinstancestatus = ENROL_INSTANCE_ENABLED;
1892 $oldenrolid = $this->get_old_parentid('enrol');
1893 if (isset($this->originalstatus[$oldenrolid])) {
1894 $oldinstancestatus = $this->originalstatus[$oldenrolid];
1896 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1897 // And only if user is a mapped one.
1898 if ($userid = $this->get_mappingid('user', $data->userid)) {
1899 if (isset($this->plugins[$instance->enrol])) {
1900 $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
1910 * Make sure the user restoring the course can actually access it.
1912 class restore_fix_restorer_access_step extends restore_execution_step {
1913 protected function define_execution() {
1914 global $CFG, $DB;
1916 if (!$userid = $this->task->get_userid()) {
1917 return;
1920 if (empty($CFG->restorernewroleid)) {
1921 // Bad luck, no fallback role for restorers specified
1922 return;
1925 $courseid = $this->get_courseid();
1926 $context = context_course::instance($courseid);
1928 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1929 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
1930 return;
1933 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
1934 role_assign($CFG->restorernewroleid, $userid, $context);
1936 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1937 // Extra role is enough, yay!
1938 return;
1941 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
1942 // hopefully admin selected suitable $CFG->restorernewroleid ...
1943 if (!enrol_is_enabled('manual')) {
1944 return;
1946 if (!$enrol = enrol_get_plugin('manual')) {
1947 return;
1949 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
1950 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
1951 $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
1952 $enrol->add_instance($course, $fields);
1955 enrol_try_internal_enrol($courseid, $userid);
1961 * This structure steps restores the filters and their configs
1963 class restore_filters_structure_step extends restore_structure_step {
1965 protected function define_structure() {
1967 $paths = array();
1969 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1970 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1972 return $paths;
1975 public function process_active($data) {
1977 $data = (object)$data;
1979 if (strpos($data->filter, 'filter/') === 0) {
1980 $data->filter = substr($data->filter, 7);
1982 } else if (strpos($data->filter, '/') !== false) {
1983 // Unsupported old filter.
1984 return;
1987 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1988 return;
1990 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1993 public function process_config($data) {
1995 $data = (object)$data;
1997 if (strpos($data->filter, 'filter/') === 0) {
1998 $data->filter = substr($data->filter, 7);
2000 } else if (strpos($data->filter, '/') !== false) {
2001 // Unsupported old filter.
2002 return;
2005 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2006 return;
2008 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2014 * This structure steps restores the comments
2015 * Note: Cannot use the comments API because defaults to USER->id.
2016 * That should change allowing to pass $userid
2018 class restore_comments_structure_step extends restore_structure_step {
2020 protected function define_structure() {
2022 $paths = array();
2024 $paths[] = new restore_path_element('comment', '/comments/comment');
2026 return $paths;
2029 public function process_comment($data) {
2030 global $DB;
2032 $data = (object)$data;
2034 // First of all, if the comment has some itemid, ask to the task what to map
2035 $mapping = false;
2036 if ($data->itemid) {
2037 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2038 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2040 // Only restore the comment if has no mapping OR we have found the matching mapping
2041 if (!$mapping || $data->itemid) {
2042 // Only if user mapping and context
2043 $data->userid = $this->get_mappingid('user', $data->userid);
2044 if ($data->userid && $this->task->get_contextid()) {
2045 $data->contextid = $this->task->get_contextid();
2046 // Only if there is another comment with same context/user/timecreated
2047 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2048 if (!$DB->record_exists('comments', $params)) {
2049 $DB->insert_record('comments', $data);
2057 * This structure steps restores the badges and their configs
2059 class restore_badges_structure_step extends restore_structure_step {
2062 * Conditionally decide if this step should be executed.
2064 * This function checks the following parameters:
2066 * 1. Badges and course badges are enabled on the site.
2067 * 2. The course/badges.xml file exists.
2068 * 3. All modules are restorable.
2069 * 4. All modules are marked for restore.
2071 * @return bool True is safe to execute, false otherwise
2073 protected function execute_condition() {
2074 global $CFG;
2076 // First check is badges and course level badges are enabled on this site.
2077 if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2078 // Disabled, don't restore course badges.
2079 return false;
2082 // Check if badges.xml is included in the backup.
2083 $fullpath = $this->task->get_taskbasepath();
2084 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2085 if (!file_exists($fullpath)) {
2086 // Not found, can't restore course badges.
2087 return false;
2090 // Check we are able to restore all backed up modules.
2091 if ($this->task->is_missing_modules()) {
2092 return false;
2095 // Finally check all modules within the backup are being restored.
2096 if ($this->task->is_excluding_activities()) {
2097 return false;
2100 return true;
2103 protected function define_structure() {
2104 $paths = array();
2105 $paths[] = new restore_path_element('badge', '/badges/badge');
2106 $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2107 $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2108 $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2110 return $paths;
2113 public function process_badge($data) {
2114 global $DB, $CFG;
2116 require_once($CFG->libdir . '/badgeslib.php');
2118 $data = (object)$data;
2119 $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2120 if (empty($data->usercreated)) {
2121 $data->usercreated = $this->task->get_userid();
2123 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2124 if (empty($data->usermodified)) {
2125 $data->usermodified = $this->task->get_userid();
2128 // We'll restore the badge image.
2129 $restorefiles = true;
2131 $courseid = $this->get_courseid();
2133 $params = array(
2134 'name' => $data->name,
2135 'description' => $data->description,
2136 'timecreated' => $this->apply_date_offset($data->timecreated),
2137 'timemodified' => $this->apply_date_offset($data->timemodified),
2138 'usercreated' => $data->usercreated,
2139 'usermodified' => $data->usermodified,
2140 'issuername' => $data->issuername,
2141 'issuerurl' => $data->issuerurl,
2142 'issuercontact' => $data->issuercontact,
2143 'expiredate' => $this->apply_date_offset($data->expiredate),
2144 'expireperiod' => $data->expireperiod,
2145 'type' => BADGE_TYPE_COURSE,
2146 'courseid' => $courseid,
2147 'message' => $data->message,
2148 'messagesubject' => $data->messagesubject,
2149 'attachment' => $data->attachment,
2150 'notification' => $data->notification,
2151 'status' => BADGE_STATUS_INACTIVE,
2152 'nextcron' => $this->apply_date_offset($data->nextcron)
2155 $newid = $DB->insert_record('badge', $params);
2156 $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2159 public function process_criterion($data) {
2160 global $DB;
2162 $data = (object)$data;
2164 $params = array(
2165 'badgeid' => $this->get_new_parentid('badge'),
2166 'criteriatype' => $data->criteriatype,
2167 'method' => $data->method
2169 $newid = $DB->insert_record('badge_criteria', $params);
2170 $this->set_mapping('criterion', $data->id, $newid);
2173 public function process_parameter($data) {
2174 global $DB, $CFG;
2176 require_once($CFG->libdir . '/badgeslib.php');
2178 $data = (object)$data;
2179 $criteriaid = $this->get_new_parentid('criterion');
2181 // Parameter array that will go to database.
2182 $params = array();
2183 $params['critid'] = $criteriaid;
2185 $oldparam = explode('_', $data->name);
2187 if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2188 $module = $this->get_mappingid('course_module', $oldparam[1]);
2189 $params['name'] = $oldparam[0] . '_' . $module;
2190 $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2191 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2192 $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2193 $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2194 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2195 $role = $this->get_mappingid('role', $data->value);
2196 if (!empty($role)) {
2197 $params['name'] = 'role_' . $role;
2198 $params['value'] = $role;
2199 } else {
2200 return;
2204 if (!$DB->record_exists('badge_criteria_param', $params)) {
2205 $DB->insert_record('badge_criteria_param', $params);
2209 public function process_manual_award($data) {
2210 global $DB;
2212 $data = (object)$data;
2213 $role = $this->get_mappingid('role', $data->issuerrole);
2215 if (!empty($role)) {
2216 $award = array(
2217 'badgeid' => $this->get_new_parentid('badge'),
2218 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2219 'issuerid' => $this->get_mappingid('user', $data->issuerid),
2220 'issuerrole' => $role,
2221 'datemet' => $this->apply_date_offset($data->datemet)
2224 // Skip the manual award if recipient or issuer can not be mapped to.
2225 if (empty($award['recipientid']) || empty($award['issuerid'])) {
2226 return;
2229 $DB->insert_record('badge_manual_award', $award);
2233 protected function after_execute() {
2234 // Add related files.
2235 $this->add_related_files('badges', 'badgeimage', 'badge');
2240 * This structure steps restores the calendar events
2242 class restore_calendarevents_structure_step extends restore_structure_step {
2244 protected function define_structure() {
2246 $paths = array();
2248 $paths[] = new restore_path_element('calendarevents', '/events/event');
2250 return $paths;
2253 public function process_calendarevents($data) {
2254 global $DB, $SITE;
2256 $data = (object)$data;
2257 $oldid = $data->id;
2258 $restorefiles = true; // We'll restore the files
2259 // Find the userid and the groupid associated with the event. Return if not found.
2260 $data->userid = $this->get_mappingid('user', $data->userid);
2261 if ($data->userid === false) {
2262 return;
2264 if (!empty($data->groupid)) {
2265 $data->groupid = $this->get_mappingid('group', $data->groupid);
2266 if ($data->groupid === false) {
2267 return;
2270 // Handle events with empty eventtype //MDL-32827
2271 if(empty($data->eventtype)) {
2272 if ($data->courseid == $SITE->id) { // Site event
2273 $data->eventtype = "site";
2274 } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2275 // Course assingment event
2276 $data->eventtype = "due";
2277 } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event
2278 $data->eventtype = "course";
2279 } else if ($data->groupid) { // Group event
2280 $data->eventtype = "group";
2281 } else if ($data->userid) { // User event
2282 $data->eventtype = "user";
2283 } else {
2284 return;
2288 $params = array(
2289 'name' => $data->name,
2290 'description' => $data->description,
2291 'format' => $data->format,
2292 'courseid' => $this->get_courseid(),
2293 'groupid' => $data->groupid,
2294 'userid' => $data->userid,
2295 'repeatid' => $data->repeatid,
2296 'modulename' => $data->modulename,
2297 'eventtype' => $data->eventtype,
2298 'timestart' => $this->apply_date_offset($data->timestart),
2299 'timeduration' => $data->timeduration,
2300 'visible' => $data->visible,
2301 'uuid' => $data->uuid,
2302 'sequence' => $data->sequence,
2303 'timemodified' => $this->apply_date_offset($data->timemodified));
2304 if ($this->name == 'activity_calendar') {
2305 $params['instance'] = $this->task->get_activityid();
2306 } else {
2307 $params['instance'] = 0;
2309 $sql = "SELECT id
2310 FROM {event}
2311 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2312 AND courseid = ?
2313 AND repeatid = ?
2314 AND modulename = ?
2315 AND timestart = ?
2316 AND timeduration = ?
2317 AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2318 $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
2319 $result = $DB->record_exists_sql($sql, $arg);
2320 if (empty($result)) {
2321 $newitemid = $DB->insert_record('event', $params);
2322 $this->set_mapping('event', $oldid, $newitemid);
2323 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2327 protected function after_execute() {
2328 // Add related files
2329 $this->add_related_files('calendar', 'event_description', 'event_description');
2333 class restore_course_completion_structure_step extends restore_structure_step {
2336 * Conditionally decide if this step should be executed.
2338 * This function checks parameters that are not immediate settings to ensure
2339 * that the enviroment is suitable for the restore of course completion info.
2341 * This function checks the following four parameters:
2343 * 1. Course completion is enabled on the site
2344 * 2. The backup includes course completion information
2345 * 3. All modules are restorable
2346 * 4. All modules are marked for restore.
2348 * @return bool True is safe to execute, false otherwise
2350 protected function execute_condition() {
2351 global $CFG;
2353 // First check course completion is enabled on this site
2354 if (empty($CFG->enablecompletion)) {
2355 // Disabled, don't restore course completion
2356 return false;
2359 // Check it is included in the backup
2360 $fullpath = $this->task->get_taskbasepath();
2361 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2362 if (!file_exists($fullpath)) {
2363 // Not found, can't restore course completion
2364 return false;
2367 // Check we are able to restore all backed up modules
2368 if ($this->task->is_missing_modules()) {
2369 return false;
2372 // Finally check all modules within the backup are being restored.
2373 if ($this->task->is_excluding_activities()) {
2374 return false;
2377 return true;
2381 * Define the course completion structure
2383 * @return array Array of restore_path_element
2385 protected function define_structure() {
2387 // To know if we are including user completion info
2388 $userinfo = $this->get_setting_value('userscompletion');
2390 $paths = array();
2391 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2392 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2394 if ($userinfo) {
2395 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2396 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2399 return $paths;
2404 * Process course completion criteria
2406 * @global moodle_database $DB
2407 * @param stdClass $data
2409 public function process_course_completion_criteria($data) {
2410 global $DB;
2412 $data = (object)$data;
2413 $data->course = $this->get_courseid();
2415 // Apply the date offset to the time end field
2416 $data->timeend = $this->apply_date_offset($data->timeend);
2418 // Map the role from the criteria
2419 if (!empty($data->role)) {
2420 $data->role = $this->get_mappingid('role', $data->role);
2423 $skipcriteria = false;
2425 // If the completion criteria is for a module we need to map the module instance
2426 // to the new module id.
2427 if (!empty($data->moduleinstance) && !empty($data->module)) {
2428 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
2429 if (empty($data->moduleinstance)) {
2430 $skipcriteria = true;
2432 } else {
2433 $data->module = null;
2434 $data->moduleinstance = null;
2437 // We backup the course shortname rather than the ID so that we can match back to the course
2438 if (!empty($data->courseinstanceshortname)) {
2439 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
2440 if (!$courseinstanceid) {
2441 $skipcriteria = true;
2443 } else {
2444 $courseinstanceid = null;
2446 $data->courseinstance = $courseinstanceid;
2448 if (!$skipcriteria) {
2449 $params = array(
2450 'course' => $data->course,
2451 'criteriatype' => $data->criteriatype,
2452 'enrolperiod' => $data->enrolperiod,
2453 'courseinstance' => $data->courseinstance,
2454 'module' => $data->module,
2455 'moduleinstance' => $data->moduleinstance,
2456 'timeend' => $data->timeend,
2457 'gradepass' => $data->gradepass,
2458 'role' => $data->role
2460 $newid = $DB->insert_record('course_completion_criteria', $params);
2461 $this->set_mapping('course_completion_criteria', $data->id, $newid);
2466 * Processes course compltion criteria complete records
2468 * @global moodle_database $DB
2469 * @param stdClass $data
2471 public function process_course_completion_crit_compl($data) {
2472 global $DB;
2474 $data = (object)$data;
2476 // This may be empty if criteria could not be restored
2477 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
2479 $data->course = $this->get_courseid();
2480 $data->userid = $this->get_mappingid('user', $data->userid);
2482 if (!empty($data->criteriaid) && !empty($data->userid)) {
2483 $params = array(
2484 'userid' => $data->userid,
2485 'course' => $data->course,
2486 'criteriaid' => $data->criteriaid,
2487 'timecompleted' => $this->apply_date_offset($data->timecompleted)
2489 if (isset($data->gradefinal)) {
2490 $params['gradefinal'] = $data->gradefinal;
2492 if (isset($data->unenroled)) {
2493 $params['unenroled'] = $data->unenroled;
2495 $DB->insert_record('course_completion_crit_compl', $params);
2500 * Process course completions
2502 * @global moodle_database $DB
2503 * @param stdClass $data
2505 public function process_course_completions($data) {
2506 global $DB;
2508 $data = (object)$data;
2510 $data->course = $this->get_courseid();
2511 $data->userid = $this->get_mappingid('user', $data->userid);
2513 if (!empty($data->userid)) {
2514 $params = array(
2515 'userid' => $data->userid,
2516 'course' => $data->course,
2517 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
2518 'timestarted' => $this->apply_date_offset($data->timestarted),
2519 'timecompleted' => $this->apply_date_offset($data->timecompleted),
2520 'reaggregate' => $data->reaggregate
2522 $DB->insert_record('course_completions', $params);
2527 * Process course completion aggregate methods
2529 * @global moodle_database $DB
2530 * @param stdClass $data
2532 public function process_course_completion_aggr_methd($data) {
2533 global $DB;
2535 $data = (object)$data;
2537 $data->course = $this->get_courseid();
2539 // Only create the course_completion_aggr_methd records if
2540 // the target course has not them defined. MDL-28180
2541 if (!$DB->record_exists('course_completion_aggr_methd', array(
2542 'course' => $data->course,
2543 'criteriatype' => $data->criteriatype))) {
2544 $params = array(
2545 'course' => $data->course,
2546 'criteriatype' => $data->criteriatype,
2547 'method' => $data->method,
2548 'value' => $data->value,
2550 $DB->insert_record('course_completion_aggr_methd', $params);
2557 * This structure step restores course logs (cmid = 0), delegating
2558 * the hard work to the corresponding {@link restore_logs_processor} passing the
2559 * collection of {@link restore_log_rule} rules to be observed as they are defined
2560 * by the task. Note this is only executed based in the 'logs' setting.
2562 * NOTE: This is executed by final task, to have all the activities already restored
2564 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2565 * records are. There are others like 'calendar' and 'upload' that will be handled
2566 * later.
2568 * NOTE: All the missing actions (not able to be restored) are sent to logs for
2569 * debugging purposes
2571 class restore_course_logs_structure_step extends restore_structure_step {
2574 * Conditionally decide if this step should be executed.
2576 * This function checks the following parameter:
2578 * 1. the course/logs.xml file exists
2580 * @return bool true is safe to execute, false otherwise
2582 protected function execute_condition() {
2584 // Check it is included in the backup
2585 $fullpath = $this->task->get_taskbasepath();
2586 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2587 if (!file_exists($fullpath)) {
2588 // Not found, can't restore course logs
2589 return false;
2592 return true;
2595 protected function define_structure() {
2597 $paths = array();
2599 // Simple, one plain level of information contains them
2600 $paths[] = new restore_path_element('log', '/logs/log');
2602 return $paths;
2605 protected function process_log($data) {
2606 global $DB;
2608 $data = (object)($data);
2610 $data->time = $this->apply_date_offset($data->time);
2611 $data->userid = $this->get_mappingid('user', $data->userid);
2612 $data->course = $this->get_courseid();
2613 $data->cmid = 0;
2615 // For any reason user wasn't remapped ok, stop processing this
2616 if (empty($data->userid)) {
2617 return;
2620 // Everything ready, let's delegate to the restore_logs_processor
2622 // Set some fixed values that will save tons of DB requests
2623 $values = array(
2624 'course' => $this->get_courseid());
2625 // Get instance and process log record
2626 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2628 // If we have data, insert it, else something went wrong in the restore_logs_processor
2629 if ($data) {
2630 if (empty($data->url)) {
2631 $data->url = '';
2633 if (empty($data->info)) {
2634 $data->info = '';
2636 // Store the data in the legacy log table if we are still using it.
2637 $manager = get_log_manager();
2638 if (method_exists($manager, 'legacy_add_to_log')) {
2639 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
2640 $data->info, $data->cmid, $data->userid);
2647 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2648 * sharing its same structure but modifying the way records are handled
2650 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2652 protected function process_log($data) {
2653 global $DB;
2655 $data = (object)($data);
2657 $data->time = $this->apply_date_offset($data->time);
2658 $data->userid = $this->get_mappingid('user', $data->userid);
2659 $data->course = $this->get_courseid();
2660 $data->cmid = $this->task->get_moduleid();
2662 // For any reason user wasn't remapped ok, stop processing this
2663 if (empty($data->userid)) {
2664 return;
2667 // Everything ready, let's delegate to the restore_logs_processor
2669 // Set some fixed values that will save tons of DB requests
2670 $values = array(
2671 'course' => $this->get_courseid(),
2672 'course_module' => $this->task->get_moduleid(),
2673 $this->task->get_modulename() => $this->task->get_activityid());
2674 // Get instance and process log record
2675 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2677 // If we have data, insert it, else something went wrong in the restore_logs_processor
2678 if ($data) {
2679 if (empty($data->url)) {
2680 $data->url = '';
2682 if (empty($data->info)) {
2683 $data->info = '';
2685 // Store the data in the legacy log table if we are still using it.
2686 $manager = get_log_manager();
2687 if (method_exists($manager, 'legacy_add_to_log')) {
2688 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
2689 $data->info, $data->cmid, $data->userid);
2697 * Defines the restore step for advanced grading methods attached to the activity module
2699 class restore_activity_grading_structure_step extends restore_structure_step {
2702 * This step is executed only if the grading file is present
2704 protected function execute_condition() {
2706 $fullpath = $this->task->get_taskbasepath();
2707 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2708 if (!file_exists($fullpath)) {
2709 return false;
2712 return true;
2717 * Declares paths in the grading.xml file we are interested in
2719 protected function define_structure() {
2721 $paths = array();
2722 $userinfo = $this->get_setting_value('userinfo');
2724 $area = new restore_path_element('grading_area', '/areas/area');
2725 $paths[] = $area;
2726 // attach local plugin stucture to $area element
2727 $this->add_plugin_structure('local', $area);
2729 $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
2730 $paths[] = $definition;
2731 $this->add_plugin_structure('gradingform', $definition);
2732 // attach local plugin stucture to $definition element
2733 $this->add_plugin_structure('local', $definition);
2736 if ($userinfo) {
2737 $instance = new restore_path_element('grading_instance',
2738 '/areas/area/definitions/definition/instances/instance');
2739 $paths[] = $instance;
2740 $this->add_plugin_structure('gradingform', $instance);
2741 // attach local plugin stucture to $intance element
2742 $this->add_plugin_structure('local', $instance);
2745 return $paths;
2749 * Processes one grading area element
2751 * @param array $data element data
2753 protected function process_grading_area($data) {
2754 global $DB;
2756 $task = $this->get_task();
2757 $data = (object)$data;
2758 $oldid = $data->id;
2759 $data->component = 'mod_'.$task->get_modulename();
2760 $data->contextid = $task->get_contextid();
2762 $newid = $DB->insert_record('grading_areas', $data);
2763 $this->set_mapping('grading_area', $oldid, $newid);
2767 * Processes one grading definition element
2769 * @param array $data element data
2771 protected function process_grading_definition($data) {
2772 global $DB;
2774 $task = $this->get_task();
2775 $data = (object)$data;
2776 $oldid = $data->id;
2777 $data->areaid = $this->get_new_parentid('grading_area');
2778 $data->copiedfromid = null;
2779 $data->timecreated = time();
2780 $data->usercreated = $task->get_userid();
2781 $data->timemodified = $data->timecreated;
2782 $data->usermodified = $data->usercreated;
2784 $newid = $DB->insert_record('grading_definitions', $data);
2785 $this->set_mapping('grading_definition', $oldid, $newid, true);
2789 * Processes one grading form instance element
2791 * @param array $data element data
2793 protected function process_grading_instance($data) {
2794 global $DB;
2796 $data = (object)$data;
2798 // new form definition id
2799 $newformid = $this->get_new_parentid('grading_definition');
2801 // get the name of the area we are restoring to
2802 $sql = "SELECT ga.areaname
2803 FROM {grading_definitions} gd
2804 JOIN {grading_areas} ga ON gd.areaid = ga.id
2805 WHERE gd.id = ?";
2806 $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
2808 // get the mapped itemid - the activity module is expected to define the mappings
2809 // for each gradable area
2810 $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
2812 $oldid = $data->id;
2813 $data->definitionid = $newformid;
2814 $data->raterid = $this->get_mappingid('user', $data->raterid);
2815 $data->itemid = $newitemid;
2817 $newid = $DB->insert_record('grading_instances', $data);
2818 $this->set_mapping('grading_instance', $oldid, $newid);
2822 * Final operations when the database records are inserted
2824 protected function after_execute() {
2825 // Add files embedded into the definition description
2826 $this->add_related_files('grading', 'description', 'grading_definition');
2832 * This structure step restores the grade items associated with one activity
2833 * All the grade items are made child of the "course" grade item but the original
2834 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
2835 * the complete gradebook (categories and calculations), that information is
2836 * available there
2838 class restore_activity_grades_structure_step extends restore_structure_step {
2840 protected function define_structure() {
2842 $paths = array();
2843 $userinfo = $this->get_setting_value('userinfo');
2845 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
2846 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
2847 if ($userinfo) {
2848 $paths[] = new restore_path_element('grade_grade',
2849 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
2851 return $paths;
2854 protected function process_grade_item($data) {
2855 global $DB;
2857 $data = (object)($data);
2858 $oldid = $data->id; // We'll need these later
2859 $oldparentid = $data->categoryid;
2860 $courseid = $this->get_courseid();
2862 // make sure top course category exists, all grade items will be associated
2863 // to it. Later, if restoring the whole gradebook, categories will be introduced
2864 $coursecat = grade_category::fetch_course_category($courseid);
2865 $coursecatid = $coursecat->id; // Get the categoryid to be used
2867 $idnumber = null;
2868 if (!empty($data->idnumber)) {
2869 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
2870 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
2871 // so the best is to keep the ones already in the gradebook
2872 // Potential problem: duplicates if same items are restored more than once. :-(
2873 // This needs to be fixed in some way (outcomes & activities with multiple items)
2874 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
2875 // In any case, verify always for uniqueness
2876 $sql = "SELECT cm.id
2877 FROM {course_modules} cm
2878 WHERE cm.course = :courseid AND
2879 cm.idnumber = :idnumber AND
2880 cm.id <> :cmid";
2881 $params = array(
2882 'courseid' => $courseid,
2883 'idnumber' => $data->idnumber,
2884 'cmid' => $this->task->get_moduleid()
2886 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
2887 $idnumber = $data->idnumber;
2891 unset($data->id);
2892 $data->categoryid = $coursecatid;
2893 $data->courseid = $this->get_courseid();
2894 $data->iteminstance = $this->task->get_activityid();
2895 $data->idnumber = $idnumber;
2896 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
2897 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
2898 $data->timecreated = $this->apply_date_offset($data->timecreated);
2899 $data->timemodified = $this->apply_date_offset($data->timemodified);
2901 $gradeitem = new grade_item($data, false);
2902 $gradeitem->insert('restore');
2904 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
2905 $gradeitem->sortorder = $data->sortorder;
2906 $gradeitem->update('restore');
2908 // Set mapping, saving the original category id into parentitemid
2909 // gradebook restore (final task) will need it to reorganise items
2910 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
2913 protected function process_grade_grade($data) {
2914 $data = (object)($data);
2915 $olduserid = $data->userid;
2916 unset($data->id);
2918 $data->itemid = $this->get_new_parentid('grade_item');
2920 $data->userid = $this->get_mappingid('user', $data->userid, null);
2921 if (!empty($data->userid)) {
2922 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
2923 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
2924 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
2925 $data->overridden = $this->apply_date_offset($data->overridden);
2927 $grade = new grade_grade($data, false);
2928 $grade->insert('restore');
2929 // no need to save any grade_grade mapping
2930 } else {
2931 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
2936 * process activity grade_letters. Note that, while these are possible,
2937 * because grade_letters are contextid based, in practice, only course
2938 * context letters can be defined. So we keep here this method knowing
2939 * it won't be executed ever. gradebook restore will restore course letters.
2941 protected function process_grade_letter($data) {
2942 global $DB;
2944 $data['contextid'] = $this->task->get_contextid();
2945 $gradeletter = (object)$data;
2947 // Check if it exists before adding it
2948 unset($data['id']);
2949 if (!$DB->record_exists('grade_letters', $data)) {
2950 $newitemid = $DB->insert_record('grade_letters', $gradeletter);
2952 // no need to save any grade_letter mapping
2955 public function after_restore() {
2956 // Fix grade item's sortorder after restore, as it might have duplicates.
2957 $courseid = $this->get_task()->get_courseid();
2958 grade_item::fix_duplicate_sortorder($courseid);
2964 * This structure steps restores one instance + positions of one block
2965 * Note: Positions corresponding to one existing context are restored
2966 * here, but all the ones having unknown contexts are sent to backup_ids
2967 * for a later chance to be restored at the end (final task)
2969 class restore_block_instance_structure_step extends restore_structure_step {
2971 protected function define_structure() {
2973 $paths = array();
2975 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
2976 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
2978 return $paths;
2981 public function process_block($data) {
2982 global $DB, $CFG;
2984 $data = (object)$data; // Handy
2985 $oldcontextid = $data->contextid;
2986 $oldid = $data->id;
2987 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
2989 // Look for the parent contextid
2990 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
2991 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
2994 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
2995 // If there is already one block of that type in the parent context
2996 // and the block is not multiple, stop processing
2997 // Use blockslib loader / method executor
2998 if (!$bi = block_instance($data->blockname)) {
2999 return false;
3002 if (!$bi->instance_allow_multiple()) {
3003 if ($DB->record_exists_sql("SELECT bi.id
3004 FROM {block_instances} bi
3005 JOIN {block} b ON b.name = bi.blockname
3006 WHERE bi.parentcontextid = ?
3007 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
3008 return false;
3012 // If there is already one block of that type in the parent context
3013 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
3014 // stop processing
3015 $params = array(
3016 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
3017 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
3018 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
3019 if ($birecs = $DB->get_records('block_instances', $params)) {
3020 foreach($birecs as $birec) {
3021 if ($birec->configdata == $data->configdata) {
3022 return false;
3027 // Set task old contextid, blockid and blockname once we know them
3028 $this->task->set_old_contextid($oldcontextid);
3029 $this->task->set_old_blockid($oldid);
3030 $this->task->set_blockname($data->blockname);
3032 // Let's look for anything within configdata neededing processing
3033 // (nulls and uses of legacy file.php)
3034 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
3035 $configdata = (array)unserialize(base64_decode($data->configdata));
3036 foreach ($configdata as $attribute => $value) {
3037 if (in_array($attribute, $attrstotransform)) {
3038 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
3041 $data->configdata = base64_encode(serialize((object)$configdata));
3044 // Create the block instance
3045 $newitemid = $DB->insert_record('block_instances', $data);
3046 // Save the mapping (with restorefiles support)
3047 $this->set_mapping('block_instance', $oldid, $newitemid, true);
3048 // Create the block context
3049 $newcontextid = context_block::instance($newitemid)->id;
3050 // Save the block contexts mapping and sent it to task
3051 $this->set_mapping('context', $oldcontextid, $newcontextid);
3052 $this->task->set_contextid($newcontextid);
3053 $this->task->set_blockid($newitemid);
3055 // Restore block fileareas if declared
3056 $component = 'block_' . $this->task->get_blockname();
3057 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
3058 $this->add_related_files($component, $filearea, null);
3061 // Process block positions, creating them or accumulating for final step
3062 foreach($positions as $position) {
3063 $position = (object)$position;
3064 $position->blockinstanceid = $newitemid; // The instance is always the restored one
3065 // If position is for one already mapped (known) contextid
3066 // process it now, creating the position
3067 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
3068 $position->contextid = $newpositionctxid;
3069 // Create the block position
3070 $DB->insert_record('block_positions', $position);
3072 // The position belongs to an unknown context, send it to backup_ids
3073 // to process them as part of the final steps of restore. We send the
3074 // whole $position object there, hence use the low level method.
3075 } else {
3076 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
3083 * Structure step to restore common course_module information
3085 * This step will process the module.xml file for one activity, in order to restore
3086 * the corresponding information to the course_modules table, skipping various bits
3087 * of information based on CFG settings (groupings, completion...) in order to fullfill
3088 * all the reqs to be able to create the context to be used by all the rest of steps
3089 * in the activity restore task
3091 class restore_module_structure_step extends restore_structure_step {
3093 protected function define_structure() {
3094 global $CFG;
3096 $paths = array();
3098 $module = new restore_path_element('module', '/module');
3099 $paths[] = $module;
3100 if ($CFG->enableavailability) {
3101 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
3102 $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
3105 // Apply for 'format' plugins optional paths at module level
3106 $this->add_plugin_structure('format', $module);
3108 // Apply for 'plagiarism' plugins optional paths at module level
3109 $this->add_plugin_structure('plagiarism', $module);
3111 // Apply for 'local' plugins optional paths at module level
3112 $this->add_plugin_structure('local', $module);
3114 return $paths;
3117 protected function process_module($data) {
3118 global $CFG, $DB;
3120 $data = (object)$data;
3121 $oldid = $data->id;
3122 $this->task->set_old_moduleversion($data->version);
3124 $data->course = $this->task->get_courseid();
3125 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
3126 // Map section (first try by course_section mapping match. Useful in course and section restores)
3127 $data->section = $this->get_mappingid('course_section', $data->sectionid);
3128 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
3129 $params = array(
3130 'course' => $this->get_courseid(),
3131 'section' => $data->sectionnumber);
3132 $data->section = $DB->get_field('course_sections', 'id', $params);
3134 if (!$data->section) { // sectionnumber failed, try to get first section in course
3135 $params = array(
3136 'course' => $this->get_courseid());
3137 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
3139 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
3140 $sectionrec = array(
3141 'course' => $this->get_courseid(),
3142 'section' => 0);
3143 $DB->insert_record('course_sections', $sectionrec); // section 0
3144 $sectionrec = array(
3145 'course' => $this->get_courseid(),
3146 'section' => 1);
3147 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
3149 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
3150 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
3151 $data->idnumber = '';
3153 if (empty($CFG->enablecompletion)) { // completion
3154 $data->completion = 0;
3155 $data->completiongradeitemnumber = null;
3156 $data->completionview = 0;
3157 $data->completionexpected = 0;
3158 } else {
3159 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
3161 if (empty($CFG->enableavailability)) {
3162 $data->availability = null;
3164 // Backups that did not include showdescription, set it to default 0
3165 // (this is not totally necessary as it has a db default, but just to
3166 // be explicit).
3167 if (!isset($data->showdescription)) {
3168 $data->showdescription = 0;
3170 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
3172 // If there are legacy availablility data fields (and no new format data),
3173 // convert the old fields.
3174 if (empty($data->availability)) {
3175 // If groupmembersonly is disabled on this system, convert the
3176 // groupmembersonly option into the new API. Otherwise don't.
3177 $data->availability = \core_availability\info::convert_legacy_fields(
3178 $data, false, !$CFG->enablegroupmembersonly);
3181 // course_module record ready, insert it
3182 $newitemid = $DB->insert_record('course_modules', $data);
3183 // save mapping
3184 $this->set_mapping('course_module', $oldid, $newitemid);
3185 // set the new course_module id in the task
3186 $this->task->set_moduleid($newitemid);
3187 // we can now create the context safely
3188 $ctxid = context_module::instance($newitemid)->id;
3189 // set the new context id in the task
3190 $this->task->set_contextid($ctxid);
3191 // update sequence field in course_section
3192 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
3193 $sequence .= ',' . $newitemid;
3194 } else {
3195 $sequence = $newitemid;
3197 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
3199 // If there is the legacy showavailability data, store this for later use.
3200 // (This data is not present when restoring 'new' backups.)
3201 if (isset($data->showavailability)) {
3202 // Cache the showavailability flag using the backup_ids data field.
3203 restore_dbops::set_backup_ids_record($this->get_restoreid(),
3204 'module_showavailability', $newitemid, 0, null,
3205 (object)array('showavailability' => $data->showavailability));
3210 * Process the legacy availability table record. This table does not exist
3211 * in Moodle 2.7+ but we still support restore.
3213 * @param stdClass $data Record data
3215 protected function process_availability($data) {
3216 $data = (object)$data;
3217 // Simply going to store the whole availability record now, we'll process
3218 // all them later in the final task (once all activities have been restored)
3219 // Let's call the low level one to be able to store the whole object
3220 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
3221 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
3225 * Process the legacy availability fields table record. This table does not
3226 * exist in Moodle 2.7+ but we still support restore.
3228 * @param stdClass $data Record data
3230 protected function process_availability_field($data) {
3231 global $DB;
3232 $data = (object)$data;
3233 // Mark it is as passed by default
3234 $passed = true;
3235 $customfieldid = null;
3237 // If a customfield has been used in order to pass we must be able to match an existing
3238 // customfield by name (data->customfield) and type (data->customfieldtype)
3239 if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
3240 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
3241 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
3242 $passed = false;
3243 } else if (!empty($data->customfield)) {
3244 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
3245 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
3246 $passed = ($customfieldid !== false);
3249 if ($passed) {
3250 // Create the object to insert into the database
3251 $availfield = new stdClass();
3252 $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
3253 $availfield->userfield = $data->userfield;
3254 $availfield->customfieldid = $customfieldid;
3255 $availfield->operator = $data->operator;
3256 $availfield->value = $data->value;
3258 // Get showavailability option.
3259 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
3260 'module_showavailability', $availfield->coursemoduleid);
3261 if (!$showrec) {
3262 // Should not happen.
3263 throw new coding_exception('No matching showavailability record');
3265 $show = $showrec->info->showavailability;
3267 // The $availfieldobject is now in the format used in the old
3268 // system. Interpret this and convert to new system.
3269 $currentvalue = $DB->get_field('course_modules', 'availability',
3270 array('id' => $availfield->coursemoduleid), MUST_EXIST);
3271 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
3272 $currentvalue, $availfield, $show);
3273 $DB->set_field('course_modules', 'availability', $newvalue,
3274 array('id' => $availfield->coursemoduleid));
3280 * Structure step that will process the user activity completion
3281 * information if all these conditions are met:
3282 * - Target site has completion enabled ($CFG->enablecompletion)
3283 * - Activity includes completion info (file_exists)
3285 class restore_userscompletion_structure_step extends restore_structure_step {
3287 * To conditionally decide if this step must be executed
3288 * Note the "settings" conditions are evaluated in the
3289 * corresponding task. Here we check for other conditions
3290 * not being restore settings (files, site settings...)
3292 protected function execute_condition() {
3293 global $CFG;
3295 // Completion disabled in this site, don't execute
3296 if (empty($CFG->enablecompletion)) {
3297 return false;
3300 // No user completion info found, don't execute
3301 $fullpath = $this->task->get_taskbasepath();
3302 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3303 if (!file_exists($fullpath)) {
3304 return false;
3307 // Arrived here, execute the step
3308 return true;
3311 protected function define_structure() {
3313 $paths = array();
3315 $paths[] = new restore_path_element('completion', '/completions/completion');
3317 return $paths;
3320 protected function process_completion($data) {
3321 global $DB;
3323 $data = (object)$data;
3325 $data->coursemoduleid = $this->task->get_moduleid();
3326 $data->userid = $this->get_mappingid('user', $data->userid);
3327 $data->timemodified = $this->apply_date_offset($data->timemodified);
3329 // Find the existing record
3330 $existing = $DB->get_record('course_modules_completion', array(
3331 'coursemoduleid' => $data->coursemoduleid,
3332 'userid' => $data->userid), 'id, timemodified');
3333 // Check we didn't already insert one for this cmid and userid
3334 // (there aren't supposed to be duplicates in that field, but
3335 // it was possible until MDL-28021 was fixed).
3336 if ($existing) {
3337 // Update it to these new values, but only if the time is newer
3338 if ($existing->timemodified < $data->timemodified) {
3339 $data->id = $existing->id;
3340 $DB->update_record('course_modules_completion', $data);
3342 } else {
3343 // Normal entry where it doesn't exist already
3344 $DB->insert_record('course_modules_completion', $data);
3350 * Abstract structure step, parent of all the activity structure steps. Used to suuport
3351 * the main <activity ...> tag and process it. Also provides subplugin support for
3352 * activities.
3354 abstract class restore_activity_structure_step extends restore_structure_step {
3356 protected function add_subplugin_structure($subplugintype, $element) {
3358 global $CFG;
3360 // Check the requested subplugintype is a valid one
3361 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
3362 if (!file_exists($subpluginsfile)) {
3363 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
3365 include($subpluginsfile);
3366 if (!array_key_exists($subplugintype, $subplugins)) {
3367 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
3369 // Get all the restore path elements, looking across all the subplugin dirs
3370 $subpluginsdirs = core_component::get_plugin_list($subplugintype);
3371 foreach ($subpluginsdirs as $name => $subpluginsdir) {
3372 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
3373 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
3374 if (file_exists($restorefile)) {
3375 require_once($restorefile);
3376 $restoresubplugin = new $classname($subplugintype, $name, $this);
3377 // Add subplugin paths to the step
3378 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
3384 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
3385 * have the parent task available for wrapping purposes (get course/context....)
3386 * @return restore_task
3388 public function get_task() {
3389 return $this->task;
3393 * Adds support for the 'activity' path that is common to all the activities
3394 * and will be processed globally here
3396 protected function prepare_activity_structure($paths) {
3398 $paths[] = new restore_path_element('activity', '/activity');
3400 return $paths;
3404 * Process the activity path, informing the task about various ids, needed later
3406 protected function process_activity($data) {
3407 $data = (object)$data;
3408 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
3409 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
3410 $this->task->set_old_activityid($data->id); // Save old activityid in task
3414 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
3415 * and will adjust the new activity id (the instance) in various places
3417 protected function apply_activity_instance($newitemid) {
3418 global $DB;
3420 $this->task->set_activityid($newitemid); // Save activity id in task
3421 // Apply the id to course_sections->instanceid
3422 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
3423 // Do the mapping for modulename, preparing it for files by oldcontext
3424 $modulename = $this->task->get_modulename();
3425 $oldid = $this->task->get_old_activityid();
3426 $this->set_mapping($modulename, $oldid, $newitemid, true);
3431 * Structure step in charge of creating/mapping all the qcats and qs
3432 * by parsing the questions.xml file and checking it against the
3433 * results calculated by {@link restore_process_categories_and_questions}
3434 * and stored in backup_ids_temp
3436 class restore_create_categories_and_questions extends restore_structure_step {
3438 /** @var array $cachecategory store a question category */
3439 protected $cachedcategory = null;
3441 protected function define_structure() {
3443 $category = new restore_path_element('question_category', '/question_categories/question_category');
3444 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
3445 $hint = new restore_path_element('question_hint',
3446 '/question_categories/question_category/questions/question/question_hints/question_hint');
3448 $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag');
3450 // Apply for 'qtype' plugins optional paths at question level
3451 $this->add_plugin_structure('qtype', $question);
3453 // Apply for 'local' plugins optional paths at question level
3454 $this->add_plugin_structure('local', $question);
3456 return array($category, $question, $hint, $tag);
3459 protected function process_question_category($data) {
3460 global $DB;
3462 $data = (object)$data;
3463 $oldid = $data->id;
3465 // Check we have one mapping for this category
3466 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
3467 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
3470 // Check we have to create the category (newitemid = 0)
3471 if ($mapping->newitemid) {
3472 return; // newitemid != 0, this category is going to be mapped. Nothing to do
3475 // Arrived here, newitemid = 0, we need to create the category
3476 // we'll do it at parentitemid context, but for CONTEXT_MODULE
3477 // categories, that will be created at CONTEXT_COURSE and moved
3478 // to module context later when the activity is created
3479 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
3480 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
3482 $data->contextid = $mapping->parentitemid;
3484 // Let's create the question_category and save mapping
3485 $newitemid = $DB->insert_record('question_categories', $data);
3486 $this->set_mapping('question_category', $oldid, $newitemid);
3487 // Also annotate them as question_category_created, we need
3488 // that later when remapping parents
3489 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
3492 protected function process_question($data) {
3493 global $DB;
3495 $data = (object)$data;
3496 $oldid = $data->id;
3498 // Check we have one mapping for this question
3499 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
3500 return; // No mapping = this question doesn't need to be created/mapped
3503 // Get the mapped category (cannot use get_new_parentid() because not
3504 // all the categories have been created, so it is not always available
3505 // Instead we get the mapping for the question->parentitemid because
3506 // we have loaded qcatids there for all parsed questions
3507 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
3509 // In the past, there were some very sloppy values of penalty. Fix them.
3510 if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
3511 $data->penalty = 0.3333333;
3513 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
3514 $data->penalty = 0.6666667;
3516 if ($data->penalty >= 1) {
3517 $data->penalty = 1;
3520 $userid = $this->get_mappingid('user', $data->createdby);
3521 $data->createdby = $userid ? $userid : $this->task->get_userid();
3523 $userid = $this->get_mappingid('user', $data->modifiedby);
3524 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
3526 // With newitemid = 0, let's create the question
3527 if (!$questionmapping->newitemid) {
3528 $newitemid = $DB->insert_record('question', $data);
3529 $this->set_mapping('question', $oldid, $newitemid);
3530 // Also annotate them as question_created, we need
3531 // that later when remapping parents (keeping the old categoryid as parentid)
3532 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
3533 } else {
3534 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
3535 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
3536 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
3539 // Note, we don't restore any question files yet
3540 // as far as the CONTEXT_MODULE categories still
3541 // haven't their contexts to be restored to
3542 // The {@link restore_create_question_files}, executed in the final step
3543 // step will be in charge of restoring all the question files
3546 protected function process_question_hint($data) {
3547 global $DB;
3549 $data = (object)$data;
3550 $oldid = $data->id;
3552 // Detect if the question is created or mapped
3553 $oldquestionid = $this->get_old_parentid('question');
3554 $newquestionid = $this->get_new_parentid('question');
3555 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
3557 // If the question has been created by restore, we need to create its question_answers too
3558 if ($questioncreated) {
3559 // Adjust some columns
3560 $data->questionid = $newquestionid;
3561 // Insert record
3562 $newitemid = $DB->insert_record('question_hints', $data);
3564 // The question existed, we need to map the existing question_hints
3565 } else {
3566 // Look in question_hints by hint text matching
3567 $sql = 'SELECT id
3568 FROM {question_hints}
3569 WHERE questionid = ?
3570 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
3571 $params = array($newquestionid, $data->hint);
3572 $newitemid = $DB->get_field_sql($sql, $params);
3574 // Not able to find the hint, let's try cleaning the hint text
3575 // of all the question's hints in DB as slower fallback. MDL-33863.
3576 if (!$newitemid) {
3577 $potentialhints = $DB->get_records('question_hints',
3578 array('questionid' => $newquestionid), '', 'id, hint');
3579 foreach ($potentialhints as $potentialhint) {
3580 // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
3581 $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
3582 $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
3583 if ($cleanhint === $data->hint) {
3584 $newitemid = $data->id;
3589 // If we haven't found the newitemid, something has gone really wrong, question in DB
3590 // is missing hints, exception
3591 if (!$newitemid) {
3592 $info = new stdClass();
3593 $info->filequestionid = $oldquestionid;
3594 $info->dbquestionid = $newquestionid;
3595 $info->hint = $data->hint;
3596 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
3599 // Create mapping (I'm not sure if this is really needed?)
3600 $this->set_mapping('question_hint', $oldid, $newitemid);
3603 protected function process_tag($data) {
3604 global $CFG, $DB;
3606 $data = (object)$data;
3607 $newquestion = $this->get_new_parentid('question');
3609 if (!empty($CFG->usetags)) { // if enabled in server
3610 // TODO: This is highly inefficient. Each time we add one tag
3611 // we fetch all the existing because tag_set() deletes them
3612 // so everything must be reinserted on each call
3613 $tags = array();
3614 $existingtags = tag_get_tags('question', $newquestion);
3615 // Re-add all the existitng tags
3616 foreach ($existingtags as $existingtag) {
3617 $tags[] = $existingtag->rawname;
3619 // Add the one being restored
3620 $tags[] = $data->rawname;
3621 // Get the category, so we can then later get the context.
3622 $categoryid = $this->get_new_parentid('question_category');
3623 if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
3624 $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
3626 // Send all the tags back to the question
3627 tag_set('question', $newquestion, $tags, 'core_question', $this->cachedcategory->contextid);
3631 protected function after_execute() {
3632 global $DB;
3634 // First of all, recode all the created question_categories->parent fields
3635 $qcats = $DB->get_records('backup_ids_temp', array(
3636 'backupid' => $this->get_restoreid(),
3637 'itemname' => 'question_category_created'));
3638 foreach ($qcats as $qcat) {
3639 $newparent = 0;
3640 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
3641 // Get new parent (mapped or created, so we look in quesiton_category mappings)
3642 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
3643 'backupid' => $this->get_restoreid(),
3644 'itemname' => 'question_category',
3645 'itemid' => $dbcat->parent))) {
3646 // contextids must match always, as far as we always include complete qbanks, just check it
3647 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
3648 if ($dbcat->contextid == $newparentctxid) {
3649 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
3650 } else {
3651 $newparent = 0; // No ctx match for both cats, no parent relationship
3654 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
3655 if (!$newparent) {
3656 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
3660 // Now, recode all the created question->parent fields
3661 $qs = $DB->get_records('backup_ids_temp', array(
3662 'backupid' => $this->get_restoreid(),
3663 'itemname' => 'question_created'));
3664 foreach ($qs as $q) {
3665 $newparent = 0;
3666 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
3667 // Get new parent (mapped or created, so we look in question mappings)
3668 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
3669 'backupid' => $this->get_restoreid(),
3670 'itemname' => 'question',
3671 'itemid' => $dbq->parent))) {
3672 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
3676 // Note, we don't restore any question files yet
3677 // as far as the CONTEXT_MODULE categories still
3678 // haven't their contexts to be restored to
3679 // The {@link restore_create_question_files}, executed in the final step
3680 // step will be in charge of restoring all the question files
3685 * Execution step that will move all the CONTEXT_MODULE question categories
3686 * created at early stages of restore in course context (because modules weren't
3687 * created yet) to their target module (matching by old-new-contextid mapping)
3689 class restore_move_module_questions_categories extends restore_execution_step {
3691 protected function define_execution() {
3692 global $DB;
3694 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
3695 foreach ($contexts as $contextid => $contextlevel) {
3696 // Only if context mapping exists (i.e. the module has been restored)
3697 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
3698 // Update all the qcats having their parentitemid set to the original contextid
3699 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
3700 FROM {backup_ids_temp}
3701 WHERE backupid = ?
3702 AND itemname = 'question_category'
3703 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
3704 foreach ($modulecats as $modulecat) {
3705 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
3706 // And set new contextid also in question_category mapping (will be
3707 // used by {@link restore_create_question_files} later
3708 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
3716 * Execution step that will create all the question/answers/qtype-specific files for the restored
3717 * questions. It must be executed after {@link restore_move_module_questions_categories}
3718 * because only then each question is in its final category and only then the
3719 * contexts can be determined.
3721 class restore_create_question_files extends restore_execution_step {
3723 /** @var array Question-type specific component items cache. */
3724 private $qtypecomponentscache = array();
3727 * Preform the restore_create_question_files step.
3729 protected function define_execution() {
3730 global $DB;
3732 // Track progress, as this task can take a long time.
3733 $progress = $this->task->get_progress();
3734 $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
3736 // Parentitemids of question_createds in backup_ids_temp are the category it is in.
3737 // MUST use a recordset, as there is no unique key in the first (or any) column.
3738 $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
3739 FROM {backup_ids_temp} bi
3740 JOIN {question} q ON q.id = bi.newitemid
3741 WHERE bi.backupid = ?
3742 AND bi.itemname = 'question_created'
3743 ORDER BY categoryid ASC", array($this->get_restoreid()));
3745 $currentcatid = -1;
3746 foreach ($catqtypes as $categoryid => $row) {
3747 $qtype = $row->qtype;
3749 // Check if we are in a new category.
3750 if ($currentcatid !== $categoryid) {
3751 // Report progress for each category.
3752 $progress->progress();
3754 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
3755 'question_category', $categoryid)) {
3756 // Something went really wrong, cannot find the question_category for the question_created records.
3757 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
3758 continue;
3761 // Calculate source and target contexts.
3762 $oldctxid = $qcatmapping->info->contextid;
3763 $newctxid = $qcatmapping->parentitemid;
3765 $this->send_common_files($oldctxid, $newctxid, $progress);
3766 $currentcatid = $categoryid;
3769 $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
3771 $catqtypes->close();
3772 $progress->end_progress();
3776 * Send the common question files to a new context.
3778 * @param int $oldctxid Old context id.
3779 * @param int $newctxid New context id.
3780 * @param \core\progress $progress Progress object to use.
3782 private function send_common_files($oldctxid, $newctxid, $progress) {
3783 // Add common question files (question and question_answer ones).
3784 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
3785 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3786 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
3787 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3788 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
3789 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
3790 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
3791 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
3792 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
3793 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
3794 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
3795 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3796 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
3797 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3798 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
3799 $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
3803 * Send the question type specific files to a new context.
3805 * @param text $qtype The qtype name to send.
3806 * @param int $oldctxid Old context id.
3807 * @param int $newctxid New context id.
3808 * @param \core\progress $progress Progress object to use.
3810 private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
3811 if (!isset($this->qtypecomponentscache[$qtype])) {
3812 $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
3814 $components = $this->qtypecomponentscache[$qtype];
3815 foreach ($components as $component => $fileareas) {
3816 foreach ($fileareas as $filearea => $mapping) {
3817 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
3818 $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
3825 * Try to restore aliases and references to external files.
3827 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
3828 * We expect that all regular (non-alias) files have already been restored. Make sure
3829 * there is no restore step executed after this one that would call send_files_to_pool() again.
3831 * You may notice we have hardcoded support for Server files, Legacy course files
3832 * and user Private files here at the moment. This could be eventually replaced with a set of
3833 * callbacks in the future if needed.
3835 * @copyright 2012 David Mudrak <david@moodle.com>
3836 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3838 class restore_process_file_aliases_queue extends restore_execution_step {
3840 /** @var array internal cache for {@link choose_repository()} */
3841 private $cachereposbyid = array();
3843 /** @var array internal cache for {@link choose_repository()} */
3844 private $cachereposbytype = array();
3847 * What to do when this step is executed.
3849 protected function define_execution() {
3850 global $DB;
3852 $this->log('processing file aliases queue', backup::LOG_DEBUG);
3854 $fs = get_file_storage();
3856 // Load the queue.
3857 $rs = $DB->get_recordset('backup_ids_temp',
3858 array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'),
3859 '', 'info');
3861 // Iterate over aliases in the queue.
3862 foreach ($rs as $record) {
3863 $info = backup_controller_dbops::decode_backup_temp_info($record->info);
3865 // Try to pick a repository instance that should serve the alias.
3866 $repository = $this->choose_repository($info);
3868 if (is_null($repository)) {
3869 $this->notify_failure($info, 'unable to find a matching repository instance');
3870 continue;
3873 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
3874 // Aliases to Server files and Legacy course files may refer to a file
3875 // contained in the backup file or to some existing file (if we are on the
3876 // same site).
3877 try {
3878 $reference = file_storage::unpack_reference($info->oldfile->reference);
3879 } catch (Exception $e) {
3880 $this->notify_failure($info, 'invalid reference field format');
3881 continue;
3884 // Let's see if the referred source file was also included in the backup.
3885 $candidates = $DB->get_recordset('backup_files_temp', array(
3886 'backupid' => $this->get_restoreid(),
3887 'contextid' => $reference['contextid'],
3888 'component' => $reference['component'],
3889 'filearea' => $reference['filearea'],
3890 'itemid' => $reference['itemid'],
3891 ), '', 'info, newcontextid, newitemid');
3893 $source = null;
3895 foreach ($candidates as $candidate) {
3896 $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
3897 if ($candidateinfo->filename === $reference['filename']
3898 and $candidateinfo->filepath === $reference['filepath']
3899 and !is_null($candidate->newcontextid)
3900 and !is_null($candidate->newitemid) ) {
3901 $source = $candidateinfo;
3902 $source->contextid = $candidate->newcontextid;
3903 $source->itemid = $candidate->newitemid;
3904 break;
3907 $candidates->close();
3909 if ($source) {
3910 // We have an alias that refers to another file also included in
3911 // the backup. Let us change the reference field so that it refers
3912 // to the restored copy of the original file.
3913 $reference = file_storage::pack_reference($source);
3915 // Send the new alias to the filepool.
3916 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
3917 $this->notify_success($info);
3918 continue;
3920 } else {
3921 // This is a reference to some moodle file that was not contained in the backup
3922 // file. If we are restoring to the same site, keep the reference untouched
3923 // and restore the alias as is if the referenced file exists.
3924 if ($this->task->is_samesite()) {
3925 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
3926 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
3927 $reference = file_storage::pack_reference($reference);
3928 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
3929 $this->notify_success($info);
3930 continue;
3931 } else {
3932 $this->notify_failure($info, 'referenced file not found');
3933 continue;
3936 // If we are at other site, we can't restore this alias.
3937 } else {
3938 $this->notify_failure($info, 'referenced file not included');
3939 continue;
3943 } else if ($info->oldfile->repositorytype === 'user') {
3944 if ($this->task->is_samesite()) {
3945 // For aliases to user Private files at the same site, we have a chance to check
3946 // if the referenced file still exists.
3947 try {
3948 $reference = file_storage::unpack_reference($info->oldfile->reference);
3949 } catch (Exception $e) {
3950 $this->notify_failure($info, 'invalid reference field format');
3951 continue;
3953 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
3954 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
3955 $reference = file_storage::pack_reference($reference);
3956 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
3957 $this->notify_success($info);
3958 continue;
3959 } else {
3960 $this->notify_failure($info, 'referenced file not found');
3961 continue;
3964 // If we are at other site, we can't restore this alias.
3965 } else {
3966 $this->notify_failure($info, 'restoring at another site');
3967 continue;
3970 } else {
3971 // This is a reference to some external file such as in boxnet or dropbox.
3972 // If we are restoring to the same site, keep the reference untouched and
3973 // restore the alias as is.
3974 if ($this->task->is_samesite()) {
3975 $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
3976 $this->notify_success($info);
3977 continue;
3979 // If we are at other site, we can't restore this alias.
3980 } else {
3981 $this->notify_failure($info, 'restoring at another site');
3982 continue;
3986 $rs->close();
3990 * Choose the repository instance that should handle the alias.
3992 * At the same site, we can rely on repository instance id and we just
3993 * check it still exists. On other site, try to find matching Server files or
3994 * Legacy course files repository instance. Return null if no matching
3995 * repository instance can be found.
3997 * @param stdClass $info
3998 * @return repository|null
4000 private function choose_repository(stdClass $info) {
4001 global $DB, $CFG;
4002 require_once($CFG->dirroot.'/repository/lib.php');
4004 if ($this->task->is_samesite()) {
4005 // We can rely on repository instance id.
4007 if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
4008 return $this->cachereposbyid[$info->oldfile->repositoryid];
4011 $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
4013 try {
4014 $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
4015 return $this->cachereposbyid[$info->oldfile->repositoryid];
4016 } catch (Exception $e) {
4017 $this->cachereposbyid[$info->oldfile->repositoryid] = null;
4018 return null;
4021 } else {
4022 // We can rely on repository type only.
4024 if (empty($info->oldfile->repositorytype)) {
4025 return null;
4028 if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
4029 return $this->cachereposbytype[$info->oldfile->repositorytype];
4032 $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
4034 // Both Server files and Legacy course files repositories have a single
4035 // instance at the system context to use. Let us try to find it.
4036 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
4037 $sql = "SELECT ri.id
4038 FROM {repository} r
4039 JOIN {repository_instances} ri ON ri.typeid = r.id
4040 WHERE r.type = ? AND ri.contextid = ?";
4041 $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
4042 if (empty($ris)) {
4043 return null;
4045 $repoids = array_keys($ris);
4046 $repoid = reset($repoids);
4047 try {
4048 $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
4049 return $this->cachereposbytype[$info->oldfile->repositorytype];
4050 } catch (Exception $e) {
4051 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
4052 return null;
4056 $this->cachereposbytype[$info->oldfile->repositorytype] = null;
4057 return null;
4062 * Let the user know that the given alias was successfully restored
4064 * @param stdClass $info
4066 private function notify_success(stdClass $info) {
4067 $filedesc = $this->describe_alias($info);
4068 $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
4072 * Let the user know that the given alias can't be restored
4074 * @param stdClass $info
4075 * @param string $reason detailed reason to be logged
4077 private function notify_failure(stdClass $info, $reason = '') {
4078 $filedesc = $this->describe_alias($info);
4079 if ($reason) {
4080 $reason = ' ('.$reason.')';
4082 $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
4083 $this->add_result_item('file_aliases_restore_failures', $filedesc);
4087 * Return a human readable description of the alias file
4089 * @param stdClass $info
4090 * @return string
4092 private function describe_alias(stdClass $info) {
4094 $filedesc = $this->expected_alias_location($info->newfile);
4096 if (!is_null($info->oldfile->source)) {
4097 $filedesc .= ' ('.$info->oldfile->source.')';
4100 return $filedesc;
4104 * Return the expected location of a file
4106 * Please note this may and may not work as a part of URL to pluginfile.php
4107 * (depends on how the given component/filearea deals with the itemid).
4109 * @param stdClass $filerecord
4110 * @return string
4112 private function expected_alias_location($filerecord) {
4114 $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
4115 if (!is_null($filerecord->itemid)) {
4116 $filedesc .= '/'.$filerecord->itemid;
4118 $filedesc .= $filerecord->filepath.$filerecord->filename;
4120 return $filedesc;
4124 * Append a value to the given resultset
4126 * @param string $name name of the result containing a list of values
4127 * @param mixed $value value to add as another item in that result
4129 private function add_result_item($name, $value) {
4131 $results = $this->task->get_results();
4133 if (isset($results[$name])) {
4134 if (!is_array($results[$name])) {
4135 throw new coding_exception('Unable to append a result item into a non-array structure.');
4137 $current = $results[$name];
4138 $current[] = $value;
4139 $this->task->add_result(array($name => $current));
4141 } else {
4142 $this->task->add_result(array($name => array($value)));
4149 * Abstract structure step, to be used by all the activities using core questions stuff
4150 * (like the quiz module), to support qtype plugins, states and sessions
4152 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
4153 /** @var array question_attempt->id to qtype. */
4154 protected $qtypes = array();
4155 /** @var array question_attempt->id to questionid. */
4156 protected $newquestionids = array();
4159 * Attach below $element (usually attempts) the needed restore_path_elements
4160 * to restore question_usages and all they contain.
4162 * If you use the $nameprefix parameter, then you will need to implement some
4163 * extra methods in your class, like
4165 * protected function process_{nameprefix}question_attempt($data) {
4166 * $this->restore_question_usage_worker($data, '{nameprefix}');
4168 * protected function process_{nameprefix}question_attempt($data) {
4169 * $this->restore_question_attempt_worker($data, '{nameprefix}');
4171 * protected function process_{nameprefix}question_attempt_step($data) {
4172 * $this->restore_question_attempt_step_worker($data, '{nameprefix}');
4175 * @param restore_path_element $element the parent element that the usages are stored inside.
4176 * @param array $paths the paths array that is being built.
4177 * @param string $nameprefix should match the prefix passed to the corresponding
4178 * backup_questions_activity_structure_step::add_question_usages call.
4180 protected function add_question_usages($element, &$paths, $nameprefix = '') {
4181 // Check $element is restore_path_element
4182 if (! $element instanceof restore_path_element) {
4183 throw new restore_step_exception('element_must_be_restore_path_element', $element);
4186 // Check $paths is one array
4187 if (!is_array($paths)) {
4188 throw new restore_step_exception('paths_must_be_array', $paths);
4190 $paths[] = new restore_path_element($nameprefix . 'question_usage',
4191 $element->get_path() . "/{$nameprefix}question_usage");
4192 $paths[] = new restore_path_element($nameprefix . 'question_attempt',
4193 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
4194 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
4195 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
4196 true);
4197 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
4198 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
4202 * Process question_usages
4204 protected function process_question_usage($data) {
4205 $this->restore_question_usage_worker($data, '');
4209 * Process question_attempts
4211 protected function process_question_attempt($data) {
4212 $this->restore_question_attempt_worker($data, '');
4216 * Process question_attempt_steps
4218 protected function process_question_attempt_step($data) {
4219 $this->restore_question_attempt_step_worker($data, '');
4223 * This method does the acutal work for process_question_usage or
4224 * process_{nameprefix}_question_usage.
4225 * @param array $data the data from the XML file.
4226 * @param string $nameprefix the element name prefix.
4228 protected function restore_question_usage_worker($data, $nameprefix) {
4229 global $DB;
4231 // Clear our caches.
4232 $this->qtypes = array();
4233 $this->newquestionids = array();
4235 $data = (object)$data;
4236 $oldid = $data->id;
4238 $oldcontextid = $this->get_task()->get_old_contextid();
4239 $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
4241 // Everything ready, insert (no mapping needed)
4242 $newitemid = $DB->insert_record('question_usages', $data);
4244 $this->inform_new_usage_id($newitemid);
4246 $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
4250 * When process_question_usage creates the new usage, it calls this method
4251 * to let the activity link to the new usage. For example, the quiz uses
4252 * this method to set quiz_attempts.uniqueid to the new usage id.
4253 * @param integer $newusageid
4255 abstract protected function inform_new_usage_id($newusageid);
4258 * This method does the acutal work for process_question_attempt or
4259 * process_{nameprefix}_question_attempt.
4260 * @param array $data the data from the XML file.
4261 * @param string $nameprefix the element name prefix.
4263 protected function restore_question_attempt_worker($data, $nameprefix) {
4264 global $DB;
4266 $data = (object)$data;
4267 $oldid = $data->id;
4268 $question = $this->get_mapping('question', $data->questionid);
4270 $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
4271 $data->questionid = $question->newitemid;
4272 if (!property_exists($data, 'variant')) {
4273 $data->variant = 1;
4275 $data->timemodified = $this->apply_date_offset($data->timemodified);
4277 if (!property_exists($data, 'maxfraction')) {
4278 $data->maxfraction = 1;
4281 $newitemid = $DB->insert_record('question_attempts', $data);
4283 $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
4284 $this->qtypes[$newitemid] = $question->info->qtype;
4285 $this->newquestionids[$newitemid] = $data->questionid;
4289 * This method does the acutal work for process_question_attempt_step or
4290 * process_{nameprefix}_question_attempt_step.
4291 * @param array $data the data from the XML file.
4292 * @param string $nameprefix the element name prefix.
4294 protected function restore_question_attempt_step_worker($data, $nameprefix) {
4295 global $DB;
4297 $data = (object)$data;
4298 $oldid = $data->id;
4300 // Pull out the response data.
4301 $response = array();
4302 if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
4303 foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
4304 $response[$variable['name']] = $variable['value'];
4307 unset($data->response);
4309 $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
4310 $data->timecreated = $this->apply_date_offset($data->timecreated);
4311 $data->userid = $this->get_mappingid('user', $data->userid);
4313 // Everything ready, insert and create mapping (needed by question_sessions)
4314 $newitemid = $DB->insert_record('question_attempt_steps', $data);
4315 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
4317 // Now process the response data.
4318 $response = $this->questions_recode_response_data(
4319 $this->qtypes[$data->questionattemptid],
4320 $this->newquestionids[$data->questionattemptid],
4321 $data->sequencenumber, $response);
4323 foreach ($response as $name => $value) {
4324 $row = new stdClass();
4325 $row->attemptstepid = $newitemid;
4326 $row->name = $name;
4327 $row->value = $value;
4328 $DB->insert_record('question_attempt_step_data', $row, false);
4333 * Recode the respones data for a particular step of an attempt at at particular question.
4334 * @param string $qtype the question type.
4335 * @param int $newquestionid the question id.
4336 * @param int $sequencenumber the sequence number.
4337 * @param array $response the response data to recode.
4339 public function questions_recode_response_data(
4340 $qtype, $newquestionid, $sequencenumber, array $response) {
4341 $qtyperestorer = $this->get_qtype_restorer($qtype);
4342 if ($qtyperestorer) {
4343 $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
4345 return $response;
4349 * Given a list of question->ids, separated by commas, returns the
4350 * recoded list, with all the restore question mappings applied.
4351 * Note: Used by quiz->questions and quiz_attempts->layout
4352 * Note: 0 = page break (unconverted)
4354 protected function questions_recode_layout($layout) {
4355 // Extracts question id from sequence
4356 if ($questionids = explode(',', $layout)) {
4357 foreach ($questionids as $id => $questionid) {
4358 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
4359 $newquestionid = $this->get_mappingid('question', $questionid);
4360 $questionids[$id] = $newquestionid;
4364 return implode(',', $questionids);
4368 * Get the restore_qtype_plugin subclass for a specific question type.
4369 * @param string $qtype e.g. multichoice.
4370 * @return restore_qtype_plugin instance.
4372 protected function get_qtype_restorer($qtype) {
4373 // Build one static cache to store {@link restore_qtype_plugin}
4374 // while we are needing them, just to save zillions of instantiations
4375 // or using static stuff that will break our nice API
4376 static $qtypeplugins = array();
4378 if (!isset($qtypeplugins[$qtype])) {
4379 $classname = 'restore_qtype_' . $qtype . '_plugin';
4380 if (class_exists($classname)) {
4381 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
4382 } else {
4383 $qtypeplugins[$qtype] = null;
4386 return $qtypeplugins[$qtype];
4389 protected function after_execute() {
4390 parent::after_execute();
4392 // Restore any files belonging to responses.
4393 foreach (question_engine::get_all_response_file_areas() as $filearea) {
4394 $this->add_related_files('question', $filearea, 'question_attempt_step');
4399 * Attach below $element (usually attempts) the needed restore_path_elements
4400 * to restore question attempt data from Moodle 2.0.
4402 * When using this method, the parent element ($element) must be defined with
4403 * $grouped = true. Then, in that elements process method, you must call
4404 * {@link process_legacy_attempt_data()} with the groupded data. See, for
4405 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
4406 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
4407 * @param array $paths the paths array that is being built to describe the
4408 * structure.
4410 protected function add_legacy_question_attempt_data($element, &$paths) {
4411 global $CFG;
4412 require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
4414 // Check $element is restore_path_element
4415 if (!($element instanceof restore_path_element)) {
4416 throw new restore_step_exception('element_must_be_restore_path_element', $element);
4418 // Check $paths is one array
4419 if (!is_array($paths)) {
4420 throw new restore_step_exception('paths_must_be_array', $paths);
4423 $paths[] = new restore_path_element('question_state',
4424 $element->get_path() . '/states/state');
4425 $paths[] = new restore_path_element('question_session',
4426 $element->get_path() . '/sessions/session');
4429 protected function get_attempt_upgrader() {
4430 if (empty($this->attemptupgrader)) {
4431 $this->attemptupgrader = new question_engine_attempt_upgrader();
4432 $this->attemptupgrader->prepare_to_restore();
4434 return $this->attemptupgrader;
4438 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
4439 * @param object $data contains all the grouped attempt data to process.
4440 * @param pbject $quiz data about the activity the attempts belong to. Required
4441 * fields are (basically this only works for the quiz module):
4442 * oldquestions => list of question ids in this activity - using old ids.
4443 * preferredbehaviour => the behaviour to use for questionattempts.
4445 protected function process_legacy_quiz_attempt_data($data, $quiz) {
4446 global $DB;
4447 $upgrader = $this->get_attempt_upgrader();
4449 $data = (object)$data;
4451 $layout = explode(',', $data->layout);
4452 $newlayout = $layout;
4454 // Convert each old question_session into a question_attempt.
4455 $qas = array();
4456 foreach (explode(',', $quiz->oldquestions) as $questionid) {
4457 if ($questionid == 0) {
4458 continue;
4461 $newquestionid = $this->get_mappingid('question', $questionid);
4462 if (!$newquestionid) {
4463 throw new restore_step_exception('questionattemptreferstomissingquestion',
4464 $questionid, $questionid);
4467 $question = $upgrader->load_question($newquestionid, $quiz->id);
4469 foreach ($layout as $key => $qid) {
4470 if ($qid == $questionid) {
4471 $newlayout[$key] = $newquestionid;
4475 list($qsession, $qstates) = $this->find_question_session_and_states(
4476 $data, $questionid);
4478 if (empty($qsession) || empty($qstates)) {
4479 throw new restore_step_exception('questionattemptdatamissing',
4480 $questionid, $questionid);
4483 list($qsession, $qstates) = $this->recode_legacy_response_data(
4484 $question, $qsession, $qstates);
4486 $data->layout = implode(',', $newlayout);
4487 $qas[$newquestionid] = $upgrader->convert_question_attempt(
4488 $quiz, $data, $question, $qsession, $qstates);
4491 // Now create a new question_usage.
4492 $usage = new stdClass();
4493 $usage->component = 'mod_quiz';
4494 $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
4495 $usage->preferredbehaviour = $quiz->preferredbehaviour;
4496 $usage->id = $DB->insert_record('question_usages', $usage);
4498 $this->inform_new_usage_id($usage->id);
4500 $data->uniqueid = $usage->id;
4501 $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
4502 $this->questions_recode_layout($quiz->oldquestions));
4505 protected function find_question_session_and_states($data, $questionid) {
4506 $qsession = null;
4507 foreach ($data->sessions['session'] as $session) {
4508 if ($session['questionid'] == $questionid) {
4509 $qsession = (object) $session;
4510 break;
4514 $qstates = array();
4515 foreach ($data->states['state'] as $state) {
4516 if ($state['question'] == $questionid) {
4517 // It would be natural to use $state['seq_number'] as the array-key
4518 // here, but it seems that buggy behaviour in 2.0 and early can
4519 // mean that that is not unique, so we use id, which is guaranteed
4520 // to be unique.
4521 $qstates[$state['id']] = (object) $state;
4524 ksort($qstates);
4525 $qstates = array_values($qstates);
4527 return array($qsession, $qstates);
4531 * Recode any ids in the response data
4532 * @param object $question the question data
4533 * @param object $qsession the question sessions.
4534 * @param array $qstates the question states.
4536 protected function recode_legacy_response_data($question, $qsession, $qstates) {
4537 $qsession->questionid = $question->id;
4539 foreach ($qstates as &$state) {
4540 $state->question = $question->id;
4541 $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
4544 return array($qsession, $qstates);
4548 * Recode the legacy answer field.
4549 * @param object $state the state to recode the answer of.
4550 * @param string $qtype the question type.
4552 public function restore_recode_legacy_answer($state, $qtype) {
4553 $restorer = $this->get_qtype_restorer($qtype);
4554 if ($restorer) {
4555 return $restorer->recode_legacy_state_answer($state);
4556 } else {
4557 return $state->answer;