3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Defines various restore steps that will be used by common tasks in restore
21 * @package core_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();
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 = get_context_instance(CONTEXT_COURSE, $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 = get_context_instance(CONTEXT_SYSTEM)->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);
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() {
67 restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
68 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
69 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
70 backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
76 * Restore calculated grade items, grade categories etc
78 class restore_gradebook_structure_step extends restore_structure_step {
81 * To conditionally decide if this step must be executed
82 * Note the "settings" conditions are evaluated in the
83 * corresponding task. Here we check for other conditions
84 * not being restore settings (files, site settings...)
86 protected function execute_condition() {
89 // No gradebook info found, don't execute
90 $fullpath = $this->task->get_taskbasepath();
91 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
92 if (!file_exists($fullpath)) {
96 // Some module present in backup file isn't available to restore
97 // in this site, don't execute
98 if ($this->task->is_missing_modules()) {
102 // Some activity has been excluded to be restored, don't execute
103 if ($this->task->is_excluding_activities()) {
107 // There should only be one grade category (the 1 associated with the course itself)
108 // If other categories already exist we're restoring into an existing course.
109 // Restoring categories into a course with an existing category structure is unlikely to go well
110 $category = new stdclass();
111 $category->courseid = $this->get_courseid();
112 $catcount = $DB->count_records('grade_categories', (array)$category);
117 // Arrived here, execute the step
121 protected function define_structure() {
123 $userinfo = $this->task->get_setting_value('users');
125 $paths[] = new restore_path_element('gradebook', '/gradebook');
126 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
127 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
129 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
131 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
132 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
137 protected function process_gradebook($data) {
140 protected function process_grade_item($data) {
143 $data = (object)$data;
146 $data->course = $this->get_courseid();
148 $data->courseid = $this->get_courseid();
150 if ($data->itemtype=='manual') {
151 // manual grade items store category id in categoryid
152 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
153 } else if ($data->itemtype=='course') {
154 // course grade item stores their category id in iteminstance
155 $coursecat = grade_category::fetch_course_category($this->get_courseid());
156 $data->iteminstance = $coursecat->id;
157 } else if ($data->itemtype=='category') {
158 // category grade items store their category id in iteminstance
159 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
161 throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
164 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
165 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
167 $data->locktime = $this->apply_date_offset($data->locktime);
168 $data->timecreated = $this->apply_date_offset($data->timecreated);
169 $data->timemodified = $this->apply_date_offset($data->timemodified);
171 $coursecategory = $newitemid = null;
172 //course grade item should already exist so updating instead of inserting
173 if($data->itemtype=='course') {
174 //get the ID of the already created grade item
175 $gi = new stdclass();
176 $gi->courseid = $this->get_courseid();
177 $gi->itemtype = $data->itemtype;
179 //need to get the id of the grade_category that was automatically created for the course
180 $category = new stdclass();
181 $category->courseid = $this->get_courseid();
182 $category->parent = null;
183 //course category fullname starts out as ? but may be edited
184 //$category->fullname = '?';
185 $coursecategory = $DB->get_record('grade_categories', (array)$category);
186 $gi->iteminstance = $coursecategory->id;
188 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
189 if (!empty($existinggradeitem)) {
190 $data->id = $newitemid = $existinggradeitem->id;
191 $DB->update_record('grade_items', $data);
195 if (empty($newitemid)) {
196 //in case we found the course category but still need to insert the course grade item
197 if ($data->itemtype=='course' && !empty($coursecategory)) {
198 $data->iteminstance = $coursecategory->id;
201 $newitemid = $DB->insert_record('grade_items', $data);
203 $this->set_mapping('grade_item', $oldid, $newitemid);
206 protected function process_grade_grade($data) {
209 $data = (object)$data;
210 $olduserid = $data->userid;
212 $data->itemid = $this->get_new_parentid('grade_item');
214 $data->userid = $this->get_mappingid('user', $data->userid, null);
215 if (!empty($data->userid)) {
216 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
217 $data->locktime = $this->apply_date_offset($data->locktime);
218 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
219 $data->overridden = $this->apply_date_offset($data->overridden);
220 $data->timecreated = $this->apply_date_offset($data->timecreated);
221 $data->timemodified = $this->apply_date_offset($data->timemodified);
223 $newitemid = $DB->insert_record('grade_grades', $data);
225 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
229 protected function process_grade_category($data) {
232 $data = (object)$data;
235 $data->course = $this->get_courseid();
236 $data->courseid = $data->course;
238 $data->timecreated = $this->apply_date_offset($data->timecreated);
239 $data->timemodified = $this->apply_date_offset($data->timemodified);
242 //no parent means a course level grade category. That may have been created when the course was created
243 if(empty($data->parent)) {
244 //parent was being saved as 0 when it should be null
245 $data->parent = null;
247 //get the already created course level grade category
248 $category = new stdclass();
249 $category->courseid = $this->get_courseid();
250 $category->parent = null;
252 $coursecategory = $DB->get_record('grade_categories', (array)$category);
253 if (!empty($coursecategory)) {
254 $data->id = $newitemid = $coursecategory->id;
255 $DB->update_record('grade_categories', $data);
259 //need to insert a course category
260 if (empty($newitemid)) {
261 $newitemid = $DB->insert_record('grade_categories', $data);
263 $this->set_mapping('grade_category', $oldid, $newitemid);
265 protected function process_grade_letter($data) {
268 $data = (object)$data;
271 $data->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
273 $newitemid = $DB->insert_record('grade_letters', $data);
274 $this->set_mapping('grade_letter', $oldid, $newitemid);
276 protected function process_grade_setting($data) {
279 $data = (object)$data;
282 $data->courseid = $this->get_courseid();
284 $newitemid = $DB->insert_record('grade_settings', $data);
285 //$this->set_mapping('grade_setting', $oldid, $newitemid);
289 * put all activity grade items in the correct grade category and mark all for recalculation
291 protected function after_execute() {
295 'backupid' => $this->get_restoreid(),
296 'itemname' => 'grade_item'//,
297 //'itemid' => $itemid
299 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
301 // We need this for calculation magic later on.
305 foreach($rs as $grade_item_backup) {
307 // Store the oldid with the new id.
308 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
310 $updateobj = new stdclass();
311 $updateobj->id = $grade_item_backup->newitemid;
313 //if this is an activity grade item that needs to be put back in its correct category
314 if (!empty($grade_item_backup->parentitemid)) {
315 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
316 if (!is_null($oldcategoryid)) {
317 $updateobj->categoryid = $oldcategoryid;
318 $DB->update_record('grade_items', $updateobj);
321 //mark course and category items as needing to be recalculated
322 $updateobj->needsupdate=1;
323 $DB->update_record('grade_items', $updateobj);
329 // We need to update the calculations for calculated grade items that may reference old
330 // grade item ids using ##gi\d+##.
331 // $mappings can be empty, use 0 if so (won't match ever)
332 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
333 $sql = "SELECT gi.id, gi.calculation
334 FROM {grade_items} gi
335 WHERE gi.id {$sql} AND
336 calculation IS NOT NULL";
337 $rs = $DB->get_recordset_sql($sql, $params);
338 foreach ($rs as $gradeitem) {
339 // Collect all of the used grade item id references
340 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
341 // This calculation doesn't reference any other grade items... EASY!
344 // For this next bit we are going to do the replacement of id's in two steps:
345 // 1. We will replace all old id references with a special mapping reference.
346 // 2. We will replace all mapping references with id's
347 // Why do we do this?
348 // Because there potentially there will be an overlap of ids within the query and we
349 // we substitute the wrong id.. safest way around this is the two step system
350 $calculationmap = array();
352 foreach ($matches[1] as $match) {
353 // Check that the old id is known to us, if not it was broken to begin with and will
354 // continue to be broken.
355 if (!array_key_exists($match, $mappings)) {
358 // Our special mapping key
359 $mapping = '##MAPPING'.$mapcount.'##';
360 // The old id that exists within the calculation now
361 $oldid = '##gi'.$match.'##';
362 // The new id that we want to replace the old one with.
363 $newid = '##gi'.$mappings[$match].'##';
364 // Replace in the special mapping key
365 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
366 // And record the mapping
367 $calculationmap[$mapping] = $newid;
370 // Iterate all special mappings for this calculation and replace in the new id's
371 foreach ($calculationmap as $mapping => $newid) {
372 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
374 // Update the calculation now that its being remapped
375 $DB->update_record('grade_items', $gradeitem);
379 // Need to correct the grade category path and parent
381 'courseid' => $this->get_courseid()
384 $rs = $DB->get_recordset('grade_categories', $conditions);
385 // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
386 foreach ($rs as $gc) {
387 if (!empty($gc->parent)) {
388 $grade_category = new stdClass();
389 $grade_category->id = $gc->id;
390 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
391 $DB->update_record('grade_categories', $grade_category);
396 // Now we can rebuild all the paths
397 $rs = $DB->get_recordset('grade_categories', $conditions);
398 foreach ($rs as $gc) {
399 $grade_category = new stdClass();
400 $grade_category->id = $gc->id;
401 $grade_category->path = grade_category::build_path($gc);
402 $grade_category->depth = substr_count($grade_category->path, '/') - 1;
403 $DB->update_record('grade_categories', $grade_category);
407 // Restore marks items as needing update. Update everything now.
408 grade_regrade_final_grades($this->get_courseid());
413 * decode all the interlinks present in restored content
414 * relying 100% in the restore_decode_processor that handles
415 * both the contents to modify and the rules to be applied
417 class restore_decode_interlinks extends restore_execution_step {
419 protected function define_execution() {
420 // Get the decoder (from the plan)
421 $decoder = $this->task->get_decoder();
422 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
423 // And launch it, everything will be processed
429 * first, ensure that we have no gaps in section numbers
430 * and then, rebuid the course cache
432 class restore_rebuild_course_cache extends restore_execution_step {
434 protected function define_execution() {
437 // Although there is some sort of auto-recovery of missing sections
438 // present in course/formats... here we check that all the sections
439 // from 0 to MAX(section->section) exist, creating them if necessary
440 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
441 // Iterate over all sections
442 for ($i = 0; $i <= $maxsection; $i++) {
443 // If the section $i doesn't exist, create it
444 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
446 'course' => $this->get_courseid(),
448 $DB->insert_record('course_sections', $sectionrec); // missing section created
452 // Rebuild cache now that all sections are in place
453 rebuild_course_cache($this->get_courseid());
458 * Review all the tasks having one after_restore method
459 * executing it to perform some final adjustments of information
460 * not available when the task was executed.
462 class restore_execute_after_restore extends restore_execution_step {
464 protected function define_execution() {
466 // Simply call to the execute_after_restore() method of the task
467 // that always is the restore_final_task
468 $this->task->launch_execute_after_restore();
474 * Review all the (pending) block positions in backup_ids, matching by
475 * contextid, creating positions as needed. This is executed by the
476 * final task, once all the contexts have been created
478 class restore_review_pending_block_positions extends restore_execution_step {
480 protected function define_execution() {
483 // Get all the block_position objects pending to match
484 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
485 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
486 // Process block positions, creating them or accumulating for final step
487 foreach($rs as $posrec) {
488 // Get the complete position object (stored as info)
489 $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
490 // If position is for one already mapped (known) contextid
491 // process it now, creating the position, else nothing to
492 // do, position finally discarded
493 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
494 $position->contextid = $newctx->newitemid;
495 // Create the block position
496 $DB->insert_record('block_positions', $position);
504 * Process all the saved module availability records in backup_ids, matching
505 * course modules and grade item id once all them have been already restored.
506 * only if all matchings are satisfied the availability condition will be created.
507 * At the same time, it is required for the site to have that functionality enabled.
509 class restore_process_course_modules_availability extends restore_execution_step {
511 protected function define_execution() {
514 // Site hasn't availability enabled
515 if (empty($CFG->enableavailability)) {
519 // Get all the module_availability objects to process
520 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
521 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
522 // Process availabilities, creating them if everything matches ok
523 foreach($rs as $availrec) {
524 $allmatchesok = true;
525 // Get the complete availabilityobject
526 $availability = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_availability', $availrec->itemid)->info;
527 // Map the sourcecmid if needed and possible
528 if (!empty($availability->sourcecmid)) {
529 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
531 $availability->sourcecmid = $newcm->newitemid;
533 $allmatchesok = false; // Failed matching, we won't create this availability rule
536 // Map the gradeitemid if needed and possible
537 if (!empty($availability->gradeitemid)) {
538 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
540 $availability->gradeitemid = $newgi->newitemid;
542 $allmatchesok = false; // Failed matching, we won't create this availability rule
545 if ($allmatchesok) { // Everything ok, create the availability rule
546 $DB->insert_record('course_modules_availability', $availability);
555 * Execution step that, *conditionally* (if there isn't preloaded information)
556 * will load the inforef files for all the included course/section/activity tasks
557 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
559 class restore_load_included_inforef_records extends restore_execution_step {
561 protected function define_execution() {
563 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
567 // Get all the included tasks
568 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
569 foreach ($tasks as $task) {
570 // Load the inforef.xml file if exists
571 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
572 if (file_exists($inforefpath)) {
573 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath); // Load each inforef file to temp_ids
580 * Execution step that will load all the needed files into backup_files_temp
581 * - info: contains the whole original object (times, names...)
582 * (all them being original ids as loaded from xml)
584 class restore_load_included_files extends restore_structure_step {
586 protected function define_structure() {
588 $file = new restore_path_element('file', '/files/file');
594 * Process one <file> element from files.xml
596 * @param array $data the element data
598 public function process_file($data) {
600 $data = (object)$data; // handy
602 // load it if needed:
603 // - it it is one of the annotated inforef files (course/section/activity/block)
604 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
605 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
606 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
607 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
608 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
609 $data->component == 'grouping' || $data->component == 'grade' ||
610 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
611 if ($isfileref || $iscomponent) {
612 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
618 * Execution step that, *conditionally* (if there isn't preloaded information),
619 * will load all the needed roles to backup_temp_ids. They will be stored with
620 * "role" itemname. Also it will perform one automatic mapping to roles existing
621 * in the target site, based in permissions of the user performing the restore,
622 * archetypes and other bits. At the end, each original role will have its associated
623 * target role or 0 if it's going to be skipped. Note we wrap everything over one
624 * restore_dbops method, as far as the same stuff is going to be also executed
625 * by restore prechecks
627 class restore_load_and_map_roles extends restore_execution_step {
629 protected function define_execution() {
630 if ($this->task->get_preloaded_information()) { // if info is already preloaded
634 $file = $this->get_basepath() . '/roles.xml';
635 // Load needed toles to temp_ids
636 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
638 // Process roles, mapping/skipping. Any error throws exception
639 // Note we pass controller's info because it can contain role mapping information
640 // about manual mappings performed by UI
641 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);
646 * Execution step that, *conditionally* (if there isn't preloaded information
647 * and users have been selected in settings, will load all the needed users
648 * to backup_temp_ids. They will be stored with "user" itemname and with
649 * their original contextid as paremitemid
651 class restore_load_included_users extends restore_execution_step {
653 protected function define_execution() {
655 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
658 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
661 $file = $this->get_basepath() . '/users.xml';
662 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
667 * Execution step that, *conditionally* (if there isn't preloaded information
668 * and users have been selected in settings, will process all the needed users
669 * in order to decide and perform any action with them (create / map / error)
670 * Note: Any error will cause exception, as far as this is the same processing
671 * than the one into restore prechecks (that should have stopped process earlier)
673 class restore_process_included_users extends restore_execution_step {
675 protected function define_execution() {
677 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
680 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
683 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
688 * Execution step that will create all the needed users as calculated
689 * by @restore_process_included_users (those having newiteind = 0)
691 class restore_create_included_users extends restore_execution_step {
693 protected function define_execution() {
695 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->task->get_userid());
700 * Structure step that will create all the needed groups and groupings
701 * by loading them from the groups.xml file performing the required matches.
702 * Note group members only will be added if restoring user info
704 class restore_groups_structure_step extends restore_structure_step {
706 protected function define_structure() {
708 $paths = array(); // Add paths here
710 $paths[] = new restore_path_element('group', '/groups/group');
711 if ($this->get_setting_value('users')) {
712 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
714 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
715 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
720 // Processing functions go here
721 public function process_group($data) {
724 $data = (object)$data; // handy
725 $data->courseid = $this->get_courseid();
727 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
728 // another a group in the same course
729 $context = context_course::instance($data->courseid);
730 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
731 if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
732 unset($data->idnumber);
735 unset($data->idnumber);
738 $oldid = $data->id; // need this saved for later
740 $restorefiles = false; // Only if we end creating the group
742 // Search if the group already exists (by name & description) in the target course
743 $description_clause = '';
744 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
745 if (!empty($data->description)) {
746 $description_clause = ' AND ' .
747 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
748 $params['description'] = $data->description;
750 if (!$groupdb = $DB->get_record_sql("SELECT *
752 WHERE courseid = :courseid
753 AND name = :grname $description_clause", $params)) {
754 // group doesn't exist, create
755 $newitemid = $DB->insert_record('groups', $data);
756 $restorefiles = true; // We'll restore the files
758 // group exists, use it
759 $newitemid = $groupdb->id;
761 // Save the id mapping
762 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
765 public function process_member($data) {
768 $data = (object)$data; // handy
770 // get parent group->id
771 $data->groupid = $this->get_new_parentid('group');
773 // map user newitemid and insert if not member already
774 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
775 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
776 $DB->insert_record('groups_members', $data);
781 public function process_grouping($data) {
784 $data = (object)$data; // handy
785 $data->courseid = $this->get_courseid();
787 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
788 // another a grouping in the same course
789 $context = context_course::instance($data->courseid);
790 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
791 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
792 unset($data->idnumber);
795 unset($data->idnumber);
798 $oldid = $data->id; // need this saved for later
799 $restorefiles = false; // Only if we end creating the grouping
801 // Search if the grouping already exists (by name & description) in the target course
802 $description_clause = '';
803 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
804 if (!empty($data->description)) {
805 $description_clause = ' AND ' .
806 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
807 $params['description'] = $data->description;
809 if (!$groupingdb = $DB->get_record_sql("SELECT *
811 WHERE courseid = :courseid
812 AND name = :grname $description_clause", $params)) {
813 // grouping doesn't exist, create
814 $newitemid = $DB->insert_record('groupings', $data);
815 $restorefiles = true; // We'll restore the files
817 // grouping exists, use it
818 $newitemid = $groupingdb->id;
820 // Save the id mapping
821 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
824 public function process_grouping_group($data) {
827 $data = (object)$data;
829 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
830 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
833 $params['groupingid'] = $data->groupingid;
834 $params['groupid'] = $data->groupid;
836 if (!$DB->record_exists('groupings_groups', $params)) {
837 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
841 protected function after_execute() {
842 // Add group related files, matching with "group" mappings
843 $this->add_related_files('group', 'icon', 'group');
844 $this->add_related_files('group', 'description', 'group');
845 // Add grouping related files, matching with "grouping" mappings
846 $this->add_related_files('grouping', 'description', 'grouping');
852 * Structure step that will create all the needed scales
853 * by loading them from the scales.xml
855 class restore_scales_structure_step extends restore_structure_step {
857 protected function define_structure() {
859 $paths = array(); // Add paths here
860 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
864 protected function process_scale($data) {
867 $data = (object)$data;
869 $restorefiles = false; // Only if we end creating the group
871 $oldid = $data->id; // need this saved for later
873 // Look for scale (by 'scale' both in standard (course=0) and current course
874 // with priority to standard scales (ORDER clause)
875 // scale is not course unique, use get_record_sql to suppress warning
876 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
877 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
878 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
879 if (!$scadb = $DB->get_record_sql("SELECT *
881 WHERE courseid IN (0, :courseid)
882 AND $compare_scale_clause
883 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
884 // Remap the user if possible, defaut to user performing the restore if not
885 $userid = $this->get_mappingid('user', $data->userid);
886 $data->userid = $userid ? $userid : $this->task->get_userid();
887 // Remap the course if course scale
888 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
889 // If global scale (course=0), check the user has perms to create it
890 // falling to course scale if not
891 $systemctx = get_context_instance(CONTEXT_SYSTEM);
892 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
893 $data->courseid = $this->get_courseid();
895 // scale doesn't exist, create
896 $newitemid = $DB->insert_record('scale', $data);
897 $restorefiles = true; // We'll restore the files
899 // scale exists, use it
900 $newitemid = $scadb->id;
902 // Save the id mapping (with files support at system context)
903 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
906 protected function after_execute() {
907 // Add scales related files, matching with "scale" mappings
908 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
914 * Structure step that will create all the needed outocomes
915 * by loading them from the outcomes.xml
917 class restore_outcomes_structure_step extends restore_structure_step {
919 protected function define_structure() {
921 $paths = array(); // Add paths here
922 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
926 protected function process_outcome($data) {
929 $data = (object)$data;
931 $restorefiles = false; // Only if we end creating the group
933 $oldid = $data->id; // need this saved for later
935 // Look for outcome (by shortname both in standard (courseid=null) and current course
936 // with priority to standard outcomes (ORDER clause)
937 // outcome is not course unique, use get_record_sql to suppress warning
938 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
939 if (!$outdb = $DB->get_record_sql('SELECT *
940 FROM {grade_outcomes}
941 WHERE shortname = :shortname
942 AND (courseid = :courseid OR courseid IS NULL)
943 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
945 $userid = $this->get_mappingid('user', $data->usermodified);
946 $data->usermodified = $userid ? $userid : $this->task->get_userid();
948 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
949 // Remap the course if course outcome
950 $data->courseid = $data->courseid ? $this->get_courseid() : null;
951 // If global outcome (course=null), check the user has perms to create it
952 // falling to course outcome if not
953 $systemctx = get_context_instance(CONTEXT_SYSTEM);
954 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
955 $data->courseid = $this->get_courseid();
957 // outcome doesn't exist, create
958 $newitemid = $DB->insert_record('grade_outcomes', $data);
959 $restorefiles = true; // We'll restore the files
961 // scale exists, use it
962 $newitemid = $outdb->id;
964 // Set the corresponding grade_outcomes_courses record
965 $outcourserec = new stdclass();
966 $outcourserec->courseid = $this->get_courseid();
967 $outcourserec->outcomeid = $newitemid;
968 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
969 $DB->insert_record('grade_outcomes_courses', $outcourserec);
971 // Save the id mapping (with files support at system context)
972 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
975 protected function after_execute() {
976 // Add outcomes related files, matching with "outcome" mappings
977 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
982 * Execution step that, *conditionally* (if there isn't preloaded information
983 * will load all the question categories and questions (header info only)
984 * to backup_temp_ids. They will be stored with "question_category" and
985 * "question" itemnames and with their original contextid and question category
988 class restore_load_categories_and_questions extends restore_execution_step {
990 protected function define_execution() {
992 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
995 $file = $this->get_basepath() . '/questions.xml';
996 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1001 * Execution step that, *conditionally* (if there isn't preloaded information)
1002 * will process all the needed categories and questions
1003 * in order to decide and perform any action with them (create / map / error)
1004 * Note: Any error will cause exception, as far as this is the same processing
1005 * than the one into restore prechecks (that should have stopped process earlier)
1007 class restore_process_categories_and_questions extends restore_execution_step {
1009 protected function define_execution() {
1011 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1014 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1019 * Structure step that will read the section.xml creating/updating sections
1020 * as needed, rebuilding course cache and other friends
1022 class restore_section_structure_step extends restore_structure_step {
1024 protected function define_structure() {
1029 $section = new restore_path_element('section', '/section');
1030 $paths[] = $section;
1031 if ($CFG->enableavailability) {
1032 $paths[] = new restore_path_element('availability', '/section/availability');
1035 // Apply for 'format' plugins optional paths at section level
1036 $this->add_plugin_structure('format', $section);
1041 public function process_section($data) {
1043 $data = (object)$data;
1044 $oldid = $data->id; // We'll need this later
1046 $restorefiles = false;
1048 // Look for the section
1049 $section = new stdclass();
1050 $section->course = $this->get_courseid();
1051 $section->section = $data->number;
1052 // Section doesn't exist, create it with all the info from backup
1053 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1054 $section->name = $data->name;
1055 $section->summary = $data->summary;
1056 $section->summaryformat = $data->summaryformat;
1057 $section->sequence = '';
1058 $section->visible = $data->visible;
1059 if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1060 $section->availablefrom = 0;
1061 $section->availableuntil = 0;
1062 $section->showavailability = 0;
1064 $section->availablefrom = isset($data->availablefrom) ? $this->apply_date_offset($data->availablefrom) : 0;
1065 $section->availableuntil = isset($data->availableuntil) ? $this->apply_date_offset($data->availableuntil) : 0;
1066 $section->showavailability = isset($data->showavailability) ? $data->showavailability : 0;
1068 if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
1069 $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
1071 $newitemid = $DB->insert_record('course_sections', $section);
1072 $restorefiles = true;
1074 // Section exists, update non-empty information
1076 $section->id = $secrec->id;
1077 if ((string)$secrec->name === '') {
1078 $section->name = $data->name;
1080 if (empty($secrec->summary)) {
1081 $section->summary = $data->summary;
1082 $section->summaryformat = $data->summaryformat;
1083 $restorefiles = true;
1085 if (empty($secrec->groupingid)) {
1086 if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
1087 $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
1091 // Don't update available from, available until, or show availability
1092 // (I didn't see a useful way to define whether existing or new one should
1093 // take precedence).
1095 $DB->update_record('course_sections', $section);
1096 $newitemid = $secrec->id;
1099 // Annotate the section mapping, with restorefiles option if needed
1100 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1102 // set the new course_section id in the task
1103 $this->task->set_sectionid($newitemid);
1106 // Commented out. We never modify course->numsections as far as that is used
1107 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1108 // Note: We keep the code here, to know about and because of the possibility of making this
1109 // optional based on some setting/attribute in the future
1110 // If needed, adjust course->numsections
1111 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1112 // if ($numsections < $section->section) {
1113 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1118 public function process_availability($data) {
1120 $data = (object)$data;
1122 $data->coursesectionid = $this->task->get_sectionid();
1124 // NOTE: Other values in $data need updating, but these (cm,
1125 // grade items) have not yet been restored, so are done later.
1127 $newid = $DB->insert_record('course_sections_availability', $data);
1129 // We do not need to map between old and new id but storing a mapping
1130 // means it gets added to the backup_ids table to record which ones
1131 // need updating. The mapping is stored with $newid => $newid for
1133 $this->set_mapping('course_sections_availability', $newid, $newid);
1136 protected function after_execute() {
1137 // Add section related files, with 'course_section' itemid to match
1138 $this->add_related_files('course', 'section', 'course_section');
1141 public function after_restore() {
1144 $sectionid = $this->get_task()->get_sectionid();
1146 // Get data object for current section availability (if any).
1147 $data = $DB->get_record('course_sections_availability',
1148 array('coursesectionid' => $sectionid), 'id, sourcecmid, gradeitemid', IGNORE_MISSING);
1150 // If it exists, update mappings.
1152 // Only update mappings for entries which are created by this restore.
1153 // Otherwise, when you restore to an existing course, it will mess up
1154 // existing section availability entries.
1155 if (!$this->get_mappingid('course_sections_availability', $data->id, false)) {
1159 // Update source cmid / grade id to new value.
1160 $data->sourcecmid = $this->get_mappingid('course_module', $data->sourcecmid);
1161 if (!$data->sourcecmid) {
1162 $data->sourcecmid = null;
1164 $data->gradeitemid = $this->get_mappingid('grade_item', $data->gradeitemid);
1165 if (!$data->gradeitemid) {
1166 $data->gradeitemid = null;
1169 $DB->update_record('course_sections_availability', $data);
1176 * Structure step that will read the course.xml file, loading it and performing
1177 * various actions depending of the site/restore settings. Note that target
1178 * course always exist before arriving here so this step will be updating
1179 * the course record (never inserting)
1181 class restore_course_structure_step extends restore_structure_step {
1183 * @var bool this gets set to true by {@link process_course()} if we are
1184 * restoring an old coures that used the legacy 'module security' feature.
1185 * If so, we have to do more work in {@link after_execute()}.
1187 protected $legacyrestrictmodules = false;
1190 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1191 * array with array keys the module names ('forum', 'quiz', etc.). These are
1192 * the modules that are allowed according to the data in the backup file.
1193 * In {@link after_execute()} we then have to prevent adding of all the other
1194 * types of activity.
1196 protected $legacyallowedmodules = array();
1198 protected function define_structure() {
1200 $course = new restore_path_element('course', '/course');
1201 $category = new restore_path_element('category', '/course/category');
1202 $tag = new restore_path_element('tag', '/course/tags/tag');
1203 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1205 // Apply for 'format' plugins optional paths at course level
1206 $this->add_plugin_structure('format', $course);
1208 // Apply for 'theme' plugins optional paths at course level
1209 $this->add_plugin_structure('theme', $course);
1211 // Apply for 'report' plugins optional paths at course level
1212 $this->add_plugin_structure('report', $course);
1214 // Apply for 'course report' plugins optional paths at course level
1215 $this->add_plugin_structure('coursereport', $course);
1217 // Apply for plagiarism plugins optional paths at course level
1218 $this->add_plugin_structure('plagiarism', $course);
1220 return array($course, $category, $tag, $allowed_module);
1224 * Processing functions go here
1226 * @global moodledatabase $DB
1227 * @param stdClass $data
1229 public function process_course($data) {
1232 $data = (object)$data;
1234 $fullname = $this->get_setting_value('course_fullname');
1235 $shortname = $this->get_setting_value('course_shortname');
1236 $startdate = $this->get_setting_value('course_startdate');
1238 // Calculate final course names, to avoid dupes
1239 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1241 // Need to change some fields before updating the course record
1242 $data->id = $this->get_courseid();
1243 $data->fullname = $fullname;
1244 $data->shortname= $shortname;
1246 $context = get_context_instance_by_id($this->task->get_contextid());
1247 if (has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1248 $data->idnumber = '';
1250 unset($data->idnumber);
1253 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1254 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1255 if (empty($data->hiddensections)) {
1256 $data->hiddensections = 0;
1259 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1260 // then we will need to process restricted modules after execution.
1261 $this->legacyrestrictmodules = !empty($data->restrictmodules);
1263 $data->startdate= $this->apply_date_offset($data->startdate);
1264 if ($data->defaultgroupingid) {
1265 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1267 if (empty($CFG->enablecompletion)) {
1268 $data->enablecompletion = 0;
1269 $data->completionstartonenrol = 0;
1270 $data->completionnotify = 0;
1272 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1273 if (!array_key_exists($data->lang, $languages)) {
1277 $themes = get_list_of_themes(); // Get themes for quick search later
1278 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1282 // Course record ready, update it
1283 $DB->update_record('course', $data);
1285 // Role name aliases
1286 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1289 public function process_category($data) {
1290 // Nothing to do with the category. UI sets it before restore starts
1293 public function process_tag($data) {
1296 $data = (object)$data;
1298 if (!empty($CFG->usetags)) { // if enabled in server
1299 // TODO: This is highly inneficient. Each time we add one tag
1300 // we fetch all the existing because tag_set() deletes them
1301 // so everything must be reinserted on each call
1303 $existingtags = tag_get_tags('course', $this->get_courseid());
1304 // Re-add all the existitng tags
1305 foreach ($existingtags as $existingtag) {
1306 $tags[] = $existingtag->rawname;
1308 // Add the one being restored
1309 $tags[] = $data->rawname;
1310 // Send all the tags back to the course
1311 tag_set('course', $this->get_courseid(), $tags);
1315 public function process_allowed_module($data) {
1316 $data = (object)$data;
1318 // Backwards compatiblity support for the data that used to be in the
1319 // course_allowed_modules table.
1320 if ($this->legacyrestrictmodules) {
1321 $this->legacyallowedmodules[$data->modulename] = 1;
1325 protected function after_execute() {
1328 // Add course related files, without itemid to match
1329 $this->add_related_files('course', 'summary', null);
1330 $this->add_related_files('course', 'legacy', null);
1332 // Deal with legacy allowed modules.
1333 if ($this->legacyrestrictmodules) {
1334 $context = context_course::instance($this->get_courseid());
1336 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1337 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1338 foreach ($managerroleids as $roleid) {
1339 unset($roleids[$roleid]);
1342 foreach (get_plugin_list('mod') as $modname => $notused) {
1343 if (isset($this->legacyallowedmodules[$modname])) {
1344 // Module is allowed, no worries.
1348 $capability = 'mod/' . $modname . ':addinstance';
1349 foreach ($roleids as $roleid) {
1350 assign_capability($capability, CAP_PREVENT, $roleid, $context);
1359 * Structure step that will read the roles.xml file (at course/activity/block levels)
1360 * containig all the role_assignments and overrides for that context. If corresponding to
1361 * one mapped role, they will be applied to target context. Will observe the role_assignments
1362 * setting to decide if ras are restored.
1363 * Note: only ras with component == null are restored as far as the any ra with component
1364 * is handled by one enrolment plugin, hence it will createt the ras later
1366 class restore_ras_and_caps_structure_step extends restore_structure_step {
1368 protected function define_structure() {
1372 // Observe the role_assignments setting
1373 if ($this->get_setting_value('role_assignments')) {
1374 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1376 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1384 * This has to be called after enrolments processing.
1386 * @param mixed $data
1389 public function process_assignment($data) {
1392 $data = (object)$data;
1394 // Check roleid, userid are one of the mapped ones
1395 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1398 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1401 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1402 // Only assign roles to not deleted users
1405 if (!$contextid = $this->task->get_contextid()) {
1409 if (empty($data->component)) {
1410 // assign standard manual roles
1411 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1412 role_assign($newroleid, $newuserid, $contextid);
1414 } else if ((strpos($data->component, 'enrol_') === 0)) {
1415 // Deal with enrolment roles
1416 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1417 if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
1418 //note: we have to verify component because it might have changed
1419 if ($component === 'enrol_manual') {
1420 // manual is a special case, we do not use components - this owudl happen when converting from other plugin
1421 role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
1423 role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
1430 public function process_override($data) {
1431 $data = (object)$data;
1433 // Check roleid is one of the mapped ones
1434 $newroleid = $this->get_mappingid('role', $data->roleid);
1435 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1436 if ($newroleid && $this->task->get_contextid()) {
1437 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1438 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1439 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1445 * This structure steps restores the enrol plugins and their underlying
1446 * enrolments, performing all the mappings and/or movements required
1448 class restore_enrolments_structure_step extends restore_structure_step {
1451 * Conditionally decide if this step should be executed.
1453 * This function checks the following parameter:
1455 * 1. the course/enrolments.xml file exists
1457 * @return bool true is safe to execute, false otherwise
1459 protected function execute_condition() {
1461 // Check it is included in the backup
1462 $fullpath = $this->task->get_taskbasepath();
1463 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1464 if (!file_exists($fullpath)) {
1465 // Not found, can't restore enrolments info
1472 protected function define_structure() {
1476 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1477 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1483 * Create enrolment instances.
1485 * This has to be called after creation of roles
1486 * and before adding of role assignments.
1488 * @param mixed $data
1491 public function process_enrol($data) {
1494 $data = (object)$data;
1495 $oldid = $data->id; // We'll need this later
1497 $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);
1499 if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
1500 // TODO: add complex restore support via custom class
1501 debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
1502 $this->set_mapping('enrol', $oldid, 0);
1506 // Perform various checks to decide what to do with the enrol plugin
1507 if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
1508 // TODO: decide if we want to switch to manual enrol - we need UI for this
1509 debugging("Enrol plugin data can not be restored because it is not installed");
1510 $this->set_mapping('enrol', $oldid, 0);
1514 if (!enrol_is_enabled($data->enrol)) {
1515 // TODO: decide if we want to switch to manual enrol - we need UI for this
1516 debugging("Enrol plugin data can not be restored because it is not enabled");
1517 $this->set_mapping('enrol', $oldid, 0);
1521 // map standard fields - plugin has to process custom fields from own restore class
1522 $data->roleid = $this->get_mappingid('role', $data->roleid);
1523 //TODO: should we move the enrol start and end date here?
1525 // always add instance, if the course does not support multiple instances it just returns NULL
1526 $enrol = enrol_get_plugin($data->enrol);
1527 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1528 if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
1531 if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
1532 // most probably plugin that supports only one instance
1533 $newitemid = key($instances);
1535 debugging('Can not create new enrol instance or reuse existing');
1540 if ($restoretype === ENROL_RESTORE_NOUSERS) {
1541 // plugin requests to prevent restore of any users
1545 $this->set_mapping('enrol', $oldid, $newitemid);
1549 * Create user enrolments
1551 * This has to be called after creation of enrolment instances
1552 * and before adding of role assignments.
1554 * @param mixed $data
1557 public function process_enrolment($data) {
1560 $data = (object)$data;
1562 // Process only if parent instance have been mapped
1563 if ($enrolid = $this->get_new_parentid('enrol')) {
1564 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1565 // And only if user is a mapped one
1566 if ($userid = $this->get_mappingid('user', $data->userid)) {
1567 $enrol = enrol_get_plugin($instance->enrol);
1568 //TODO: do we need specify modifierid?
1569 $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
1570 //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
1579 * Make sure the user restoring the course can actually access it.
1581 class restore_fix_restorer_access_step extends restore_execution_step {
1582 protected function define_execution() {
1585 if (!$userid = $this->task->get_userid()) {
1589 if (empty($CFG->restorernewroleid)) {
1590 // Bad luck, no fallback role for restorers specified
1594 $courseid = $this->get_courseid();
1595 $context = context_course::instance($courseid);
1597 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1598 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
1602 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
1603 role_assign($CFG->restorernewroleid, $userid, $context);
1605 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1606 // Extra role is enough, yay!
1610 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
1611 // hopefully admin selected suitable $CFG->restorernewroleid ...
1612 if (!enrol_is_enabled('manual')) {
1615 if (!$enrol = enrol_get_plugin('manual')) {
1618 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
1619 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
1620 $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
1621 $enrol->add_instance($course, $fields);
1624 enrol_try_internal_enrol($courseid, $userid);
1630 * This structure steps restores the filters and their configs
1632 class restore_filters_structure_step extends restore_structure_step {
1634 protected function define_structure() {
1638 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1639 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1644 public function process_active($data) {
1646 $data = (object)$data;
1648 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1651 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1654 public function process_config($data) {
1656 $data = (object)$data;
1658 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1661 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1667 * This structure steps restores the comments
1668 * Note: Cannot use the comments API because defaults to USER->id.
1669 * That should change allowing to pass $userid
1671 class restore_comments_structure_step extends restore_structure_step {
1673 protected function define_structure() {
1677 $paths[] = new restore_path_element('comment', '/comments/comment');
1682 public function process_comment($data) {
1685 $data = (object)$data;
1687 // First of all, if the comment has some itemid, ask to the task what to map
1689 if ($data->itemid) {
1690 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1691 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
1693 // Only restore the comment if has no mapping OR we have found the matching mapping
1694 if (!$mapping || $data->itemid) {
1695 // Only if user mapping and context
1696 $data->userid = $this->get_mappingid('user', $data->userid);
1697 if ($data->userid && $this->task->get_contextid()) {
1698 $data->contextid = $this->task->get_contextid();
1699 // Only if there is another comment with same context/user/timecreated
1700 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1701 if (!$DB->record_exists('comments', $params)) {
1702 $DB->insert_record('comments', $data);
1710 * This structure steps restores the calendar events
1712 class restore_calendarevents_structure_step extends restore_structure_step {
1714 protected function define_structure() {
1718 $paths[] = new restore_path_element('calendarevents', '/events/event');
1723 public function process_calendarevents($data) {
1726 $data = (object)$data;
1728 $restorefiles = true; // We'll restore the files
1729 // Find the userid and the groupid associated with the event. Return if not found.
1730 $data->userid = $this->get_mappingid('user', $data->userid);
1731 if ($data->userid === false) {
1734 if (!empty($data->groupid)) {
1735 $data->groupid = $this->get_mappingid('group', $data->groupid);
1736 if ($data->groupid === false) {
1742 'name' => $data->name,
1743 'description' => $data->description,
1744 'format' => $data->format,
1745 'courseid' => $this->get_courseid(),
1746 'groupid' => $data->groupid,
1747 'userid' => $data->userid,
1748 'repeatid' => $data->repeatid,
1749 'modulename' => $data->modulename,
1750 'eventtype' => $data->eventtype,
1751 'timestart' => $this->apply_date_offset($data->timestart),
1752 'timeduration' => $data->timeduration,
1753 'visible' => $data->visible,
1754 'uuid' => $data->uuid,
1755 'sequence' => $data->sequence,
1756 'timemodified' => $this->apply_date_offset($data->timemodified));
1757 if ($this->name == 'activity_calendar') {
1758 $params['instance'] = $this->task->get_activityid();
1760 $params['instance'] = 0;
1762 $sql = 'SELECT id FROM {event} WHERE name = ? AND courseid = ? AND
1763 repeatid = ? AND modulename = ? AND timestart = ? AND timeduration =?
1764 AND ' . $DB->sql_compare_text('description', 255) . ' = ' . $DB->sql_compare_text('?', 255);
1765 $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
1766 $result = $DB->record_exists_sql($sql, $arg);
1767 if (empty($result)) {
1768 $newitemid = $DB->insert_record('event', $params);
1769 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
1773 protected function after_execute() {
1774 // Add related files
1775 $this->add_related_files('calendar', 'event_description', 'event_description');
1779 class restore_course_completion_structure_step extends restore_structure_step {
1782 * Conditionally decide if this step should be executed.
1784 * This function checks parameters that are not immediate settings to ensure
1785 * that the enviroment is suitable for the restore of course completion info.
1787 * This function checks the following four parameters:
1789 * 1. Course completion is enabled on the site
1790 * 2. The backup includes course completion information
1791 * 3. All modules are restorable
1792 * 4. All modules are marked for restore.
1794 * @return bool True is safe to execute, false otherwise
1796 protected function execute_condition() {
1799 // First check course completion is enabled on this site
1800 if (empty($CFG->enablecompletion)) {
1801 // Disabled, don't restore course completion
1805 // Check it is included in the backup
1806 $fullpath = $this->task->get_taskbasepath();
1807 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1808 if (!file_exists($fullpath)) {
1809 // Not found, can't restore course completion
1813 // Check we are able to restore all backed up modules
1814 if ($this->task->is_missing_modules()) {
1818 // Finally check all modules within the backup are being restored.
1819 if ($this->task->is_excluding_activities()) {
1827 * Define the course completion structure
1829 * @return array Array of restore_path_element
1831 protected function define_structure() {
1833 // To know if we are including user completion info
1834 $userinfo = $this->get_setting_value('userscompletion');
1837 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1838 $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1839 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1842 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1843 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1851 * Process course completion criteria
1853 * @global moodle_database $DB
1854 * @param stdClass $data
1856 public function process_course_completion_criteria($data) {
1859 $data = (object)$data;
1860 $data->course = $this->get_courseid();
1862 // Apply the date offset to the time end field
1863 $data->timeend = $this->apply_date_offset($data->timeend);
1865 // Map the role from the criteria
1866 if (!empty($data->role)) {
1867 $data->role = $this->get_mappingid('role', $data->role);
1870 $skipcriteria = false;
1872 // If the completion criteria is for a module we need to map the module instance
1873 // to the new module id.
1874 if (!empty($data->moduleinstance) && !empty($data->module)) {
1875 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
1876 if (empty($data->moduleinstance)) {
1877 $skipcriteria = true;
1880 $data->module = null;
1881 $data->moduleinstance = null;
1884 // We backup the course shortname rather than the ID so that we can match back to the course
1885 if (!empty($data->courseinstanceshortname)) {
1886 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1887 if (!$courseinstanceid) {
1888 $skipcriteria = true;
1891 $courseinstanceid = null;
1893 $data->courseinstance = $courseinstanceid;
1895 if (!$skipcriteria) {
1897 'course' => $data->course,
1898 'criteriatype' => $data->criteriatype,
1899 'enrolperiod' => $data->enrolperiod,
1900 'courseinstance' => $data->courseinstance,
1901 'module' => $data->module,
1902 'moduleinstance' => $data->moduleinstance,
1903 'timeend' => $data->timeend,
1904 'gradepass' => $data->gradepass,
1905 'role' => $data->role
1907 $newid = $DB->insert_record('course_completion_criteria', $params);
1908 $this->set_mapping('course_completion_criteria', $data->id, $newid);
1913 * Processes course compltion criteria complete records
1915 * @global moodle_database $DB
1916 * @param stdClass $data
1918 public function process_course_completion_crit_compl($data) {
1921 $data = (object)$data;
1923 // This may be empty if criteria could not be restored
1924 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
1926 $data->course = $this->get_courseid();
1927 $data->userid = $this->get_mappingid('user', $data->userid);
1929 if (!empty($data->criteriaid) && !empty($data->userid)) {
1931 'userid' => $data->userid,
1932 'course' => $data->course,
1933 'criteriaid' => $data->criteriaid,
1934 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1936 if (isset($data->gradefinal)) {
1937 $params['gradefinal'] = $data->gradefinal;
1939 if (isset($data->unenroled)) {
1940 $params['unenroled'] = $data->unenroled;
1942 if (isset($data->deleted)) {
1943 $params['deleted'] = $data->deleted;
1945 $DB->insert_record('course_completion_crit_compl', $params);
1950 * Process course completions
1952 * @global moodle_database $DB
1953 * @param stdClass $data
1955 public function process_course_completions($data) {
1958 $data = (object)$data;
1960 $data->course = $this->get_courseid();
1961 $data->userid = $this->get_mappingid('user', $data->userid);
1963 if (!empty($data->userid)) {
1965 'userid' => $data->userid,
1966 'course' => $data->course,
1967 'deleted' => $data->deleted,
1968 'timenotified' => $this->apply_date_offset($data->timenotified),
1969 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1970 'timestarted' => $this->apply_date_offset($data->timestarted),
1971 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1972 'reaggregate' => $data->reaggregate
1974 $DB->insert_record('course_completions', $params);
1979 * Process course completion notification records.
1981 * Note: As of Moodle 2.0 this table is not being used however it has been
1982 * left in in the hopes that one day the functionality there will be completed
1984 * @global moodle_database $DB
1985 * @param stdClass $data
1987 public function process_course_completion_notify($data) {
1990 $data = (object)$data;
1992 $data->course = $this->get_courseid();
1993 if (!empty($data->role)) {
1994 $data->role = $this->get_mappingid('role', $data->role);
1998 'course' => $data->course,
1999 'role' => $data->role,
2000 'message' => $data->message,
2001 'timesent' => $this->apply_date_offset($data->timesent),
2003 $DB->insert_record('course_completion_notify', $params);
2007 * Process course completion aggregate methods
2009 * @global moodle_database $DB
2010 * @param stdClass $data
2012 public function process_course_completion_aggr_methd($data) {
2015 $data = (object)$data;
2017 $data->course = $this->get_courseid();
2019 // Only create the course_completion_aggr_methd records if
2020 // the target course has not them defined. MDL-28180
2021 if (!$DB->record_exists('course_completion_aggr_methd', array(
2022 'course' => $data->course,
2023 'criteriatype' => $data->criteriatype))) {
2025 'course' => $data->course,
2026 'criteriatype' => $data->criteriatype,
2027 'method' => $data->method,
2028 'value' => $data->value,
2030 $DB->insert_record('course_completion_aggr_methd', $params);
2037 * This structure step restores course logs (cmid = 0), delegating
2038 * the hard work to the corresponding {@link restore_logs_processor} passing the
2039 * collection of {@link restore_log_rule} rules to be observed as they are defined
2040 * by the task. Note this is only executed based in the 'logs' setting.
2042 * NOTE: This is executed by final task, to have all the activities already restored
2044 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2045 * records are. There are others like 'calendar' and 'upload' that will be handled
2048 * NOTE: All the missing actions (not able to be restored) are sent to logs for
2049 * debugging purposes
2051 class restore_course_logs_structure_step extends restore_structure_step {
2054 * Conditionally decide if this step should be executed.
2056 * This function checks the following parameter:
2058 * 1. the course/logs.xml file exists
2060 * @return bool true is safe to execute, false otherwise
2062 protected function execute_condition() {
2064 // Check it is included in the backup
2065 $fullpath = $this->task->get_taskbasepath();
2066 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2067 if (!file_exists($fullpath)) {
2068 // Not found, can't restore course logs
2075 protected function define_structure() {
2079 // Simple, one plain level of information contains them
2080 $paths[] = new restore_path_element('log', '/logs/log');
2085 protected function process_log($data) {
2088 $data = (object)($data);
2090 $data->time = $this->apply_date_offset($data->time);
2091 $data->userid = $this->get_mappingid('user', $data->userid);
2092 $data->course = $this->get_courseid();
2095 // For any reason user wasn't remapped ok, stop processing this
2096 if (empty($data->userid)) {
2100 // Everything ready, let's delegate to the restore_logs_processor
2102 // Set some fixed values that will save tons of DB requests
2104 'course' => $this->get_courseid());
2105 // Get instance and process log record
2106 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2108 // If we have data, insert it, else something went wrong in the restore_logs_processor
2110 $DB->insert_record('log', $data);
2116 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2117 * sharing its same structure but modifying the way records are handled
2119 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2121 protected function process_log($data) {
2124 $data = (object)($data);
2126 $data->time = $this->apply_date_offset($data->time);
2127 $data->userid = $this->get_mappingid('user', $data->userid);
2128 $data->course = $this->get_courseid();
2129 $data->cmid = $this->task->get_moduleid();
2131 // For any reason user wasn't remapped ok, stop processing this
2132 if (empty($data->userid)) {
2136 // Everything ready, let's delegate to the restore_logs_processor
2138 // Set some fixed values that will save tons of DB requests
2140 'course' => $this->get_courseid(),
2141 'course_module' => $this->task->get_moduleid(),
2142 $this->task->get_modulename() => $this->task->get_activityid());
2143 // Get instance and process log record
2144 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2146 // If we have data, insert it, else something went wrong in the restore_logs_processor
2148 $DB->insert_record('log', $data);
2155 * Defines the restore step for advanced grading methods attached to the activity module
2157 class restore_activity_grading_structure_step extends restore_structure_step {
2160 * This step is executed only if the grading file is present
2162 protected function execute_condition() {
2164 $fullpath = $this->task->get_taskbasepath();
2165 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2166 if (!file_exists($fullpath)) {
2175 * Declares paths in the grading.xml file we are interested in
2177 protected function define_structure() {
2180 $userinfo = $this->get_setting_value('userinfo');
2182 $paths[] = new restore_path_element('grading_area', '/areas/area');
2184 $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
2185 $paths[] = $definition;
2186 $this->add_plugin_structure('gradingform', $definition);
2189 $instance = new restore_path_element('grading_instance',
2190 '/areas/area/definitions/definition/instances/instance');
2191 $paths[] = $instance;
2192 $this->add_plugin_structure('gradingform', $instance);
2199 * Processes one grading area element
2201 * @param array $data element data
2203 protected function process_grading_area($data) {
2206 $task = $this->get_task();
2207 $data = (object)$data;
2209 $data->component = 'mod_'.$task->get_modulename();
2210 $data->contextid = $task->get_contextid();
2212 $newid = $DB->insert_record('grading_areas', $data);
2213 $this->set_mapping('grading_area', $oldid, $newid);
2217 * Processes one grading definition element
2219 * @param array $data element data
2221 protected function process_grading_definition($data) {
2224 $task = $this->get_task();
2225 $data = (object)$data;
2227 $data->areaid = $this->get_new_parentid('grading_area');
2228 $data->copiedfromid = null;
2229 $data->timecreated = time();
2230 $data->usercreated = $task->get_userid();
2231 $data->timemodified = $data->timecreated;
2232 $data->usermodified = $data->usercreated;
2234 $newid = $DB->insert_record('grading_definitions', $data);
2235 $this->set_mapping('grading_definition', $oldid, $newid, true);
2239 * Processes one grading form instance element
2241 * @param array $data element data
2243 protected function process_grading_instance($data) {
2246 $data = (object)$data;
2248 // new form definition id
2249 $newformid = $this->get_new_parentid('grading_definition');
2251 // get the name of the area we are restoring to
2252 $sql = "SELECT ga.areaname
2253 FROM {grading_definitions} gd
2254 JOIN {grading_areas} ga ON gd.areaid = ga.id
2256 $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
2258 // get the mapped itemid - the activity module is expected to define the mappings
2259 // for each gradable area
2260 $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
2263 $data->definitionid = $newformid;
2264 $data->raterid = $this->get_mappingid('user', $data->raterid);
2265 $data->itemid = $newitemid;
2267 $newid = $DB->insert_record('grading_instances', $data);
2268 $this->set_mapping('grading_instance', $oldid, $newid);
2272 * Final operations when the database records are inserted
2274 protected function after_execute() {
2275 // Add files embedded into the definition description
2276 $this->add_related_files('grading', 'description', 'grading_definition');
2282 * This structure step restores the grade items associated with one activity
2283 * All the grade items are made child of the "course" grade item but the original
2284 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
2285 * the complete gradebook (categories and calculations), that information is
2288 class restore_activity_grades_structure_step extends restore_structure_step {
2290 protected function define_structure() {
2293 $userinfo = $this->get_setting_value('userinfo');
2295 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
2296 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
2298 $paths[] = new restore_path_element('grade_grade',
2299 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
2304 protected function process_grade_item($data) {
2307 $data = (object)($data);
2308 $oldid = $data->id; // We'll need these later
2309 $oldparentid = $data->categoryid;
2310 $courseid = $this->get_courseid();
2312 // make sure top course category exists, all grade items will be associated
2313 // to it. Later, if restoring the whole gradebook, categories will be introduced
2314 $coursecat = grade_category::fetch_course_category($courseid);
2315 $coursecatid = $coursecat->id; // Get the categoryid to be used
2318 if (!empty($data->idnumber)) {
2319 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
2320 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
2321 // so the best is to keep the ones already in the gradebook
2322 // Potential problem: duplicates if same items are restored more than once. :-(
2323 // This needs to be fixed in some way (outcomes & activities with multiple items)
2324 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
2325 // In any case, verify always for uniqueness
2326 $sql = "SELECT cm.id
2327 FROM {course_modules} cm
2328 WHERE cm.course = :courseid AND
2329 cm.idnumber = :idnumber AND
2332 'courseid' => $courseid,
2333 'idnumber' => $data->idnumber,
2334 'cmid' => $this->task->get_moduleid()
2336 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
2337 $idnumber = $data->idnumber;
2342 $data->categoryid = $coursecatid;
2343 $data->courseid = $this->get_courseid();
2344 $data->iteminstance = $this->task->get_activityid();
2345 $data->idnumber = $idnumber;
2346 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
2347 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
2348 $data->timecreated = $this->apply_date_offset($data->timecreated);
2349 $data->timemodified = $this->apply_date_offset($data->timemodified);
2351 $gradeitem = new grade_item($data, false);
2352 $gradeitem->insert('restore');
2354 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
2355 $gradeitem->sortorder = $data->sortorder;
2356 $gradeitem->update('restore');
2358 // Set mapping, saving the original category id into parentitemid
2359 // gradebook restore (final task) will need it to reorganise items
2360 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
2363 protected function process_grade_grade($data) {
2364 $data = (object)($data);
2365 $olduserid = $data->userid;
2368 $data->itemid = $this->get_new_parentid('grade_item');
2370 $data->userid = $this->get_mappingid('user', $data->userid, null);
2371 if (!empty($data->userid)) {
2372 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
2373 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
2374 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
2375 $data->overridden = $this->apply_date_offset($data->overridden);
2377 $grade = new grade_grade($data, false);
2378 $grade->insert('restore');
2379 // no need to save any grade_grade mapping
2381 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
2386 * process activity grade_letters. Note that, while these are possible,
2387 * because grade_letters are contextid based, in proctice, only course
2388 * context letters can be defined. So we keep here this method knowing
2389 * it won't be executed ever. gradebook restore will restore course letters.
2391 protected function process_grade_letter($data) {
2394 $data = (object)$data;
2396 $data->contextid = $this->task->get_contextid();
2397 $newitemid = $DB->insert_record('grade_letters', $data);
2398 // no need to save any grade_letter mapping
2404 * This structure steps restores one instance + positions of one block
2405 * Note: Positions corresponding to one existing context are restored
2406 * here, but all the ones having unknown contexts are sent to backup_ids
2407 * for a later chance to be restored at the end (final task)
2409 class restore_block_instance_structure_step extends restore_structure_step {
2411 protected function define_structure() {
2415 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
2416 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
2421 public function process_block($data) {
2424 $data = (object)$data; // Handy
2425 $oldcontextid = $data->contextid;
2427 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
2429 // Look for the parent contextid
2430 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
2431 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
2434 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
2435 // If there is already one block of that type in the parent context
2436 // and the block is not multiple, stop processing
2437 // Use blockslib loader / method executor
2438 if (!$bi = block_instance($data->blockname)) {
2442 if (!$bi->instance_allow_multiple()) {
2443 if ($DB->record_exists_sql("SELECT bi.id
2444 FROM {block_instances} bi
2445 JOIN {block} b ON b.name = bi.blockname
2446 WHERE bi.parentcontextid = ?
2447 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
2452 // If there is already one block of that type in the parent context
2453 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
2456 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
2457 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
2458 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
2459 if ($birecs = $DB->get_records('block_instances', $params)) {
2460 foreach($birecs as $birec) {
2461 if ($birec->configdata == $data->configdata) {
2467 // Set task old contextid, blockid and blockname once we know them
2468 $this->task->set_old_contextid($oldcontextid);
2469 $this->task->set_old_blockid($oldid);
2470 $this->task->set_blockname($data->blockname);
2472 // Let's look for anything within configdata neededing processing
2473 // (nulls and uses of legacy file.php)
2474 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
2475 $configdata = (array)unserialize(base64_decode($data->configdata));
2476 foreach ($configdata as $attribute => $value) {
2477 if (in_array($attribute, $attrstotransform)) {
2478 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
2481 $data->configdata = base64_encode(serialize((object)$configdata));
2484 // Create the block instance
2485 $newitemid = $DB->insert_record('block_instances', $data);
2486 // Save the mapping (with restorefiles support)
2487 $this->set_mapping('block_instance', $oldid, $newitemid, true);
2488 // Create the block context
2489 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
2490 // Save the block contexts mapping and sent it to task
2491 $this->set_mapping('context', $oldcontextid, $newcontextid);
2492 $this->task->set_contextid($newcontextid);
2493 $this->task->set_blockid($newitemid);
2495 // Restore block fileareas if declared
2496 $component = 'block_' . $this->task->get_blockname();
2497 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
2498 $this->add_related_files($component, $filearea, null);
2501 // Process block positions, creating them or accumulating for final step
2502 foreach($positions as $position) {
2503 $position = (object)$position;
2504 $position->blockinstanceid = $newitemid; // The instance is always the restored one
2505 // If position is for one already mapped (known) contextid
2506 // process it now, creating the position
2507 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
2508 $position->contextid = $newpositionctxid;
2509 // Create the block position
2510 $DB->insert_record('block_positions', $position);
2512 // The position belongs to an unknown context, send it to backup_ids
2513 // to process them as part of the final steps of restore. We send the
2514 // whole $position object there, hence use the low level method.
2516 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
2523 * Structure step to restore common course_module information
2525 * This step will process the module.xml file for one activity, in order to restore
2526 * the corresponding information to the course_modules table, skipping various bits
2527 * of information based on CFG settings (groupings, completion...) in order to fullfill
2528 * all the reqs to be able to create the context to be used by all the rest of steps
2529 * in the activity restore task
2531 class restore_module_structure_step extends restore_structure_step {
2533 protected function define_structure() {
2538 $module = new restore_path_element('module', '/module');
2540 if ($CFG->enableavailability) {
2541 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
2544 // Apply for 'format' plugins optional paths at module level
2545 $this->add_plugin_structure('format', $module);
2547 // Apply for 'plagiarism' plugins optional paths at module level
2548 $this->add_plugin_structure('plagiarism', $module);
2553 protected function process_module($data) {
2556 $data = (object)$data;
2558 $this->task->set_old_moduleversion($data->version);
2560 $data->course = $this->task->get_courseid();
2561 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
2562 // Map section (first try by course_section mapping match. Useful in course and section restores)
2563 $data->section = $this->get_mappingid('course_section', $data->sectionid);
2564 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
2566 'course' => $this->get_courseid(),
2567 'section' => $data->sectionnumber);
2568 $data->section = $DB->get_field('course_sections', 'id', $params);
2570 if (!$data->section) { // sectionnumber failed, try to get first section in course
2572 'course' => $this->get_courseid());
2573 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
2575 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
2576 $sectionrec = array(
2577 'course' => $this->get_courseid(),
2579 $DB->insert_record('course_sections', $sectionrec); // section 0
2580 $sectionrec = array(
2581 'course' => $this->get_courseid(),
2583 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
2585 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
2586 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
2587 $data->groupmembersonly = 0;
2589 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
2590 $data->idnumber = '';
2592 if (empty($CFG->enablecompletion)) { // completion
2593 $data->completion = 0;
2594 $data->completiongradeitemnumber = null;
2595 $data->completionview = 0;
2596 $data->completionexpected = 0;
2598 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
2600 if (empty($CFG->enableavailability)) {
2601 $data->availablefrom = 0;
2602 $data->availableuntil = 0;
2603 $data->showavailability = 0;
2605 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
2606 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
2608 // Backups that did not include showdescription, set it to default 0
2609 // (this is not totally necessary as it has a db default, but just to
2611 if (!isset($data->showdescription)) {
2612 $data->showdescription = 0;
2614 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
2616 // course_module record ready, insert it
2617 $newitemid = $DB->insert_record('course_modules', $data);
2619 $this->set_mapping('course_module', $oldid, $newitemid);
2620 // set the new course_module id in the task
2621 $this->task->set_moduleid($newitemid);
2622 // we can now create the context safely
2623 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
2624 // set the new context id in the task
2625 $this->task->set_contextid($ctxid);
2626 // update sequence field in course_section
2627 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
2628 $sequence .= ',' . $newitemid;
2630 $sequence = $newitemid;
2632 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
2636 protected function process_availability($data) {
2637 $data = (object)$data;
2638 // Simply going to store the whole availability record now, we'll process
2639 // all them later in the final task (once all actvivities have been restored)
2640 // Let's call the low level one to be able to store the whole object
2641 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
2642 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
2647 * Structure step that will process the user activity completion
2648 * information if all these conditions are met:
2649 * - Target site has completion enabled ($CFG->enablecompletion)
2650 * - Activity includes completion info (file_exists)
2652 class restore_userscompletion_structure_step extends restore_structure_step {
2654 * To conditionally decide if this step must be executed
2655 * Note the "settings" conditions are evaluated in the
2656 * corresponding task. Here we check for other conditions
2657 * not being restore settings (files, site settings...)
2659 protected function execute_condition() {
2662 // Completion disabled in this site, don't execute
2663 if (empty($CFG->enablecompletion)) {
2667 // No user completion info found, don't execute
2668 $fullpath = $this->task->get_taskbasepath();
2669 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2670 if (!file_exists($fullpath)) {
2674 // Arrived here, execute the step
2678 protected function define_structure() {
2682 $paths[] = new restore_path_element('completion', '/completions/completion');
2687 protected function process_completion($data) {
2690 $data = (object)$data;
2692 $data->coursemoduleid = $this->task->get_moduleid();
2693 $data->userid = $this->get_mappingid('user', $data->userid);
2694 $data->timemodified = $this->apply_date_offset($data->timemodified);
2696 // Find the existing record
2697 $existing = $DB->get_record('course_modules_completion', array(
2698 'coursemoduleid' => $data->coursemoduleid,
2699 'userid' => $data->userid), 'id, timemodified');
2700 // Check we didn't already insert one for this cmid and userid
2701 // (there aren't supposed to be duplicates in that field, but
2702 // it was possible until MDL-28021 was fixed).
2704 // Update it to these new values, but only if the time is newer
2705 if ($existing->timemodified < $data->timemodified) {
2706 $data->id = $existing->id;
2707 $DB->update_record('course_modules_completion', $data);
2710 // Normal entry where it doesn't exist already
2711 $DB->insert_record('course_modules_completion', $data);
2717 * Abstract structure step, parent of all the activity structure steps. Used to suuport
2718 * the main <activity ...> tag and process it. Also provides subplugin support for
2721 abstract class restore_activity_structure_step extends restore_structure_step {
2723 protected function add_subplugin_structure($subplugintype, $element) {
2727 // Check the requested subplugintype is a valid one
2728 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
2729 if (!file_exists($subpluginsfile)) {
2730 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
2732 include($subpluginsfile);
2733 if (!array_key_exists($subplugintype, $subplugins)) {
2734 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
2736 // Get all the restore path elements, looking across all the subplugin dirs
2737 $subpluginsdirs = get_plugin_list($subplugintype);
2738 foreach ($subpluginsdirs as $name => $subpluginsdir) {
2739 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
2740 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
2741 if (file_exists($restorefile)) {
2742 require_once($restorefile);
2743 $restoresubplugin = new $classname($subplugintype, $name, $this);
2744 // Add subplugin paths to the step
2745 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
2751 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
2752 * have the parent task available for wrapping purposes (get course/context....)
2753 * @return restore_task
2755 public function get_task() {
2760 * Adds support for the 'activity' path that is common to all the activities
2761 * and will be processed globally here
2763 protected function prepare_activity_structure($paths) {
2765 $paths[] = new restore_path_element('activity', '/activity');
2771 * Process the activity path, informing the task about various ids, needed later
2773 protected function process_activity($data) {
2774 $data = (object)$data;
2775 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
2776 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
2777 $this->task->set_old_activityid($data->id); // Save old activityid in task
2781 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
2782 * and will adjust the new activity id (the instance) in various places
2784 protected function apply_activity_instance($newitemid) {
2787 $this->task->set_activityid($newitemid); // Save activity id in task
2788 // Apply the id to course_sections->instanceid
2789 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
2790 // Do the mapping for modulename, preparing it for files by oldcontext
2791 $modulename = $this->task->get_modulename();
2792 $oldid = $this->task->get_old_activityid();
2793 $this->set_mapping($modulename, $oldid, $newitemid, true);
2798 * Structure step in charge of creating/mapping all the qcats and qs
2799 * by parsing the questions.xml file and checking it against the
2800 * results calculated by {@link restore_process_categories_and_questions}
2801 * and stored in backup_ids_temp
2803 class restore_create_categories_and_questions extends restore_structure_step {
2805 protected function define_structure() {
2807 $category = new restore_path_element('question_category', '/question_categories/question_category');
2808 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
2809 $hint = new restore_path_element('question_hint',
2810 '/question_categories/question_category/questions/question/question_hints/question_hint');
2812 // Apply for 'qtype' plugins optional paths at question level
2813 $this->add_plugin_structure('qtype', $question);
2815 return array($category, $question, $hint);
2818 protected function process_question_category($data) {
2821 $data = (object)$data;
2824 // Check we have one mapping for this category
2825 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
2826 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
2829 // Check we have to create the category (newitemid = 0)
2830 if ($mapping->newitemid) {
2831 return; // newitemid != 0, this category is going to be mapped. Nothing to do
2834 // Arrived here, newitemid = 0, we need to create the category
2835 // we'll do it at parentitemid context, but for CONTEXT_MODULE
2836 // categories, that will be created at CONTEXT_COURSE and moved
2837 // to module context later when the activity is created
2838 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
2839 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
2841 $data->contextid = $mapping->parentitemid;
2843 // Let's create the question_category and save mapping
2844 $newitemid = $DB->insert_record('question_categories', $data);
2845 $this->set_mapping('question_category', $oldid, $newitemid);
2846 // Also annotate them as question_category_created, we need
2847 // that later when remapping parents
2848 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
2851 protected function process_question($data) {
2854 $data = (object)$data;
2857 // Check we have one mapping for this question
2858 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
2859 return; // No mapping = this question doesn't need to be created/mapped
2862 // Get the mapped category (cannot use get_new_parentid() because not
2863 // all the categories have been created, so it is not always available
2864 // Instead we get the mapping for the question->parentitemid because
2865 // we have loaded qcatids there for all parsed questions
2866 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
2868 // In the past, there were some very sloppy values of penalty. Fix them.
2869 if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
2870 $data->penalty = 0.3333333;
2872 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
2873 $data->penalty = 0.6666667;
2875 if ($data->penalty >= 1) {
2879 $data->timecreated = $this->apply_date_offset($data->timecreated);
2880 $data->timemodified = $this->apply_date_offset($data->timemodified);
2882 $userid = $this->get_mappingid('user', $data->createdby);
2883 $data->createdby = $userid ? $userid : $this->task->get_userid();
2885 $userid = $this->get_mappingid('user', $data->modifiedby);
2886 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
2888 // With newitemid = 0, let's create the question
2889 if (!$questionmapping->newitemid) {
2890 $newitemid = $DB->insert_record('question', $data);
2891 $this->set_mapping('question', $oldid, $newitemid);
2892 // Also annotate them as question_created, we need
2893 // that later when remapping parents (keeping the old categoryid as parentid)
2894 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
2896 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
2897 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
2898 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
2901 // Note, we don't restore any question files yet
2902 // as far as the CONTEXT_MODULE categories still
2903 // haven't their contexts to be restored to
2904 // The {@link restore_create_question_files}, executed in the final step
2905 // step will be in charge of restoring all the question files
2908 protected function process_question_hint($data) {
2911 $data = (object)$data;
2914 // Detect if the question is created or mapped
2915 $oldquestionid = $this->get_old_parentid('question');
2916 $newquestionid = $this->get_new_parentid('question');
2917 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
2919 // If the question has been created by restore, we need to create its question_answers too
2920 if ($questioncreated) {
2921 // Adjust some columns
2922 $data->questionid = $newquestionid;
2924 $newitemid = $DB->insert_record('question_hints', $data);
2926 // The question existed, we need to map the existing question_hints
2928 // Look in question_hints by hint text matching
2930 FROM {question_hints}
2931 WHERE questionid = ?
2932 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
2933 $params = array($newquestionid, $data->hint);
2934 $newitemid = $DB->get_field_sql($sql, $params);
2935 // If we haven't found the newitemid, something has gone really wrong, question in DB
2936 // is missing hints, exception
2938 $info = new stdClass();
2939 $info->filequestionid = $oldquestionid;
2940 $info->dbquestionid = $newquestionid;
2941 $info->hint = $data->hint;
2942 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
2945 // Create mapping (I'm not sure if this is really needed?)
2946 $this->set_mapping('question_hint', $oldid, $newitemid);
2949 protected function after_execute() {
2952 // First of all, recode all the created question_categories->parent fields
2953 $qcats = $DB->get_records('backup_ids_temp', array(
2954 'backupid' => $this->get_restoreid(),
2955 'itemname' => 'question_category_created'));
2956 foreach ($qcats as $qcat) {
2958 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
2959 // Get new parent (mapped or created, so we look in quesiton_category mappings)
2960 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2961 'backupid' => $this->get_restoreid(),
2962 'itemname' => 'question_category',
2963 'itemid' => $dbcat->parent))) {
2964 // contextids must match always, as far as we always include complete qbanks, just check it
2965 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
2966 if ($dbcat->contextid == $newparentctxid) {
2967 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
2969 $newparent = 0; // No ctx match for both cats, no parent relationship
2972 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
2974 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
2978 // Now, recode all the created question->parent fields
2979 $qs = $DB->get_records('backup_ids_temp', array(
2980 'backupid' => $this->get_restoreid(),
2981 'itemname' => 'question_created'));
2982 foreach ($qs as $q) {
2984 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
2985 // Get new parent (mapped or created, so we look in question mappings)
2986 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2987 'backupid' => $this->get_restoreid(),
2988 'itemname' => 'question',
2989 'itemid' => $dbq->parent))) {
2990 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
2994 // Note, we don't restore any question files yet
2995 // as far as the CONTEXT_MODULE categories still
2996 // haven't their contexts to be restored to
2997 // The {@link restore_create_question_files}, executed in the final step
2998 // step will be in charge of restoring all the question files
3003 * Execution step that will move all the CONTEXT_MODULE question categories
3004 * created at early stages of restore in course context (because modules weren't
3005 * created yet) to their target module (matching by old-new-contextid mapping)
3007 class restore_move_module_questions_categories extends restore_execution_step {
3009 protected function define_execution() {
3012 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
3013 foreach ($contexts as $contextid => $contextlevel) {
3014 // Only if context mapping exists (i.e. the module has been restored)
3015 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
3016 // Update all the qcats having their parentitemid set to the original contextid
3017 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
3018 FROM {backup_ids_temp}
3020 AND itemname = 'question_category'
3021 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
3022 foreach ($modulecats as $modulecat) {
3023 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
3024 // And set new contextid also in question_category mapping (will be
3025 // used by {@link restore_create_question_files} later
3026 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
3034 * Execution step that will create all the question/answers/qtype-specific files for the restored
3035 * questions. It must be executed after {@link restore_move_module_questions_categories}
3036 * because only then each question is in its final category and only then the
3037 * context can be determined
3039 * TODO: Improve this. Instead of looping over each question, it can be reduced to
3040 * be done by contexts (this will save a huge ammount of queries)
3042 class restore_create_question_files extends restore_execution_step {
3044 protected function define_execution() {
3047 // Let's process only created questions
3048 $questionsrs = $DB->get_recordset_sql("SELECT bi.itemid, bi.newitemid, bi.parentitemid, q.qtype
3049 FROM {backup_ids_temp} bi
3050 JOIN {question} q ON q.id = bi.newitemid
3051 WHERE bi.backupid = ?
3052 AND bi.itemname = 'question_created'", array($this->get_restoreid()));
3053 foreach ($questionsrs as $question) {
3054 // Get question_category mapping, it contains the target context for the question
3055 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $question->parentitemid)) {
3056 // Something went really wrong, cannot find the question_category for the question
3057 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
3060 // Calculate source and target contexts
3061 $oldctxid = $qcatmapping->info->contextid;
3062 $newctxid = $qcatmapping->parentitemid;
3064 // Add common question files (question and question_answer ones)
3065 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
3066 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3067 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
3068 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3069 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
3070 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
3071 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
3072 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
3073 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
3074 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true);
3075 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
3076 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3077 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
3078 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3079 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
3080 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3081 // Add qtype dependent files
3082 $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
3083 foreach ($components as $component => $fileareas) {
3084 foreach ($fileareas as $filearea => $mapping) {
3085 // Use itemid only if mapping is question_created
3086 $itemid = ($mapping == 'question_created') ? $question->itemid : null;
3087 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
3088 $oldctxid, $this->task->get_userid(), $mapping, $itemid, $newctxid, true);
3092 $questionsrs->close();
3098 * Try to restore aliases and references to external files.
3100 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
3101 * We expect that all regular (non-alias) files have already been restored. Make sure
3102 * there is no restore step executed after this one that would call send_files_to_pool() again.
3104 * You may notice we have hardcoded support for Server files, Legacy course files
3105 * and user Private files here at the moment. This could be eventually replaced with a set of
3106 * callbacks in the future if needed.
3108 * @copyright 2012 David Mudrak <david@moodle.com>
3109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3111 class restore_process_file_aliases_queue extends restore_execution_step {
3114 * What to do when this step is executed.
3116 protected function define_execution() {
3119 $this->log('processing file aliases queue', backup::LOG_INFO);
3121 $fs = get_file_storage();
3124 $rs = $DB->get_recordset('backup_ids_temp',
3125 array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'),
3128 // Iterate over aliases in the queue.
3129 foreach ($rs as $record) {
3130 $info = unserialize(base64_decode($record->info));
3132 // Try to pick a repository instance that should serve the alias.
3133 $repository = $this->choose_repository($info);
3135 if (is_null($repository)) {
3136 $this->notify_failure($info, 'unable to find a matching repository instance');
3140 if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') {
3141 // Aliases to Server files and Legacy course files may refer to a file
3142 // contained in the backup file or to some existing file (if we are on the
3145 $reference = file_storage::unpack_reference($info->oldfile->reference);
3146 } catch (Exception $e) {
3147 $this->notify_failure($info, 'invalid reference field format');
3151 // Let's see if the referred source file was also included in the backup.
3152 $candidates = $DB->get_recordset('backup_files_temp', array(
3153 'backupid' => $this->get_restoreid(),
3154 'contextid' => $reference['contextid'],
3155 'component' => $reference['component'],
3156 'filearea' => $reference['filearea'],
3157 'itemid' => $reference['itemid'],
3158 ), '', 'info, newcontextid, newitemid');
3162 foreach ($candidates as $candidate) {
3163 $candidateinfo = unserialize(base64_decode($candidate->info));
3164 if ($candidateinfo->filename === $reference['filename']
3165 and $candidateinfo->filepath === $reference['filepath']
3166 and !is_null($candidate->newcontextid)
3167 and !is_null($candidate->newitemid) ) {
3168 $source = $candidateinfo;
3169 $source->contextid = $candidate->newcontextid;
3170 $source->itemid = $candidate->newitemid;
3174 $candidates->close();
3177 // We have an alias that refers to another file also included in
3178 // the backup. Let us change the reference field so that it refers
3179 // to the restored copy of the original file.
3180 $reference = file_storage::pack_reference($source);
3182 // Send the new alias to the filepool.
3183 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
3184 $this->notify_success($info);
3188 // This is a reference to some moodle file that was not contained in the backup
3189 // file. If we are restoring to the same site, keep the reference untouched
3190 // and restore the alias as is if the referenced file exists.
3191 if ($this->task->is_samesite()) {
3192 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
3193 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
3194 $reference = file_storage::pack_reference($reference);
3195 $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
3196 $this->notify_success($info);
3199 $this->notify_failure($info, 'referenced file not found');
3203 // If we are at other site, we can't restore this alias.
3205 $this->notify_failure($info, 'referenced file not included');
3210 } else if ($info->oldfile->repositorytype === 'user') {
3211 if ($this->task->is_samesite()) {
3212 // For aliases to user Private files at the same site, we have a chance to check
3213 // if the referenced file still exists.
3215 $reference = file_storage::unpack_reference($info->oldfile->reference);
3216 } catch (Exception $e) {
3217 $this->notify_failure($info, 'invalid reference field format');
3220 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
3221 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
3222 $reference = file_storage::pack_reference($reference);