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 = context_course::instance($this->get_courseid())->id;
46 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
47 // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
48 $itemid = $this->task->get_old_system_contextid();
49 $newitemid = context_system::instance()->id;
50 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
51 // Create the old-course-id to new-course-id mapping, we need that available since the beginning
52 $itemid = $this->task->get_old_courseid();
53 $newitemid = $this->get_courseid();
54 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
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 $progress = $this->task->get_progress();
69 $progress->start_progress('Deleting backup dir');
70 backup_helper::delete_old_backup_dirs(strtotime('-1 week'), $progress); // Delete > 1 week old temp dirs.
71 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
72 backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir
74 $progress->end_progress();
79 * Restore calculated grade items, grade categories etc
81 class restore_gradebook_structure_step extends restore_structure_step {
84 * To conditionally decide if this step must be executed
85 * Note the "settings" conditions are evaluated in the
86 * corresponding task. Here we check for other conditions
87 * not being restore settings (files, site settings...)
89 protected function execute_condition() {
92 if ($this->get_courseid() == SITEID) {
96 // No gradebook info found, don't execute
97 $fullpath = $this->task->get_taskbasepath();
98 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
99 if (!file_exists($fullpath)) {
103 // Some module present in backup file isn't available to restore
104 // in this site, don't execute
105 if ($this->task->is_missing_modules()) {
109 // Some activity has been excluded to be restored, don't execute
110 if ($this->task->is_excluding_activities()) {
114 // There should only be one grade category (the 1 associated with the course itself)
115 // If other categories already exist we're restoring into an existing course.
116 // Restoring categories into a course with an existing category structure is unlikely to go well
117 $category = new stdclass();
118 $category->courseid = $this->get_courseid();
119 $catcount = $DB->count_records('grade_categories', (array)$category);
124 // Arrived here, execute the step
128 protected function define_structure() {
130 $userinfo = $this->task->get_setting_value('users');
132 $paths[] = new restore_path_element('gradebook', '/gradebook');
133 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
134 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
136 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
138 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
139 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
144 protected function process_gradebook($data) {
145 // For non-merge restore types:
146 // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
147 $target = $this->get_task()->get_target();
148 if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) {
149 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
151 if (!empty($data['calculations_freeze'])) {
152 if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING ||
153 $target == backup::TARGET_EXISTING_DELETING) {
154 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
159 protected function process_grade_item($data) {
162 $data = (object)$data;
165 $data->course = $this->get_courseid();
167 $data->courseid = $this->get_courseid();
169 if ($data->itemtype=='manual') {
170 // manual grade items store category id in categoryid
171 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
172 // if mapping failed put in course's grade category
173 if (NULL == $data->categoryid) {
174 $coursecat = grade_category::fetch_course_category($this->get_courseid());
175 $data->categoryid = $coursecat->id;
177 } else if ($data->itemtype=='course') {
178 // course grade item stores their category id in iteminstance
179 $coursecat = grade_category::fetch_course_category($this->get_courseid());
180 $data->iteminstance = $coursecat->id;
181 } else if ($data->itemtype=='category') {
182 // category grade items store their category id in iteminstance
183 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
185 throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
188 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
189 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
191 $data->locktime = $this->apply_date_offset($data->locktime);
192 $data->timecreated = $this->apply_date_offset($data->timecreated);
193 $data->timemodified = $this->apply_date_offset($data->timemodified);
195 $coursecategory = $newitemid = null;
196 //course grade item should already exist so updating instead of inserting
197 if($data->itemtype=='course') {
198 //get the ID of the already created grade item
199 $gi = new stdclass();
200 $gi->courseid = $this->get_courseid();
201 $gi->itemtype = $data->itemtype;
203 //need to get the id of the grade_category that was automatically created for the course
204 $category = new stdclass();
205 $category->courseid = $this->get_courseid();
206 $category->parent = null;
207 //course category fullname starts out as ? but may be edited
208 //$category->fullname = '?';
209 $coursecategory = $DB->get_record('grade_categories', (array)$category);
210 $gi->iteminstance = $coursecategory->id;
212 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
213 if (!empty($existinggradeitem)) {
214 $data->id = $newitemid = $existinggradeitem->id;
215 $DB->update_record('grade_items', $data);
217 } else if ($data->itemtype == 'manual') {
218 // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
220 'itemtype' => $data->itemtype,
221 'courseid' => $data->courseid,
222 'itemname' => $data->itemname,
223 'categoryid' => $data->categoryid,
225 $newitemid = $DB->get_field('grade_items', 'id', $gi);
228 if (empty($newitemid)) {
229 //in case we found the course category but still need to insert the course grade item
230 if ($data->itemtype=='course' && !empty($coursecategory)) {
231 $data->iteminstance = $coursecategory->id;
234 $newitemid = $DB->insert_record('grade_items', $data);
236 $this->set_mapping('grade_item', $oldid, $newitemid);
239 protected function process_grade_grade($data) {
242 $data = (object)$data;
244 $olduserid = $data->userid;
246 $data->itemid = $this->get_new_parentid('grade_item');
248 $data->userid = $this->get_mappingid('user', $data->userid, null);
249 if (!empty($data->userid)) {
250 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
251 $data->locktime = $this->apply_date_offset($data->locktime);
252 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
253 $data->overridden = $this->apply_date_offset($data->overridden);
254 $data->timecreated = $this->apply_date_offset($data->timecreated);
255 $data->timemodified = $this->apply_date_offset($data->timemodified);
257 $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
259 $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
260 $this->log($message, backup::LOG_DEBUG);
262 $newitemid = $DB->insert_record('grade_grades', $data);
263 $this->set_mapping('grade_grades', $oldid, $newitemid);
266 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
267 $this->log($message, backup::LOG_DEBUG);
271 protected function process_grade_category($data) {
274 $data = (object)$data;
277 $data->course = $this->get_courseid();
278 $data->courseid = $data->course;
280 $data->timecreated = $this->apply_date_offset($data->timecreated);
281 $data->timemodified = $this->apply_date_offset($data->timemodified);
284 //no parent means a course level grade category. That may have been created when the course was created
285 if(empty($data->parent)) {
286 //parent was being saved as 0 when it should be null
287 $data->parent = null;
289 //get the already created course level grade category
290 $category = new stdclass();
291 $category->courseid = $this->get_courseid();
292 $category->parent = null;
294 $coursecategory = $DB->get_record('grade_categories', (array)$category);
295 if (!empty($coursecategory)) {
296 $data->id = $newitemid = $coursecategory->id;
297 $DB->update_record('grade_categories', $data);
301 // Add a warning about a removed setting.
302 if (!empty($data->aggregatesubcats)) {
303 set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
306 //need to insert a course category
307 if (empty($newitemid)) {
308 $newitemid = $DB->insert_record('grade_categories', $data);
310 $this->set_mapping('grade_category', $oldid, $newitemid);
312 protected function process_grade_letter($data) {
315 $data = (object)$data;
318 $data->contextid = context_course::instance($this->get_courseid())->id;
320 $gradeletter = (array)$data;
321 unset($gradeletter['id']);
322 if (!$DB->record_exists('grade_letters', $gradeletter)) {
323 $newitemid = $DB->insert_record('grade_letters', $data);
325 $newitemid = $data->id;
328 $this->set_mapping('grade_letter', $oldid, $newitemid);
330 protected function process_grade_setting($data) {
333 $data = (object)$data;
336 $data->courseid = $this->get_courseid();
338 $target = $this->get_task()->get_target();
339 if ($data->name == 'minmaxtouse' &&
340 ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) {
341 // We never restore minmaxtouse during merge.
345 if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
346 $newitemid = $DB->insert_record('grade_settings', $data);
348 $newitemid = $data->id;
351 if (!empty($oldid)) {
352 // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
353 $this->set_mapping('grade_setting', $oldid, $newitemid);
358 * put all activity grade items in the correct grade category and mark all for recalculation
360 protected function after_execute() {
364 'backupid' => $this->get_restoreid(),
365 'itemname' => 'grade_item'//,
366 //'itemid' => $itemid
368 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
370 // We need this for calculation magic later on.
374 foreach($rs as $grade_item_backup) {
376 // Store the oldid with the new id.
377 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
379 $updateobj = new stdclass();
380 $updateobj->id = $grade_item_backup->newitemid;
382 //if this is an activity grade item that needs to be put back in its correct category
383 if (!empty($grade_item_backup->parentitemid)) {
384 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
385 if (!is_null($oldcategoryid)) {
386 $updateobj->categoryid = $oldcategoryid;
387 $DB->update_record('grade_items', $updateobj);
390 //mark course and category items as needing to be recalculated
391 $updateobj->needsupdate=1;
392 $DB->update_record('grade_items', $updateobj);
398 // We need to update the calculations for calculated grade items that may reference old
399 // grade item ids using ##gi\d+##.
400 // $mappings can be empty, use 0 if so (won't match ever)
401 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
402 $sql = "SELECT gi.id, gi.calculation
403 FROM {grade_items} gi
404 WHERE gi.id {$sql} AND
405 calculation IS NOT NULL";
406 $rs = $DB->get_recordset_sql($sql, $params);
407 foreach ($rs as $gradeitem) {
408 // Collect all of the used grade item id references
409 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
410 // This calculation doesn't reference any other grade items... EASY!
413 // For this next bit we are going to do the replacement of id's in two steps:
414 // 1. We will replace all old id references with a special mapping reference.
415 // 2. We will replace all mapping references with id's
416 // Why do we do this?
417 // Because there potentially there will be an overlap of ids within the query and we
418 // we substitute the wrong id.. safest way around this is the two step system
419 $calculationmap = array();
421 foreach ($matches[1] as $match) {
422 // Check that the old id is known to us, if not it was broken to begin with and will
423 // continue to be broken.
424 if (!array_key_exists($match, $mappings)) {
427 // Our special mapping key
428 $mapping = '##MAPPING'.$mapcount.'##';
429 // The old id that exists within the calculation now
430 $oldid = '##gi'.$match.'##';
431 // The new id that we want to replace the old one with.
432 $newid = '##gi'.$mappings[$match].'##';
433 // Replace in the special mapping key
434 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
435 // And record the mapping
436 $calculationmap[$mapping] = $newid;
439 // Iterate all special mappings for this calculation and replace in the new id's
440 foreach ($calculationmap as $mapping => $newid) {
441 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
443 // Update the calculation now that its being remapped
444 $DB->update_record('grade_items', $gradeitem);
448 // Need to correct the grade category path and parent
450 'courseid' => $this->get_courseid()
453 $rs = $DB->get_recordset('grade_categories', $conditions);
454 // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
455 foreach ($rs as $gc) {
456 if (!empty($gc->parent)) {
457 $grade_category = new stdClass();
458 $grade_category->id = $gc->id;
459 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
460 $DB->update_record('grade_categories', $grade_category);
465 // Now we can rebuild all the paths
466 $rs = $DB->get_recordset('grade_categories', $conditions);
467 foreach ($rs as $gc) {
468 $grade_category = new stdClass();
469 $grade_category->id = $gc->id;
470 $grade_category->path = grade_category::build_path($gc);
471 $grade_category->depth = substr_count($grade_category->path, '/') - 1;
472 $DB->update_record('grade_categories', $grade_category);
476 // Check what to do with the minmaxtouse setting.
477 $this->check_minmaxtouse();
479 // Freeze gradebook calculations if needed.
480 $this->gradebook_calculation_freeze();
482 // Restore marks items as needing update. Update everything now.
483 grade_regrade_final_grades($this->get_courseid());
487 * Freeze gradebook calculation if needed.
489 * This is similar to various upgrade scripts that check if the freeze is needed.
491 protected function gradebook_calculation_freeze() {
493 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
494 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
495 $backupbuild = (int)$matches[1];
497 // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
498 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) {
499 require_once($CFG->libdir . '/db/upgradelib.php');
500 upgrade_extra_credit_weightoverride($this->get_courseid());
502 // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
503 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) {
504 require_once($CFG->libdir . '/db/upgradelib.php');
505 upgrade_calculated_grade_items($this->get_courseid());
510 * Checks what should happen with the course grade setting minmaxtouse.
512 * This is related to the upgrade step at the time the setting was added.
517 protected function check_minmaxtouse() {
519 require_once($CFG->libdir . '/gradelib.php');
521 $userinfo = $this->task->get_setting_value('users');
522 $settingname = 'minmaxtouse';
523 $courseid = $this->get_courseid();
524 $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
525 $version28start = 2014111000.00;
526 $version28last = 2014111006.05;
527 $version29start = 2015051100.00;
528 $version29last = 2015060400.02;
530 $target = $this->get_task()->get_target();
531 if ($minmaxtouse === false &&
532 ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
533 // The setting was not found because this setting did not exist at the time the backup was made.
534 // And we are not restoring as merge, in which case we leave the course as it was.
535 $version = $this->get_task()->get_info()->moodle_version;
537 if ($version < $version28start) {
538 // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
539 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
540 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
543 } else if (($version >= $version28start && $version < $version28last) ||
544 ($version >= $version29start && $version < $version29last)) {
545 // They should be using grade_grade when the course has inconsistencies.
548 FROM {grade_items} gi
549 JOIN {grade_grades} gg
551 WHERE gi.courseid = ?
552 AND (gi.itemtype != ? AND gi.itemtype != ?)
553 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
555 // The course can only have inconsistencies when we restore the user info,
556 // we do not need to act on existing grades that were not restored as part of this backup.
557 if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
559 // Display the notice as we do during upgrade.
560 set_config('show_min_max_grades_changed_' . $courseid, 1);
562 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
563 // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
564 // If they are using the site-wide grade_grade setting, we only want to notice them.
565 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
570 // This should never happen because from now on minmaxtouse is always saved in backups.
577 * Step in charge of restoring the grade history of a course.
579 * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
580 * we do not want to restore the history if the gradebook and its content has not been
581 * restored. At least for now.
583 class restore_grade_history_structure_step extends restore_structure_step {
585 protected function execute_condition() {
588 if ($this->get_courseid() == SITEID) {
592 // No gradebook info found, don't execute.
593 $fullpath = $this->task->get_taskbasepath();
594 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
595 if (!file_exists($fullpath)) {
599 // Some module present in backup file isn't available to restore in this site, don't execute.
600 if ($this->task->is_missing_modules()) {
604 // Some activity has been excluded to be restored, don't execute.
605 if ($this->task->is_excluding_activities()) {
609 // There should only be one grade category (the 1 associated with the course itself).
610 $category = new stdclass();
611 $category->courseid = $this->get_courseid();
612 $catcount = $DB->count_records('grade_categories', (array)$category);
617 // Arrived here, execute the step.
621 protected function define_structure() {
625 $userinfo = $this->get_setting_value('users');
626 $history = $this->get_setting_value('grade_histories');
628 if ($userinfo && $history) {
629 $paths[] = new restore_path_element('grade_grade',
630 '/grade_history/grade_grades/grade_grade');
636 protected function process_grade_grade($data) {
639 $data = (object)($data);
640 $olduserid = $data->userid;
643 $data->userid = $this->get_mappingid('user', $data->userid, null);
644 if (!empty($data->userid)) {
645 // Do not apply the date offsets as this is history.
646 $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
647 $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
648 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
649 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
650 $DB->insert_record('grade_grades_history', $data);
652 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
653 $this->log($message, backup::LOG_DEBUG);
660 * decode all the interlinks present in restored content
661 * relying 100% in the restore_decode_processor that handles
662 * both the contents to modify and the rules to be applied
664 class restore_decode_interlinks extends restore_execution_step {
666 protected function define_execution() {
667 // Get the decoder (from the plan)
668 $decoder = $this->task->get_decoder();
669 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
670 // And launch it, everything will be processed
676 * first, ensure that we have no gaps in section numbers
677 * and then, rebuid the course cache
679 class restore_rebuild_course_cache extends restore_execution_step {
681 protected function define_execution() {
684 // Although there is some sort of auto-recovery of missing sections
685 // present in course/formats... here we check that all the sections
686 // from 0 to MAX(section->section) exist, creating them if necessary
687 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
688 // Iterate over all sections
689 for ($i = 0; $i <= $maxsection; $i++) {
690 // If the section $i doesn't exist, create it
691 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
693 'course' => $this->get_courseid(),
695 $DB->insert_record('course_sections', $sectionrec); // missing section created
699 // Rebuild cache now that all sections are in place
700 rebuild_course_cache($this->get_courseid());
701 cache_helper::purge_by_event('changesincourse');
702 cache_helper::purge_by_event('changesincoursecat');
707 * Review all the tasks having one after_restore method
708 * executing it to perform some final adjustments of information
709 * not available when the task was executed.
711 class restore_execute_after_restore extends restore_execution_step {
713 protected function define_execution() {
715 // Simply call to the execute_after_restore() method of the task
716 // that always is the restore_final_task
717 $this->task->launch_execute_after_restore();
723 * Review all the (pending) block positions in backup_ids, matching by
724 * contextid, creating positions as needed. This is executed by the
725 * final task, once all the contexts have been created
727 class restore_review_pending_block_positions extends restore_execution_step {
729 protected function define_execution() {
732 // Get all the block_position objects pending to match
733 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
734 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
735 // Process block positions, creating them or accumulating for final step
736 foreach($rs as $posrec) {
737 // Get the complete position object out of the info field.
738 $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
739 // If position is for one already mapped (known) contextid
740 // process it now, creating the position, else nothing to
741 // do, position finally discarded
742 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
743 $position->contextid = $newctx->newitemid;
744 // Create the block position
745 $DB->insert_record('block_positions', $position);
754 * Updates the availability data for course modules and sections.
756 * Runs after the restore of all course modules, sections, and grade items has
757 * completed. This is necessary in order to update IDs that have changed during
760 * @package core_backup
761 * @copyright 2014 The Open University
762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
764 class restore_update_availability extends restore_execution_step {
766 protected function define_execution() {
769 // Note: This code runs even if availability is disabled when restoring.
770 // That will ensure that if you later turn availability on for the site,
771 // there will be no incorrect IDs. (It doesn't take long if the restored
772 // data does not contain any availability information.)
774 // Get modinfo with all data after resetting cache.
775 rebuild_course_cache($this->get_courseid(), true);
776 $modinfo = get_fast_modinfo($this->get_courseid());
778 // Get the date offset for this restore.
779 $dateoffset = $this->apply_date_offset(1) - 1;
781 // Update all sections that were restored.
782 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
783 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
784 $sectionsbyid = null;
785 foreach ($rs as $rec) {
786 if (is_null($sectionsbyid)) {
787 $sectionsbyid = array();
788 foreach ($modinfo->get_section_info_all() as $section) {
789 $sectionsbyid[$section->id] = $section;
792 if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
793 // If the section was not fully restored for some reason
794 // (e.g. due to an earlier error), skip it.
795 $this->get_logger()->process('Section not fully restored: id ' .
796 $rec->newitemid, backup::LOG_WARNING);
799 $section = $sectionsbyid[$rec->newitemid];
800 if (!is_null($section->availability)) {
801 $info = new \core_availability\info_section($section);
802 $info->update_after_restore($this->get_restoreid(),
803 $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
808 // Update all modules that were restored.
809 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
810 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
811 foreach ($rs as $rec) {
812 if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
813 // If the module was not fully restored for some reason
814 // (e.g. due to an earlier error), skip it.
815 $this->get_logger()->process('Module not fully restored: id ' .
816 $rec->newitemid, backup::LOG_WARNING);
819 $cm = $modinfo->get_cm($rec->newitemid);
820 if (!is_null($cm->availability)) {
821 $info = new \core_availability\info_module($cm);
822 $info->update_after_restore($this->get_restoreid(),
823 $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
832 * Process legacy module availability records in backup_ids.
834 * Matches course modules and grade item id once all them have been already restored.
835 * Only if all matchings are satisfied the availability condition will be created.
836 * At the same time, it is required for the site to have that functionality enabled.
838 * This step is included only to handle legacy backups (2.6 and before). It does not
839 * do anything for newer backups.
841 * @copyright 2014 The Open University
842 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
844 class restore_process_course_modules_availability extends restore_execution_step {
846 protected function define_execution() {
849 // Site hasn't availability enabled
850 if (empty($CFG->enableavailability)) {
854 // Do both modules and sections.
855 foreach (array('module', 'section') as $table) {
856 // Get all the availability objects to process.
857 $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
858 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
859 // Process availabilities, creating them if everything matches ok.
860 foreach ($rs as $availrec) {
861 $allmatchesok = true;
862 // Get the complete legacy availability object.
863 $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
865 // Note: This code used to update IDs, but that is now handled by the
866 // current code (after restore) instead of this legacy code.
868 // Get showavailability option.
869 $thingid = ($table === 'module') ? $availability->coursemoduleid :
870 $availability->coursesectionid;
871 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
872 $table . '_showavailability', $thingid);
874 // Should not happen.
875 throw new coding_exception('No matching showavailability record');
877 $show = $showrec->info->showavailability;
879 // The $availability object is now in the format used in the old
880 // system. Interpret this and convert to new system.
881 $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
882 array('id' => $thingid), MUST_EXIST);
883 $newvalue = \core_availability\info::add_legacy_availability_condition(
884 $currentvalue, $availability, $show);
885 $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
886 array('id' => $thingid));
895 * Execution step that, *conditionally* (if there isn't preloaded information)
896 * will load the inforef files for all the included course/section/activity tasks
897 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
899 class restore_load_included_inforef_records extends restore_execution_step {
901 protected function define_execution() {
903 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
907 // Get all the included tasks
908 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
909 $progress = $this->task->get_progress();
910 $progress->start_progress($this->get_name(), count($tasks));
911 foreach ($tasks as $task) {
912 // Load the inforef.xml file if exists
913 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
914 if (file_exists($inforefpath)) {
915 // Load each inforef file to temp_ids.
916 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
919 $progress->end_progress();
924 * Execution step that will load all the needed files into backup_files_temp
925 * - info: contains the whole original object (times, names...)
926 * (all them being original ids as loaded from xml)
928 class restore_load_included_files extends restore_structure_step {
930 protected function define_structure() {
932 $file = new restore_path_element('file', '/files/file');
938 * Process one <file> element from files.xml
940 * @param array $data the element data
942 public function process_file($data) {
944 $data = (object)$data; // handy
946 // load it if needed:
947 // - it it is one of the annotated inforef files (course/section/activity/block)
948 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
949 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
950 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
951 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
952 $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
953 $data->component == 'grouping' || $data->component == 'grade' ||
954 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
955 if ($isfileref || $iscomponent) {
956 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
962 * Execution step that, *conditionally* (if there isn't preloaded information),
963 * will load all the needed roles to backup_temp_ids. They will be stored with
964 * "role" itemname. Also it will perform one automatic mapping to roles existing
965 * in the target site, based in permissions of the user performing the restore,
966 * archetypes and other bits. At the end, each original role will have its associated
967 * target role or 0 if it's going to be skipped. Note we wrap everything over one
968 * restore_dbops method, as far as the same stuff is going to be also executed
969 * by restore prechecks
971 class restore_load_and_map_roles extends restore_execution_step {
973 protected function define_execution() {
974 if ($this->task->get_preloaded_information()) { // if info is already preloaded
978 $file = $this->get_basepath() . '/roles.xml';
979 // Load needed toles to temp_ids
980 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
982 // Process roles, mapping/skipping. Any error throws exception
983 // Note we pass controller's info because it can contain role mapping information
984 // about manual mappings performed by UI
985 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);
990 * Execution step that, *conditionally* (if there isn't preloaded information
991 * and users have been selected in settings, will load all the needed users
992 * to backup_temp_ids. They will be stored with "user" itemname and with
993 * their original contextid as paremitemid
995 class restore_load_included_users extends restore_execution_step {
997 protected function define_execution() {
999 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1002 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1005 $file = $this->get_basepath() . '/users.xml';
1006 // Load needed users to temp_ids.
1007 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
1012 * Execution step that, *conditionally* (if there isn't preloaded information
1013 * and users have been selected in settings, will process all the needed users
1014 * in order to decide and perform any action with them (create / map / error)
1015 * Note: Any error will cause exception, as far as this is the same processing
1016 * than the one into restore prechecks (that should have stopped process earlier)
1018 class restore_process_included_users extends restore_execution_step {
1020 protected function define_execution() {
1022 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1025 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1028 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
1029 $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
1034 * Execution step that will create all the needed users as calculated
1035 * by @restore_process_included_users (those having newiteind = 0)
1037 class restore_create_included_users extends restore_execution_step {
1039 protected function define_execution() {
1041 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
1042 $this->task->get_userid(), $this->task->get_progress());
1047 * Structure step that will create all the needed groups and groupings
1048 * by loading them from the groups.xml file performing the required matches.
1049 * Note group members only will be added if restoring user info
1051 class restore_groups_structure_step extends restore_structure_step {
1053 protected function define_structure() {
1055 $paths = array(); // Add paths here
1057 // Do not include group/groupings information if not requested.
1058 $groupinfo = $this->get_setting_value('groups');
1060 $paths[] = new restore_path_element('group', '/groups/group');
1061 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
1062 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
1067 // Processing functions go here
1068 public function process_group($data) {
1071 $data = (object)$data; // handy
1072 $data->courseid = $this->get_courseid();
1074 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1075 // another a group in the same course
1076 $context = context_course::instance($data->courseid);
1077 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1078 if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
1079 unset($data->idnumber);
1082 unset($data->idnumber);
1085 $oldid = $data->id; // need this saved for later
1087 $restorefiles = false; // Only if we end creating the group
1089 // Search if the group already exists (by name & description) in the target course
1090 $description_clause = '';
1091 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1092 if (!empty($data->description)) {
1093 $description_clause = ' AND ' .
1094 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1095 $params['description'] = $data->description;
1097 if (!$groupdb = $DB->get_record_sql("SELECT *
1099 WHERE courseid = :courseid
1100 AND name = :grname $description_clause", $params)) {
1101 // group doesn't exist, create
1102 $newitemid = $DB->insert_record('groups', $data);
1103 $restorefiles = true; // We'll restore the files
1105 // group exists, use it
1106 $newitemid = $groupdb->id;
1108 // Save the id mapping
1109 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
1110 // Invalidate the course group data cache just in case.
1111 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1114 public function process_grouping($data) {
1117 $data = (object)$data; // handy
1118 $data->courseid = $this->get_courseid();
1120 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1121 // another a grouping in the same course
1122 $context = context_course::instance($data->courseid);
1123 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1124 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
1125 unset($data->idnumber);
1128 unset($data->idnumber);
1131 $oldid = $data->id; // need this saved for later
1132 $restorefiles = false; // Only if we end creating the grouping
1134 // Search if the grouping already exists (by name & description) in the target course
1135 $description_clause = '';
1136 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1137 if (!empty($data->description)) {
1138 $description_clause = ' AND ' .
1139 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1140 $params['description'] = $data->description;
1142 if (!$groupingdb = $DB->get_record_sql("SELECT *
1144 WHERE courseid = :courseid
1145 AND name = :grname $description_clause", $params)) {
1146 // grouping doesn't exist, create
1147 $newitemid = $DB->insert_record('groupings', $data);
1148 $restorefiles = true; // We'll restore the files
1150 // grouping exists, use it
1151 $newitemid = $groupingdb->id;
1153 // Save the id mapping
1154 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1155 // Invalidate the course group data cache just in case.
1156 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1159 public function process_grouping_group($data) {
1162 require_once($CFG->dirroot.'/group/lib.php');
1164 $data = (object)$data;
1165 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
1168 protected function after_execute() {
1169 // Add group related files, matching with "group" mappings
1170 $this->add_related_files('group', 'icon', 'group');
1171 $this->add_related_files('group', 'description', 'group');
1172 // Add grouping related files, matching with "grouping" mappings
1173 $this->add_related_files('grouping', 'description', 'grouping');
1174 // Invalidate the course group data.
1175 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1181 * Structure step that will create all the needed group memberships
1182 * by loading them from the groups.xml file performing the required matches.
1184 class restore_groups_members_structure_step extends restore_structure_step {
1186 protected $plugins = null;
1188 protected function define_structure() {
1190 $paths = array(); // Add paths here
1192 if ($this->get_setting_value('groups') && $this->get_setting_value('users')) {
1193 $paths[] = new restore_path_element('group', '/groups/group');
1194 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1200 public function process_group($data) {
1201 $data = (object)$data; // handy
1204 // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1205 // Let's fake internal state to make $this->get_new_parentid('group') work.
1207 $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1210 public function process_member($data) {
1212 require_once("$CFG->dirroot/group/lib.php");
1214 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1216 $data = (object)$data; // handy
1218 // get parent group->id
1219 $data->groupid = $this->get_new_parentid('group');
1221 // map user newitemid and insert if not member already
1222 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1223 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1224 // Check the component, if any, exists.
1225 if (empty($data->component)) {
1226 groups_add_member($data->groupid, $data->userid);
1228 } else if ((strpos($data->component, 'enrol_') === 0)) {
1229 // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1230 // it is possible that enrolment was restored using different plugin type.
1231 if (!isset($this->plugins)) {
1232 $this->plugins = enrol_get_plugins(true);
1234 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1235 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1236 if (isset($this->plugins[$instance->enrol])) {
1237 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1243 $dir = core_component::get_component_directory($data->component);
1244 if ($dir and is_dir($dir)) {
1245 if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1249 // Bad luck, plugin could not restore the data, let's add normal membership.
1250 groups_add_member($data->groupid, $data->userid);
1251 $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1252 $this->log($message, backup::LOG_WARNING);
1260 * Structure step that will create all the needed scales
1261 * by loading them from the scales.xml
1263 class restore_scales_structure_step extends restore_structure_step {
1265 protected function define_structure() {
1267 $paths = array(); // Add paths here
1268 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1272 protected function process_scale($data) {
1275 $data = (object)$data;
1277 $restorefiles = false; // Only if we end creating the group
1279 $oldid = $data->id; // need this saved for later
1281 // Look for scale (by 'scale' both in standard (course=0) and current course
1282 // with priority to standard scales (ORDER clause)
1283 // scale is not course unique, use get_record_sql to suppress warning
1284 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1285 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
1286 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1287 if (!$scadb = $DB->get_record_sql("SELECT *
1289 WHERE courseid IN (0, :courseid)
1290 AND $compare_scale_clause
1291 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1292 // Remap the user if possible, defaut to user performing the restore if not
1293 $userid = $this->get_mappingid('user', $data->userid);
1294 $data->userid = $userid ? $userid : $this->task->get_userid();
1295 // Remap the course if course scale
1296 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1297 // If global scale (course=0), check the user has perms to create it
1298 // falling to course scale if not
1299 $systemctx = context_system::instance();
1300 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1301 $data->courseid = $this->get_courseid();
1303 // scale doesn't exist, create
1304 $newitemid = $DB->insert_record('scale', $data);
1305 $restorefiles = true; // We'll restore the files
1307 // scale exists, use it
1308 $newitemid = $scadb->id;
1310 // Save the id mapping (with files support at system context)
1311 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1314 protected function after_execute() {
1315 // Add scales related files, matching with "scale" mappings
1316 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1322 * Structure step that will create all the needed outocomes
1323 * by loading them from the outcomes.xml
1325 class restore_outcomes_structure_step extends restore_structure_step {
1327 protected function define_structure() {
1329 $paths = array(); // Add paths here
1330 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1334 protected function process_outcome($data) {
1337 $data = (object)$data;
1339 $restorefiles = false; // Only if we end creating the group
1341 $oldid = $data->id; // need this saved for later
1343 // Look for outcome (by shortname both in standard (courseid=null) and current course
1344 // with priority to standard outcomes (ORDER clause)
1345 // outcome is not course unique, use get_record_sql to suppress warning
1346 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1347 if (!$outdb = $DB->get_record_sql('SELECT *
1348 FROM {grade_outcomes}
1349 WHERE shortname = :shortname
1350 AND (courseid = :courseid OR courseid IS NULL)
1351 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1353 $userid = $this->get_mappingid('user', $data->usermodified);
1354 $data->usermodified = $userid ? $userid : $this->task->get_userid();
1356 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1357 // Remap the course if course outcome
1358 $data->courseid = $data->courseid ? $this->get_courseid() : null;
1359 // If global outcome (course=null), check the user has perms to create it
1360 // falling to course outcome if not
1361 $systemctx = context_system::instance();
1362 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1363 $data->courseid = $this->get_courseid();
1365 // outcome doesn't exist, create
1366 $newitemid = $DB->insert_record('grade_outcomes', $data);
1367 $restorefiles = true; // We'll restore the files
1369 // scale exists, use it
1370 $newitemid = $outdb->id;
1372 // Set the corresponding grade_outcomes_courses record
1373 $outcourserec = new stdclass();
1374 $outcourserec->courseid = $this->get_courseid();
1375 $outcourserec->outcomeid = $newitemid;
1376 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1377 $DB->insert_record('grade_outcomes_courses', $outcourserec);
1379 // Save the id mapping (with files support at system context)
1380 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1383 protected function after_execute() {
1384 // Add outcomes related files, matching with "outcome" mappings
1385 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1390 * Execution step that, *conditionally* (if there isn't preloaded information
1391 * will load all the question categories and questions (header info only)
1392 * to backup_temp_ids. They will be stored with "question_category" and
1393 * "question" itemnames and with their original contextid and question category
1394 * id as paremitemids
1396 class restore_load_categories_and_questions extends restore_execution_step {
1398 protected function define_execution() {
1400 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1403 $file = $this->get_basepath() . '/questions.xml';
1404 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1409 * Execution step that, *conditionally* (if there isn't preloaded information)
1410 * will process all the needed categories and questions
1411 * in order to decide and perform any action with them (create / map / error)
1412 * Note: Any error will cause exception, as far as this is the same processing
1413 * than the one into restore prechecks (that should have stopped process earlier)
1415 class restore_process_categories_and_questions extends restore_execution_step {
1417 protected function define_execution() {
1419 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1422 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1427 * Structure step that will read the section.xml creating/updating sections
1428 * as needed, rebuilding course cache and other friends
1430 class restore_section_structure_step extends restore_structure_step {
1431 /** @var array Cache: Array of id => course format */
1432 private static $courseformats = array();
1435 * Resets a static cache of course formats. Required for unit testing.
1437 public static function reset_caches() {
1438 self::$courseformats = array();
1441 protected function define_structure() {
1446 $section = new restore_path_element('section', '/section');
1447 $paths[] = $section;
1448 if ($CFG->enableavailability) {
1449 $paths[] = new restore_path_element('availability', '/section/availability');
1450 $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1452 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1454 // Apply for 'format' plugins optional paths at section level
1455 $this->add_plugin_structure('format', $section);
1457 // Apply for 'local' plugins optional paths at section level
1458 $this->add_plugin_structure('local', $section);
1463 public function process_section($data) {
1465 $data = (object)$data;
1466 $oldid = $data->id; // We'll need this later
1468 $restorefiles = false;
1470 // Look for the section
1471 $section = new stdclass();
1472 $section->course = $this->get_courseid();
1473 $section->section = $data->number;
1474 // Section doesn't exist, create it with all the info from backup
1475 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1476 $section->name = $data->name;
1477 $section->summary = $data->summary;
1478 $section->summaryformat = $data->summaryformat;
1479 $section->sequence = '';
1480 $section->visible = $data->visible;
1481 if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1482 $section->availability = null;
1484 $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1485 // Include legacy [<2.7] availability data if provided.
1486 if (is_null($section->availability)) {
1487 $section->availability = \core_availability\info::convert_legacy_fields(
1491 $newitemid = $DB->insert_record('course_sections', $section);
1492 $restorefiles = true;
1494 // Section exists, update non-empty information
1496 $section->id = $secrec->id;
1497 if ((string)$secrec->name === '') {
1498 $section->name = $data->name;
1500 if (empty($secrec->summary)) {
1501 $section->summary = $data->summary;
1502 $section->summaryformat = $data->summaryformat;
1503 $restorefiles = true;
1506 // Don't update availability (I didn't see a useful way to define
1507 // whether existing or new one should take precedence).
1509 $DB->update_record('course_sections', $section);
1510 $newitemid = $secrec->id;
1513 // Annotate the section mapping, with restorefiles option if needed
1514 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1516 // set the new course_section id in the task
1517 $this->task->set_sectionid($newitemid);
1519 // If there is the legacy showavailability data, store this for later use.
1520 // (This data is not present when restoring 'new' backups.)
1521 if (isset($data->showavailability)) {
1522 // Cache the showavailability flag using the backup_ids data field.
1523 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1524 'section_showavailability', $newitemid, 0, null,
1525 (object)array('showavailability' => $data->showavailability));
1528 // Commented out. We never modify course->numsections as far as that is used
1529 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1530 // Note: We keep the code here, to know about and because of the possibility of making this
1531 // optional based on some setting/attribute in the future
1532 // If needed, adjust course->numsections
1533 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1534 // if ($numsections < $section->section) {
1535 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1541 * Process the legacy availability table record. This table does not exist
1542 * in Moodle 2.7+ but we still support restore.
1544 * @param stdClass $data Record data
1546 public function process_availability($data) {
1547 $data = (object)$data;
1548 // Simply going to store the whole availability record now, we'll process
1549 // all them later in the final task (once all activities have been restored)
1550 // Let's call the low level one to be able to store the whole object.
1551 $data->coursesectionid = $this->task->get_sectionid();
1552 restore_dbops::set_backup_ids_record($this->get_restoreid(),
1553 'section_availability', $data->id, 0, null, $data);
1557 * Process the legacy availability fields table record. This table does not
1558 * exist in Moodle 2.7+ but we still support restore.
1560 * @param stdClass $data Record data
1562 public function process_availability_field($data) {
1564 $data = (object)$data;
1565 // Mark it is as passed by default
1567 $customfieldid = null;
1569 // If a customfield has been used in order to pass we must be able to match an existing
1570 // customfield by name (data->customfield) and type (data->customfieldtype)
1571 if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1572 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1573 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1575 } else if (!is_null($data->customfield)) {
1576 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1577 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1578 $passed = ($customfieldid !== false);
1582 // Create the object to insert into the database
1583 $availfield = new stdClass();
1584 $availfield->coursesectionid = $this->task->get_sectionid();
1585 $availfield->userfield = $data->userfield;
1586 $availfield->customfieldid = $customfieldid;
1587 $availfield->operator = $data->operator;
1588 $availfield->value = $data->value;
1590 // Get showavailability option.
1591 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1592 'section_showavailability', $availfield->coursesectionid);
1594 // Should not happen.
1595 throw new coding_exception('No matching showavailability record');
1597 $show = $showrec->info->showavailability;
1599 // The $availfield object is now in the format used in the old
1600 // system. Interpret this and convert to new system.
1601 $currentvalue = $DB->get_field('course_sections', 'availability',
1602 array('id' => $availfield->coursesectionid), MUST_EXIST);
1603 $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1604 $currentvalue, $availfield, $show);
1605 $DB->set_field('course_sections', 'availability', $newvalue,
1606 array('id' => $availfield->coursesectionid));
1610 public function process_course_format_options($data) {
1612 $courseid = $this->get_courseid();
1613 if (!array_key_exists($courseid, self::$courseformats)) {
1614 // It is safe to have a static cache of course formats because format can not be changed after this point.
1615 self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1617 $data = (array)$data;
1618 if (self::$courseformats[$courseid] === $data['format']) {
1619 // Import section format options only if both courses (the one that was backed up
1620 // and the one we are restoring into) have same formats.
1622 'courseid' => $this->get_courseid(),
1623 'sectionid' => $this->task->get_sectionid(),
1624 'format' => $data['format'],
1625 'name' => $data['name']
1627 if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1628 // Do not overwrite existing information.
1629 $newid = $record->id;
1631 $params['value'] = $data['value'];
1632 $newid = $DB->insert_record('course_format_options', $params);
1634 $this->set_mapping('course_format_options', $data['id'], $newid);
1638 protected function after_execute() {
1639 // Add section related files, with 'course_section' itemid to match
1640 $this->add_related_files('course', 'section', 'course_section');
1645 * Structure step that will read the course.xml file, loading it and performing
1646 * various actions depending of the site/restore settings. Note that target
1647 * course always exist before arriving here so this step will be updating
1648 * the course record (never inserting)
1650 class restore_course_structure_step extends restore_structure_step {
1652 * @var bool this gets set to true by {@link process_course()} if we are
1653 * restoring an old coures that used the legacy 'module security' feature.
1654 * If so, we have to do more work in {@link after_execute()}.
1656 protected $legacyrestrictmodules = false;
1659 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1660 * array with array keys the module names ('forum', 'quiz', etc.). These are
1661 * the modules that are allowed according to the data in the backup file.
1662 * In {@link after_execute()} we then have to prevent adding of all the other
1663 * types of activity.
1665 protected $legacyallowedmodules = array();
1667 protected function define_structure() {
1669 $course = new restore_path_element('course', '/course');
1670 $category = new restore_path_element('category', '/course/category');
1671 $tag = new restore_path_element('tag', '/course/tags/tag');
1672 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1674 // Apply for 'format' plugins optional paths at course level
1675 $this->add_plugin_structure('format', $course);
1677 // Apply for 'theme' plugins optional paths at course level
1678 $this->add_plugin_structure('theme', $course);
1680 // Apply for 'report' plugins optional paths at course level
1681 $this->add_plugin_structure('report', $course);
1683 // Apply for 'course report' plugins optional paths at course level
1684 $this->add_plugin_structure('coursereport', $course);
1686 // Apply for plagiarism plugins optional paths at course level
1687 $this->add_plugin_structure('plagiarism', $course);
1689 // Apply for local plugins optional paths at course level
1690 $this->add_plugin_structure('local', $course);
1692 // Apply for admin tool plugins optional paths at course level.
1693 $this->add_plugin_structure('tool', $course);
1695 return array($course, $category, $tag, $allowed_module);
1699 * Processing functions go here
1701 * @global moodledatabase $DB
1702 * @param stdClass $data
1704 public function process_course($data) {
1706 $context = context::instance_by_id($this->task->get_contextid());
1707 $userid = $this->task->get_userid();
1708 $target = $this->get_task()->get_target();
1709 $isnewcourse = $target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING;
1711 // When restoring to a new course we can set all the things except for the ID number.
1712 $canchangeidnumber = $isnewcourse || has_capability('moodle/course:changeidnumber', $context, $userid);
1713 $canchangeshortname = $isnewcourse || has_capability('moodle/course:changeshortname', $context, $userid);
1714 $canchangefullname = $isnewcourse || has_capability('moodle/course:changefullname', $context, $userid);
1715 $canchangesummary = $isnewcourse || has_capability('moodle/course:changesummary', $context, $userid);
1717 $data = (object)$data;
1718 $data->id = $this->get_courseid();
1720 $fullname = $this->get_setting_value('course_fullname');
1721 $shortname = $this->get_setting_value('course_shortname');
1722 $startdate = $this->get_setting_value('course_startdate');
1724 // Calculate final course names, to avoid dupes.
1725 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1727 if ($canchangefullname) {
1728 $data->fullname = $fullname;
1730 unset($data->fullname);
1733 if ($canchangeshortname) {
1734 $data->shortname = $shortname;
1736 unset($data->shortname);
1739 if (!$canchangesummary) {
1740 unset($data->summary);
1741 unset($data->summaryformat);
1744 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1745 // another course on this site.
1746 if (!empty($data->idnumber) && $canchangeidnumber && $this->task->is_samesite()
1747 && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1748 // Do not reset idnumber.
1750 } else if (!$isnewcourse) {
1751 // Prevent override when restoring as merge.
1752 unset($data->idnumber);
1755 $data->idnumber = '';
1758 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1759 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1760 if (empty($data->hiddensections)) {
1761 $data->hiddensections = 0;
1764 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1765 // then we will need to process restricted modules after execution.
1766 $this->legacyrestrictmodules = !empty($data->restrictmodules);
1768 $data->startdate= $this->apply_date_offset($data->startdate);
1769 if ($data->defaultgroupingid) {
1770 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1772 if (empty($CFG->enablecompletion)) {
1773 $data->enablecompletion = 0;
1774 $data->completionstartonenrol = 0;
1775 $data->completionnotify = 0;
1777 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1778 if (!array_key_exists($data->lang, $languages)) {
1782 $themes = get_list_of_themes(); // Get themes for quick search later
1783 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1787 // Check if this is an old SCORM course format.
1788 if ($data->format == 'scorm') {
1789 $data->format = 'singleactivity';
1790 $data->activitytype = 'scorm';
1793 // Course record ready, update it
1794 $DB->update_record('course', $data);
1796 course_get_format($data)->update_course_format_options($data);
1798 // Role name aliases
1799 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1802 public function process_category($data) {
1803 // Nothing to do with the category. UI sets it before restore starts
1806 public function process_tag($data) {
1809 $data = (object)$data;
1811 core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
1812 context_course::instance($this->get_courseid()), $data->rawname);
1815 public function process_allowed_module($data) {
1816 $data = (object)$data;
1818 // Backwards compatiblity support for the data that used to be in the
1819 // course_allowed_modules table.
1820 if ($this->legacyrestrictmodules) {
1821 $this->legacyallowedmodules[$data->modulename] = 1;
1825 protected function after_execute() {
1828 // Add course related files, without itemid to match
1829 $this->add_related_files('course', 'summary', null);
1830 $this->add_related_files('course', 'overviewfiles', null);
1832 // Deal with legacy allowed modules.
1833 if ($this->legacyrestrictmodules) {
1834 $context = context_course::instance($this->get_courseid());
1836 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1837 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1838 foreach ($managerroleids as $roleid) {
1839 unset($roleids[$roleid]);
1842 foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1843 if (isset($this->legacyallowedmodules[$modname])) {
1844 // Module is allowed, no worries.
1848 $capability = 'mod/' . $modname . ':addinstance';
1849 foreach ($roleids as $roleid) {
1850 assign_capability($capability, CAP_PREVENT, $roleid, $context);
1858 * Execution step that will migrate legacy files if present.
1860 class restore_course_legacy_files_step extends restore_execution_step {
1861 public function define_execution() {
1864 // Do a check for legacy files and skip if there are none.
1865 $sql = 'SELECT count(*)
1866 FROM {backup_files_temp}
1871 $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
1873 if ($DB->count_records_sql($sql, $params)) {
1874 $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
1875 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
1876 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
1882 * Structure step that will read the roles.xml file (at course/activity/block levels)
1883 * containing all the role_assignments and overrides for that context. If corresponding to
1884 * one mapped role, they will be applied to target context. Will observe the role_assignments
1885 * setting to decide if ras are restored.
1887 * Note: this needs to be executed after all users are enrolled.
1889 class restore_ras_and_caps_structure_step extends restore_structure_step {
1890 protected $plugins = null;
1892 protected function define_structure() {
1896 // Observe the role_assignments setting
1897 if ($this->get_setting_value('role_assignments')) {
1898 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1900 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1908 * This has to be called after enrolments processing.
1910 * @param mixed $data
1913 public function process_assignment($data) {
1916 $data = (object)$data;
1918 // Check roleid, userid are one of the mapped ones
1919 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1922 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1925 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1926 // Only assign roles to not deleted users
1929 if (!$contextid = $this->task->get_contextid()) {
1933 if (empty($data->component)) {
1934 // assign standard manual roles
1935 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1936 role_assign($newroleid, $newuserid, $contextid);
1938 } else if ((strpos($data->component, 'enrol_') === 0)) {
1939 // Deal with enrolment roles - ignore the component and just find out the instance via new id,
1940 // it is possible that enrolment was restored using different plugin type.
1941 if (!isset($this->plugins)) {
1942 $this->plugins = enrol_get_plugins(true);
1944 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1945 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1946 if (isset($this->plugins[$instance->enrol])) {
1947 $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
1953 $data->roleid = $newroleid;
1954 $data->userid = $newuserid;
1955 $data->contextid = $contextid;
1956 $dir = core_component::get_component_directory($data->component);
1957 if ($dir and is_dir($dir)) {
1958 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
1962 // Bad luck, plugin could not restore the data, let's add normal membership.
1963 role_assign($data->roleid, $data->userid, $data->contextid);
1964 $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
1965 $this->log($message, backup::LOG_WARNING);
1969 public function process_override($data) {
1970 $data = (object)$data;
1972 // Check roleid is one of the mapped ones
1973 $newroleid = $this->get_mappingid('role', $data->roleid);
1974 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1975 if ($newroleid && $this->task->get_contextid()) {
1976 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1977 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1978 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1984 * If no instances yet add default enrol methods the same way as when creating new course in UI.
1986 class restore_default_enrolments_step extends restore_execution_step {
1988 public function define_execution() {
1991 // No enrolments in front page.
1992 if ($this->get_courseid() == SITEID) {
1996 $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
1998 if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
1999 // Something already added instances, do not add default instances.
2000 $plugins = enrol_get_plugins(true);
2001 foreach ($plugins as $plugin) {
2002 $plugin->restore_sync_course($course);
2006 // Looks like a newly created course.
2007 enrol_course_updated(true, $course, null);
2013 * This structure steps restores the enrol plugins and their underlying
2014 * enrolments, performing all the mappings and/or movements required
2016 class restore_enrolments_structure_step extends restore_structure_step {
2017 protected $enrolsynced = false;
2018 protected $plugins = null;
2019 protected $originalstatus = array();
2022 * Conditionally decide if this step should be executed.
2024 * This function checks the following parameter:
2026 * 1. the course/enrolments.xml file exists
2028 * @return bool true is safe to execute, false otherwise
2030 protected function execute_condition() {
2032 if ($this->get_courseid() == SITEID) {
2036 // Check it is included in the backup
2037 $fullpath = $this->task->get_taskbasepath();
2038 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2039 if (!file_exists($fullpath)) {
2040 // Not found, can't restore enrolments info
2047 protected function define_structure() {
2049 $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2050 $enrolment = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2051 // Attach local plugin stucture to enrol element.
2052 $this->add_plugin_structure('enrol', $enrol);
2054 return array($enrol, $enrolment);
2058 * Create enrolment instances.
2060 * This has to be called after creation of roles
2061 * and before adding of role assignments.
2063 * @param mixed $data
2066 public function process_enrol($data) {
2069 $data = (object)$data;
2070 $oldid = $data->id; // We'll need this later.
2073 $this->originalstatus[$oldid] = $data->status;
2075 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2076 $this->set_mapping('enrol', $oldid, 0);
2080 if (!isset($this->plugins)) {
2081 $this->plugins = enrol_get_plugins(true);
2084 if (!$this->enrolsynced) {
2085 // Make sure that all plugin may create instances and enrolments automatically
2086 // before the first instance restore - this is suitable especially for plugins
2087 // that synchronise data automatically using course->idnumber or by course categories.
2088 foreach ($this->plugins as $plugin) {
2089 $plugin->restore_sync_course($courserec);
2091 $this->enrolsynced = true;
2094 // Map standard fields - plugin has to process custom fields manually.
2095 $data->roleid = $this->get_mappingid('role', $data->roleid);
2096 $data->courseid = $courserec->id;
2098 if ($this->get_setting_value('enrol_migratetomanual')) {
2099 unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2100 if (!enrol_is_enabled('manual')) {
2101 $this->set_mapping('enrol', $oldid, 0);
2104 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2105 $instance = reset($instances);
2106 $this->set_mapping('enrol', $oldid, $instance->id);
2108 if ($data->enrol === 'manual') {
2109 $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2111 $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2113 $this->set_mapping('enrol', $oldid, $instanceid);
2117 if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2118 $this->set_mapping('enrol', $oldid, 0);
2119 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments";
2120 $this->log($message, backup::LOG_WARNING);
2123 if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2124 // Let's keep the sortorder in old backups.
2126 // Prevent problems with colliding sortorders in old backups,
2127 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2128 unset($data->sortorder);
2130 // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2131 $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2136 * Create user enrolments.
2138 * This has to be called after creation of enrolment instances
2139 * and before adding of role assignments.
2141 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2143 * @param mixed $data
2146 public function process_enrolment($data) {
2149 if (!isset($this->plugins)) {
2150 $this->plugins = enrol_get_plugins(true);
2153 $data = (object)$data;
2155 // Process only if parent instance have been mapped.
2156 if ($enrolid = $this->get_new_parentid('enrol')) {
2157 $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2158 $oldenrolid = $this->get_old_parentid('enrol');
2159 if (isset($this->originalstatus[$oldenrolid])) {
2160 $oldinstancestatus = $this->originalstatus[$oldenrolid];
2162 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2163 // And only if user is a mapped one.
2164 if ($userid = $this->get_mappingid('user', $data->userid)) {
2165 if (isset($this->plugins[$instance->enrol])) {
2166 $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2176 * Make sure the user restoring the course can actually access it.
2178 class restore_fix_restorer_access_step extends restore_execution_step {
2179 protected function define_execution() {
2182 if (!$userid = $this->task->get_userid()) {
2186 if (empty($CFG->restorernewroleid)) {
2187 // Bad luck, no fallback role for restorers specified
2191 $courseid = $this->get_courseid();
2192 $context = context_course::instance($courseid);
2194 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2195 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2199 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2200 role_assign($CFG->restorernewroleid, $userid, $context);
2202 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2203 // Extra role is enough, yay!
2207 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2208 // hopefully admin selected suitable $CFG->restorernewroleid ...
2209 if (!enrol_is_enabled('manual')) {
2212 if (!$enrol = enrol_get_plugin('manual')) {
2215 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2216 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2217 $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2218 $enrol->add_instance($course, $fields);
2221 enrol_try_internal_enrol($courseid, $userid);
2227 * This structure steps restores the filters and their configs
2229 class restore_filters_structure_step extends restore_structure_step {
2231 protected function define_structure() {
2235 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2236 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2241 public function process_active($data) {
2243 $data = (object)$data;
2245 if (strpos($data->filter, 'filter/') === 0) {
2246 $data->filter = substr($data->filter, 7);
2248 } else if (strpos($data->filter, '/') !== false) {
2249 // Unsupported old filter.
2253 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2256 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2259 public function process_config($data) {
2261 $data = (object)$data;
2263 if (strpos($data->filter, 'filter/') === 0) {
2264 $data->filter = substr($data->filter, 7);
2266 } else if (strpos($data->filter, '/') !== false) {
2267 // Unsupported old filter.
2271 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2274 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2280 * This structure steps restores the comments
2281 * Note: Cannot use the comments API because defaults to USER->id.
2282 * That should change allowing to pass $userid
2284 class restore_comments_structure_step extends restore_structure_step {
2286 protected function define_structure() {
2290 $paths[] = new restore_path_element('comment', '/comments/comment');
2295 public function process_comment($data) {
2298 $data = (object)$data;
2300 // First of all, if the comment has some itemid, ask to the task what to map
2302 if ($data->itemid) {
2303 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2304 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2306 // Only restore the comment if has no mapping OR we have found the matching mapping
2307 if (!$mapping || $data->itemid) {
2308 // Only if user mapping and context
2309 $data->userid = $this->get_mappingid('user', $data->userid);
2310 if ($data->userid && $this->task->get_contextid()) {
2311 $data->contextid = $this->task->get_contextid();
2312 // Only if there is another comment with same context/user/timecreated
2313 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2314 if (!$DB->record_exists('comments', $params)) {
2315 $DB->insert_record('comments', $data);
2323 * This structure steps restores the badges and their configs
2325 class restore_badges_structure_step extends restore_structure_step {
2328 * Conditionally decide if this step should be executed.
2330 * This function checks the following parameters:
2332 * 1. Badges and course badges are enabled on the site.
2333 * 2. The course/badges.xml file exists.
2334 * 3. All modules are restorable.
2335 * 4. All modules are marked for restore.
2337 * @return bool True is safe to execute, false otherwise
2339 protected function execute_condition() {
2342 // First check is badges and course level badges are enabled on this site.
2343 if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2344 // Disabled, don't restore course badges.
2348 // Check if badges.xml is included in the backup.
2349 $fullpath = $this->task->get_taskbasepath();
2350 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2351 if (!file_exists($fullpath)) {
2352 // Not found, can't restore course badges.
2356 // Check we are able to restore all backed up modules.
2357 if ($this->task->is_missing_modules()) {
2361 // Finally check all modules within the backup are being restored.
2362 if ($this->task->is_excluding_activities()) {
2369 protected function define_structure() {
2371 $paths[] = new restore_path_element('badge', '/badges/badge');
2372 $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2373 $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2374 $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2379 public function process_badge($data) {
2382 require_once($CFG->libdir . '/badgeslib.php');
2384 $data = (object)$data;
2385 $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2386 if (empty($data->usercreated)) {
2387 $data->usercreated = $this->task->get_userid();
2389 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2390 if (empty($data->usermodified)) {
2391 $data->usermodified = $this->task->get_userid();
2394 // We'll restore the badge image.
2395 $restorefiles = true;
2397 $courseid = $this->get_courseid();
2400 'name' => $data->name,
2401 'description' => $data->description,
2402 'timecreated' => $this->apply_date_offset($data->timecreated),
2403 'timemodified' => $this->apply_date_offset($data->timemodified),
2404 'usercreated' => $data->usercreated,
2405 'usermodified' => $data->usermodified,
2406 'issuername' => $data->issuername,
2407 'issuerurl' => $data->issuerurl,
2408 'issuercontact' => $data->issuercontact,
2409 'expiredate' => $this->apply_date_offset($data->expiredate),
2410 'expireperiod' => $data->expireperiod,
2411 'type' => BADGE_TYPE_COURSE,
2412 'courseid' => $courseid,
2413 'message' => $data->message,
2414 'messagesubject' => $data->messagesubject,
2415 'attachment' => $data->attachment,
2416 'notification' => $data->notification,
2417 'status' => BADGE_STATUS_INACTIVE,
2418 'nextcron' => $this->apply_date_offset($data->nextcron)
2421 $newid = $DB->insert_record('badge', $params);
2422 $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2425 public function process_criterion($data) {
2428 $data = (object)$data;
2431 'badgeid' => $this->get_new_parentid('badge'),
2432 'criteriatype' => $data->criteriatype,
2433 'method' => $data->method,
2434 'description' => isset($data->description) ? $data->description : '',
2435 'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0,
2437 $newid = $DB->insert_record('badge_criteria', $params);
2438 $this->set_mapping('criterion', $data->id, $newid);
2441 public function process_parameter($data) {
2444 require_once($CFG->libdir . '/badgeslib.php');
2446 $data = (object)$data;
2447 $criteriaid = $this->get_new_parentid('criterion');
2449 // Parameter array that will go to database.
2451 $params['critid'] = $criteriaid;
2453 $oldparam = explode('_', $data->name);
2455 if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2456 $module = $this->get_mappingid('course_module', $oldparam[1]);
2457 $params['name'] = $oldparam[0] . '_' . $module;
2458 $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2459 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2460 $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2461 $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2462 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2463 $role = $this->get_mappingid('role', $data->value);
2464 if (!empty($role)) {
2465 $params['name'] = 'role_' . $role;
2466 $params['value'] = $role;
2472 if (!$DB->record_exists('badge_criteria_param', $params)) {
2473 $DB->insert_record('badge_criteria_param', $params);
2477 public function process_manual_award($data) {
2480 $data = (object)$data;
2481 $role = $this->get_mappingid('role', $data->issuerrole);
2483 if (!empty($role)) {
2485 'badgeid' => $this->get_new_parentid('badge'),
2486 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2487 'issuerid' => $this->get_mappingid('user', $data->issuerid),
2488 'issuerrole' => $role,
2489 'datemet' => $this->apply_date_offset($data->datemet)
2492 // Skip the manual award if recipient or issuer can not be mapped to.
2493 if (empty($award['recipientid']) || empty($award['issuerid'])) {
2497 $DB->insert_record('badge_manual_award', $award);
2501 protected function after_execute() {
2502 // Add related files.
2503 $this->add_related_files('badges', 'badgeimage', 'badge');
2508 * This structure steps restores the calendar events
2510 class restore_calendarevents_structure_step extends restore_structure_step {
2512 protected function define_structure() {
2516 $paths[] = new restore_path_element('calendarevents', '/events/event');
2521 public function process_calendarevents($data) {
2522 global $DB, $SITE, $USER;
2524 $data = (object)$data;
2526 $restorefiles = true; // We'll restore the files
2527 // Find the userid and the groupid associated with the event.
2528 $data->userid = $this->get_mappingid('user', $data->userid);
2529 if ($data->userid === false) {
2530 // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2531 // Use the current user ID for these events.
2532 $data->userid = $USER->id;
2534 if (!empty($data->groupid)) {
2535 $data->groupid = $this->get_mappingid('group', $data->groupid);
2536 if ($data->groupid === false) {
2540 // Handle events with empty eventtype //MDL-32827
2541 if(empty($data->eventtype)) {
2542 if ($data->courseid == $SITE->id) { // Site event
2543 $data->eventtype = "site";
2544 } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2545 // Course assingment event
2546 $data->eventtype = "due";
2547 } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event
2548 $data->eventtype = "course";
2549 } else if ($data->groupid) { // Group event
2550 $data->eventtype = "group";
2551 } else if ($data->userid) { // User event
2552 $data->eventtype = "user";
2559 'name' => $data->name,
2560 'description' => $data->description,
2561 'format' => $data->format,
2562 'courseid' => $this->get_courseid(),
2563 'groupid' => $data->groupid,
2564 'userid' => $data->userid,
2565 'repeatid' => $data->repeatid,
2566 'modulename' => $data->modulename,
2567 'eventtype' => $data->eventtype,
2568 'timestart' => $this->apply_date_offset($data->timestart),
2569 'timeduration' => $data->timeduration,
2570 'visible' => $data->visible,
2571 'uuid' => $data->uuid,
2572 'sequence' => $data->sequence,
2573 'timemodified' => $this->apply_date_offset($data->timemodified));
2574 if ($this->name == 'activity_calendar') {
2575 $params['instance'] = $this->task->get_activityid();
2577 $params['instance'] = 0;
2581 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2586 AND timeduration = ?
2587 AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2588 $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
2589 $result = $DB->record_exists_sql($sql, $arg);
2590 if (empty($result)) {
2591 $newitemid = $DB->insert_record('event', $params);
2592 $this->set_mapping('event', $oldid, $newitemid);
2593 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2597 protected function after_execute() {
2598 // Add related files
2599 $this->add_related_files('calendar', 'event_description', 'event_description');
2603 class restore_course_completion_structure_step extends restore_structure_step {
2606 * Conditionally decide if this step should be executed.
2608 * This function checks parameters that are not immediate settings to ensure
2609 * that the enviroment is suitable for the restore of course completion info.
2611 * This function checks the following four parameters:
2613 * 1. Course completion is enabled on the site
2614 * 2. The backup includes course completion information
2615 * 3. All modules are restorable
2616 * 4. All modules are marked for restore.
2617 * 5. No completion criteria already exist for the course.
2619 * @return bool True is safe to execute, false otherwise
2621 protected function execute_condition() {
2624 // First check course completion is enabled on this site
2625 if (empty($CFG->enablecompletion)) {
2626 // Disabled, don't restore course completion
2630 // No course completion on the front page.
2631 if ($this->get_courseid() == SITEID) {
2635 // Check it is included in the backup
2636 $fullpath = $this->task->get_taskbasepath();
2637 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2638 if (!file_exists($fullpath)) {
2639 // Not found, can't restore course completion
2643 // Check we are able to restore all backed up modules
2644 if ($this->task->is_missing_modules()) {
2648 // Check all modules within the backup are being restored.
2649 if ($this->task->is_excluding_activities()) {
2653 // Check that no completion criteria is already set for the course.
2654 if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
2662 * Define the course completion structure
2664 * @return array Array of restore_path_element
2666 protected function define_structure() {
2668 // To know if we are including user completion info
2669 $userinfo = $this->get_setting_value('userscompletion');
2672 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2673 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2676 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2677 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2685 * Process course completion criteria
2687 * @global moodle_database $DB
2688 * @param stdClass $data
2690 public function process_course_completion_criteria($data) {
2693 $data = (object)$data;
2694 $data->course = $this->get_courseid();
2696 // Apply the date offset to the time end field
2697 $data->timeend = $this->apply_date_offset($data->timeend);
2699 // Map the role from the criteria
2700 if (isset($data->role) && $data->role != '') {
2701 // Newer backups should include roleshortname, which makes this much easier.
2702 if (!empty($data->roleshortname)) {
2703 $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
2704 if (!$roleinstanceid) {
2706 'Could not match the role shortname in course_completion_criteria, so skipping',
2711 $data->role = $roleinstanceid;
2713 $data->role = $this->get_mappingid('role', $data->role);
2716 // Check we have an id, otherwise it causes all sorts of bugs.
2719 'Could not match role in course_completion_criteria, so skipping',
2726 // If the completion criteria is for a module we need to map the module instance
2727 // to the new module id.
2728 if (!empty($data->moduleinstance) && !empty($data->module)) {
2729 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
2730 if (empty($data->moduleinstance)) {
2732 'Could not match the module instance in course_completion_criteria, so skipping',
2738 $data->module = null;
2739 $data->moduleinstance = null;
2742 // We backup the course shortname rather than the ID so that we can match back to the course
2743 if (!empty($data->courseinstanceshortname)) {
2744 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
2745 if (!$courseinstanceid) {
2747 'Could not match the course instance in course_completion_criteria, so skipping',
2753 $courseinstanceid = null;
2755 $data->courseinstance = $courseinstanceid;
2758 'course' => $data->course,
2759 'criteriatype' => $data->criteriatype,
2760 'enrolperiod' => $data->enrolperiod,
2761 'courseinstance' => $data->courseinstance,
2762 'module' => $data->module,
2763 'moduleinstance' => $data->moduleinstance,
2764 'timeend' => $data->timeend,
2765 'gradepass' => $data->gradepass,
2766 'role' => $data->role
2768 $newid = $DB->insert_record('course_completion_criteria', $params);
2769 $this->set_mapping('course_completion_criteria', $data->id, $newid);
2773 * Processes course compltion criteria complete records
2775 * @global moodle_database $DB
2776 * @param stdClass $data
2778 public function process_course_completion_crit_compl($data) {
2781 $data = (object)$data;
2783 // This may be empty if criteria could not be restored
2784 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
2786 $data->course = $this->get_courseid();
2787 $data->userid = $this->get_mappingid('user', $data->userid);
2789 if (!empty($data->criteriaid) && !empty($data->userid)) {
2791 'userid' => $data->userid,
2792 'course' => $data->course,
2793 'criteriaid' => $data->criteriaid,
2794 'timecompleted' => $this->apply_date_offset($data->timecompleted)
2796 if (isset($data->gradefinal)) {
2797 $params['gradefinal'] = $data->gradefinal;
2799 if (isset($data->unenroled)) {
2800 $params['unenroled'] = $data->unenroled;
2802 $DB->insert_record('course_completion_crit_compl', $params);
2807 * Process course completions
2809 * @global moodle_database $DB
2810 * @param stdClass $data
2812 public function process_course_completions($data) {
2815 $data = (object)$data;
2817 $data->course = $this->get_courseid();
2818 $data->userid = $this->get_mappingid('user', $data->userid);
2820 if (!empty($data->userid)) {
2822 'userid' => $data->userid,
2823 'course' => $data->course,
2824 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
2825 'timestarted' => $this->apply_date_offset($data->timestarted),
2826 'timecompleted' => $this->apply_date_offset($data->timecompleted),
2827 'reaggregate' => $data->reaggregate
2830 $existing = $DB->get_record('course_completions', array(
2831 'userid' => $data->userid,
2832 'course' => $data->course
2835 // MDL-46651 - If cron writes out a new record before we get to it
2836 // then we should replace it with the Truth data from the backup.
2837 // This may be obsolete after MDL-48518 is resolved
2839 $params['id'] = $existing->id;
2840 $DB->update_record('course_completions', $params);
2842 $DB->insert_record('course_completions', $params);
2848 * Process course completion aggregate methods
2850 * @global moodle_database $DB
2851 * @param stdClass $data
2853 public function process_course_completion_aggr_methd($data) {
2856 $data = (object)$data;
2858 $data->course = $this->get_courseid();
2860 // Only create the course_completion_aggr_methd records if
2861 // the target course has not them defined. MDL-28180
2862 if (!$DB->record_exists('course_completion_aggr_methd', array(
2863 'course' => $data->course,
2864 'criteriatype' => $data->criteriatype))) {
2866 'course' => $data->course,
2867 'criteriatype' => $data->criteriatype,
2868 'method' => $data->method,
2869 'value' => $data->value,
2871 $DB->insert_record('course_completion_aggr_methd', $params);
2878 * This structure step restores course logs (cmid = 0), delegating
2879 * the hard work to the corresponding {@link restore_logs_processor} passing the
2880 * collection of {@link restore_log_rule} rules to be observed as they are defined
2881 * by the task. Note this is only executed based in the 'logs' setting.
2883 * NOTE: This is executed by final task, to have all the activities already restored
2885 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2886 * records are. There are others like 'calendar' and 'upload' that will be handled
2889 * NOTE: All the missing actions (not able to be restored) are sent to logs for
2890 * debugging purposes
2892 class restore_course_logs_structure_step extends restore_structure_step {
2895 * Conditionally decide if this step should be executed.
2897 * This function checks the following parameter:
2899 * 1. the course/logs.xml file exists
2901 * @return bool true is safe to execute, false otherwise
2903 protected function execute_condition() {
2905 // Check it is included in the backup
2906 $fullpath = $this->task->get_taskbasepath();
2907 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2908 if (!file_exists($fullpath)) {
2909 // Not found, can't restore course logs
2916 protected function define_structure() {
2920 // Simple, one plain level of information contains them
2921 $paths[] = new restore_path_element('log', '/logs/log');
2926 protected function process_log($data) {
2929 $data = (object)($data);
2931 $data->time = $this->apply_date_offset($data->time);
2932 $data->userid = $this->get_mappingid('user', $data->userid);
2933 $data->course = $this->get_courseid();
2936 // For any reason user wasn't remapped ok, stop processing this
2937 if (empty($data->userid)) {
2941 // Everything ready, let's delegate to the restore_logs_processor
2943 // Set some fixed values that will save tons of DB requests
2945 'course' => $this->get_courseid());
2946 // Get instance and process log record
2947 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2949 // If we have data, insert it, else something went wrong in the restore_logs_processor
2951 if (empty($data->url)) {
2954 if (empty($data->info)) {
2957 // Store the data in the legacy log table if we are still using it.
2958 $manager = get_log_manager();
2959 if (method_exists($manager, 'legacy_add_to_log')) {
2960 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
2961 $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
2968 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2969 * sharing its same structure but modifying the way records are handled
2971 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2973 protected function process_log($data) {
2976 $data = (object)($data);
2978 $data->time = $this->apply_date_offset($data->time);
2979 $data->userid = $this->get_mappingid('user', $data->userid);
2980 $data->course = $this->get_courseid();
2981 $data->cmid = $this->task->get_moduleid();
2983 // For any reason user wasn't remapped ok, stop processing this
2984 if (empty($data->userid)) {
2988 // Everything ready, let's delegate to the restore_logs_processor
2990 // Set some fixed values that will save tons of DB requests
2992 'course' => $this->get_courseid(),
2993 'course_module' => $this->task->get_moduleid(),
2994 $this->task->get_modulename() => $this->task->get_activityid());
2995 // Get instance and process log record
2996 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2998 // If we have data, insert it, else something went wrong in the restore_logs_processor
3000 if (empty($data->url)) {
3003 if (empty($data->info)) {
3006 // Store the data in the legacy log table if we are still using it.
3007 $manager = get_log_manager();
3008 if (method_exists($manager, 'legacy_add_to_log')) {
3009 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3010 $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3017 * Structure step in charge of restoring the logstores.xml file for the course logs.
3019 * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3020 * it, for logs belonging to the course level.
3022 class restore_course_logstores_structure_step extends restore_structure_step {
3025 * Conditionally decide if this step should be executed.
3027 * This function checks the following parameter:
3029 * 1. the logstores.xml file exists
3031 * @return bool true is safe to execute, false otherwise
3033 protected function execute_condition() {
3035 // Check it is included in the backup.
3036 $fullpath = $this->task->get_taskbasepath();
3037 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3038 if (!file_exists($fullpath)) {
3039 // Not found, can't restore logstores.xml information.
3047 * Return the elements to be processed on restore of logstores.
3049 * @return restore_path_element[] array of elements to be processed on restore.
3051 protected function define_structure() {
3055 $logstore = new restore_path_element('logstore', '/logstores/logstore');
3056 $paths[] = $logstore;
3058 // Add logstore subplugin support to the 'logstore' element.
3059 $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3061 return array($logstore);
3065 * Process the 'logstore' element,
3067 * Note: This is empty by definition in backup, because stores do not share any
3068 * data between them, so there is nothing to process here.
3070 * @param array $data element data
3072 protected function process_logstore($data) {
3078 * Structure step in charge of restoring the logstores.xml file for the activity logs.
3080 * Note: Activity structure is completely equivalent to the course one, so just extend it.
3082 class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3086 * Restore course competencies structure step.
3088 class restore_course_competencies_structure_step extends restore_structure_step {
3091 * Returns the structure.
3095 protected function define_structure() {
3096 $userinfo = $this->get_setting_value('users');
3098 new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3099 new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3102 $paths[] = new restore_path_element('user_competency_course',
3103 '/course_competencies/user_competencies/user_competency');
3109 * Process a course competency settings.
3111 * @param array $data The data.
3113 public function process_course_competency_settings($data) {
3115 $data = (object) $data;
3117 // We do not restore the course settings during merge.
3118 $target = $this->get_task()->get_target();
3119 if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) {
3123 $courseid = $this->task->get_courseid();
3124 $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3125 array('courseid' => $courseid));
3127 // Strangely the course settings already exist, let's just leave them as is then.
3129 $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING);
3133 $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3134 $settings = new \core_competency\course_competency_settings(0, $data);
3135 $settings->create();
3139 * Process a course competency.
3141 * @param array $data The data.
3143 public function process_course_competency($data) {
3144 $data = (object) $data;
3146 // Mapping the competency by ID numbers.
3147 $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3151 $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3152 'competencyframeworkid' => $framework->get_id()));
3156 $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get_id());
3159 'competencyid' => $competency->get_id(),
3160 'courseid' => $this->task->get_courseid()
3162 $query = 'competencyid = :competencyid AND courseid = :courseid';
3163 $existing = \core_competency\course_competency::record_exists_select($query, $params);
3166 // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3167 $record = (object) $params;
3168 $record->ruleoutcome = $data->ruleoutcome;
3169 $coursecompetency = new \core_competency\course_competency(0, $record);
3170 $coursecompetency->create();
3175 * Process the user competency course.
3177 * @param array $data The data.
3179 public function process_user_competency_course($data) {
3181 $data = (object) $data;
3183 $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid);
3184 if (!$data->competencyid) {
3185 // This is strange, the competency does not belong to the course.
3187 } else if ($data->grade === null) {
3188 // We do not need to do anything when there is no grade.
3192 $data->userid = $this->get_mappingid('user', $data->userid);
3193 $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
3195 // The method add_evidence also sets the course rating.
3196 \core_competency\api::add_evidence($data->userid,
3197 $data->competencyid,
3198 $this->task->get_contextid(),
3199 \core_competency\evidence::ACTION_OVERRIDE,
3200 'evidence_courserestored',
3210 * Execute conditions.
3214 protected function execute_condition() {
3216 // Do not execute if competencies are not included.
3217 if (!$this->get_setting_value('competencies')) {
3221 // Do not execute if the competencies XML file is not found.
3222 $fullpath = $this->task->get_taskbasepath();
3223 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3224 if (!file_exists($fullpath)) {
3233 * Restore activity competencies structure step.
3235 class restore_activity_competencies_structure_step extends restore_structure_step {
3238 * Defines the structure.
3242 protected function define_structure() {
3244 new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3250 * Process a course module competency.