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 // Identify the backup we're dealing with.
125 $backuprelease = floatval($this->get_task()->get_info()->backup_release
); // The major version: 2.9, 3.0, ...
127 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release
, $matches);
128 if (!empty($matches[1])) {
129 $backupbuild = (int) $matches[1]; // The date of Moodle build at the time of the backup.
132 // On older versions the freeze value has to be converted.
133 // We do this from here as it is happening right before the file is read.
134 // This only targets the backup files that can contain the legacy freeze.
135 if ($backupbuild > 20150618 && ($backuprelease < 3.0 ||
$backupbuild < 20160527)) {
136 $this->rewrite_step_backup_file_for_legacy_freeze($fullpath);
139 // Arrived here, execute the step
143 protected function define_structure() {
145 $userinfo = $this->task
->get_setting_value('users');
147 $paths[] = new restore_path_element('attributes', '/gradebook/attributes');
148 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
149 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
151 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
153 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
154 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
159 protected function process_attributes($data) {
160 // For non-merge restore types:
161 // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
162 $target = $this->get_task()->get_target();
163 if ($target == backup
::TARGET_CURRENT_DELETING ||
$target == backup
::TARGET_EXISTING_DELETING
) {
164 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
166 if (!empty($data['calculations_freeze'])) {
167 if ($target == backup
::TARGET_NEW_COURSE ||
$target == backup
::TARGET_CURRENT_DELETING ||
168 $target == backup
::TARGET_EXISTING_DELETING
) {
169 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
174 protected function process_grade_item($data) {
177 $data = (object)$data;
180 $data->course
= $this->get_courseid();
182 $data->courseid
= $this->get_courseid();
184 if ($data->itemtype
=='manual') {
185 // manual grade items store category id in categoryid
186 $data->categoryid
= $this->get_mappingid('grade_category', $data->categoryid
, NULL);
187 // if mapping failed put in course's grade category
188 if (NULL == $data->categoryid
) {
189 $coursecat = grade_category
::fetch_course_category($this->get_courseid());
190 $data->categoryid
= $coursecat->id
;
192 } else if ($data->itemtype
=='course') {
193 // course grade item stores their category id in iteminstance
194 $coursecat = grade_category
::fetch_course_category($this->get_courseid());
195 $data->iteminstance
= $coursecat->id
;
196 } else if ($data->itemtype
=='category') {
197 // category grade items store their category id in iteminstance
198 $data->iteminstance
= $this->get_mappingid('grade_category', $data->iteminstance
, NULL);
200 throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype
);
203 $data->scaleid
= $this->get_mappingid('scale', $data->scaleid
, NULL);
204 $data->outcomeid
= $this->get_mappingid('outcome', $data->outcomeid
, NULL);
206 $data->locktime
= $this->apply_date_offset($data->locktime
);
208 $coursecategory = $newitemid = null;
209 //course grade item should already exist so updating instead of inserting
210 if($data->itemtype
=='course') {
211 //get the ID of the already created grade item
212 $gi = new stdclass();
213 $gi->courseid
= $this->get_courseid();
214 $gi->itemtype
= $data->itemtype
;
216 //need to get the id of the grade_category that was automatically created for the course
217 $category = new stdclass();
218 $category->courseid
= $this->get_courseid();
219 $category->parent
= null;
220 //course category fullname starts out as ? but may be edited
221 //$category->fullname = '?';
222 $coursecategory = $DB->get_record('grade_categories', (array)$category);
223 $gi->iteminstance
= $coursecategory->id
;
225 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
226 if (!empty($existinggradeitem)) {
227 $data->id
= $newitemid = $existinggradeitem->id
;
228 $DB->update_record('grade_items', $data);
230 } else if ($data->itemtype
== 'manual') {
231 // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
233 'itemtype' => $data->itemtype
,
234 'courseid' => $data->courseid
,
235 'itemname' => $data->itemname
,
236 'categoryid' => $data->categoryid
,
238 $newitemid = $DB->get_field('grade_items', 'id', $gi);
241 if (empty($newitemid)) {
242 //in case we found the course category but still need to insert the course grade item
243 if ($data->itemtype
=='course' && !empty($coursecategory)) {
244 $data->iteminstance
= $coursecategory->id
;
247 $newitemid = $DB->insert_record('grade_items', $data);
248 $data->id
= $newitemid;
249 $gradeitem = new grade_item($data);
250 core\event\grade_item_created
::create_from_grade_item($gradeitem)->trigger();
252 $this->set_mapping('grade_item', $oldid, $newitemid);
255 protected function process_grade_grade($data) {
258 $data = (object)$data;
260 $olduserid = $data->userid
;
262 $data->itemid
= $this->get_new_parentid('grade_item');
264 $data->userid
= $this->get_mappingid('user', $data->userid
, null);
265 if (!empty($data->userid
)) {
266 $data->usermodified
= $this->get_mappingid('user', $data->usermodified
, null);
267 $data->locktime
= $this->apply_date_offset($data->locktime
);
269 $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid
, 'itemid' => $data->itemid
));
271 $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
272 $this->log($message, backup
::LOG_DEBUG
);
274 $newitemid = $DB->insert_record('grade_grades', $data);
275 $this->set_mapping('grade_grades', $oldid, $newitemid);
278 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
279 $this->log($message, backup
::LOG_DEBUG
);
283 protected function process_grade_category($data) {
286 $data = (object)$data;
289 $data->course
= $this->get_courseid();
290 $data->courseid
= $data->course
;
293 //no parent means a course level grade category. That may have been created when the course was created
294 if(empty($data->parent
)) {
295 //parent was being saved as 0 when it should be null
296 $data->parent
= null;
298 //get the already created course level grade category
299 $category = new stdclass();
300 $category->courseid
= $this->get_courseid();
301 $category->parent
= null;
303 $coursecategory = $DB->get_record('grade_categories', (array)$category);
304 if (!empty($coursecategory)) {
305 $data->id
= $newitemid = $coursecategory->id
;
306 $DB->update_record('grade_categories', $data);
310 // Add a warning about a removed setting.
311 if (!empty($data->aggregatesubcats
)) {
312 set_config('show_aggregatesubcats_upgrade_' . $data->courseid
, 1);
315 //need to insert a course category
316 if (empty($newitemid)) {
317 $newitemid = $DB->insert_record('grade_categories', $data);
319 $this->set_mapping('grade_category', $oldid, $newitemid);
321 protected function process_grade_letter($data) {
324 $data = (object)$data;
327 $data->contextid
= context_course
::instance($this->get_courseid())->id
;
329 $gradeletter = (array)$data;
330 unset($gradeletter['id']);
331 if (!$DB->record_exists('grade_letters', $gradeletter)) {
332 $newitemid = $DB->insert_record('grade_letters', $data);
334 $newitemid = $data->id
;
337 $this->set_mapping('grade_letter', $oldid, $newitemid);
339 protected function process_grade_setting($data) {
342 $data = (object)$data;
345 $data->courseid
= $this->get_courseid();
347 $target = $this->get_task()->get_target();
348 if ($data->name
== 'minmaxtouse' &&
349 ($target == backup
::TARGET_CURRENT_ADDING ||
$target == backup
::TARGET_EXISTING_ADDING
)) {
350 // We never restore minmaxtouse during merge.
354 if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid
, 'name' => $data->name
))) {
355 $newitemid = $DB->insert_record('grade_settings', $data);
357 $newitemid = $data->id
;
360 if (!empty($oldid)) {
361 // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
362 $this->set_mapping('grade_setting', $oldid, $newitemid);
367 * put all activity grade items in the correct grade category and mark all for recalculation
369 protected function after_execute() {
373 'backupid' => $this->get_restoreid(),
374 'itemname' => 'grade_item'//,
375 //'itemid' => $itemid
377 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
379 // We need this for calculation magic later on.
383 foreach($rs as $grade_item_backup) {
385 // Store the oldid with the new id.
386 $mappings[$grade_item_backup->itemid
] = $grade_item_backup->newitemid
;
388 $updateobj = new stdclass();
389 $updateobj->id
= $grade_item_backup->newitemid
;
391 //if this is an activity grade item that needs to be put back in its correct category
392 if (!empty($grade_item_backup->parentitemid
)) {
393 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid
, null);
394 if (!is_null($oldcategoryid)) {
395 $updateobj->categoryid
= $oldcategoryid;
396 $DB->update_record('grade_items', $updateobj);
399 //mark course and category items as needing to be recalculated
400 $updateobj->needsupdate
=1;
401 $DB->update_record('grade_items', $updateobj);
407 // We need to update the calculations for calculated grade items that may reference old
408 // grade item ids using ##gi\d+##.
409 // $mappings can be empty, use 0 if so (won't match ever)
410 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED
, 'param', true, 0);
411 $sql = "SELECT gi.id, gi.calculation
412 FROM {grade_items} gi
413 WHERE gi.id {$sql} AND
414 calculation IS NOT NULL";
415 $rs = $DB->get_recordset_sql($sql, $params);
416 foreach ($rs as $gradeitem) {
417 // Collect all of the used grade item id references
418 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation
, $matches) < 1) {
419 // This calculation doesn't reference any other grade items... EASY!
422 // For this next bit we are going to do the replacement of id's in two steps:
423 // 1. We will replace all old id references with a special mapping reference.
424 // 2. We will replace all mapping references with id's
425 // Why do we do this?
426 // Because there potentially there will be an overlap of ids within the query and we
427 // we substitute the wrong id.. safest way around this is the two step system
428 $calculationmap = array();
430 foreach ($matches[1] as $match) {
431 // Check that the old id is known to us, if not it was broken to begin with and will
432 // continue to be broken.
433 if (!array_key_exists($match, $mappings)) {
436 // Our special mapping key
437 $mapping = '##MAPPING'.$mapcount.'##';
438 // The old id that exists within the calculation now
439 $oldid = '##gi'.$match.'##';
440 // The new id that we want to replace the old one with.
441 $newid = '##gi'.$mappings[$match].'##';
442 // Replace in the special mapping key
443 $gradeitem->calculation
= str_replace($oldid, $mapping, $gradeitem->calculation
);
444 // And record the mapping
445 $calculationmap[$mapping] = $newid;
448 // Iterate all special mappings for this calculation and replace in the new id's
449 foreach ($calculationmap as $mapping => $newid) {
450 $gradeitem->calculation
= str_replace($mapping, $newid, $gradeitem->calculation
);
452 // Update the calculation now that its being remapped
453 $DB->update_record('grade_items', $gradeitem);
457 // Need to correct the grade category path and parent
459 'courseid' => $this->get_courseid()
462 $rs = $DB->get_recordset('grade_categories', $conditions);
463 // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
464 foreach ($rs as $gc) {
465 if (!empty($gc->parent
)) {
466 $grade_category = new stdClass();
467 $grade_category->id
= $gc->id
;
468 $grade_category->parent
= $this->get_mappingid('grade_category', $gc->parent
);
469 $DB->update_record('grade_categories', $grade_category);
474 // Now we can rebuild all the paths
475 $rs = $DB->get_recordset('grade_categories', $conditions);
476 foreach ($rs as $gc) {
477 $grade_category = new stdClass();
478 $grade_category->id
= $gc->id
;
479 $grade_category->path
= grade_category
::build_path($gc);
480 $grade_category->depth
= substr_count($grade_category->path
, '/') - 1;
481 $DB->update_record('grade_categories', $grade_category);
485 // Check what to do with the minmaxtouse setting.
486 $this->check_minmaxtouse();
488 // Freeze gradebook calculations if needed.
489 $this->gradebook_calculation_freeze();
491 // Ensure the module cache is current when recalculating grades.
492 rebuild_course_cache($this->get_courseid(), true);
494 // Restore marks items as needing update. Update everything now.
495 grade_regrade_final_grades($this->get_courseid());
499 * Freeze gradebook calculation if needed.
501 * This is similar to various upgrade scripts that check if the freeze is needed.
503 protected function gradebook_calculation_freeze() {
505 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
506 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release
, $matches);
507 $backupbuild = (int)$matches[1];
508 // The function floatval will return a float even if there is text mixed with the release number.
509 $backuprelease = floatval($this->get_task()->get_info()->backup_release
);
511 // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
512 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) {
513 require_once($CFG->libdir
. '/db/upgradelib.php');
514 upgrade_extra_credit_weightoverride($this->get_courseid());
516 // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
517 if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) {
518 require_once($CFG->libdir
. '/db/upgradelib.php');
519 upgrade_calculated_grade_items($this->get_courseid());
521 // Courses from before 3.1 (20160518) may have a letter boundary problem and should be checked for this issue.
522 // Backups from before and including 2.9 could have a build number that is greater than 20160518 and should
523 // be checked for this problem.
524 if (!$gradebookcalculationsfreeze && ($backupbuild < 20160518 ||
$backuprelease <= 2.9)) {
525 require_once($CFG->libdir
. '/db/upgradelib.php');
526 upgrade_course_letter_boundary($this->get_courseid());
532 * Checks what should happen with the course grade setting minmaxtouse.
534 * This is related to the upgrade step at the time the setting was added.
539 protected function check_minmaxtouse() {
541 require_once($CFG->libdir
. '/gradelib.php');
543 $userinfo = $this->task
->get_setting_value('users');
544 $settingname = 'minmaxtouse';
545 $courseid = $this->get_courseid();
546 $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
547 $version28start = 2014111000.00;
548 $version28last = 2014111006.05;
549 $version29start = 2015051100.00;
550 $version29last = 2015060400.02;
552 $target = $this->get_task()->get_target();
553 if ($minmaxtouse === false &&
554 ($target != backup
::TARGET_CURRENT_ADDING
&& $target != backup
::TARGET_EXISTING_ADDING
)) {
555 // The setting was not found because this setting did not exist at the time the backup was made.
556 // And we are not restoring as merge, in which case we leave the course as it was.
557 $version = $this->get_task()->get_info()->moodle_version
;
559 if ($version < $version28start) {
560 // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
561 if ($CFG->grade_minmaxtouse
!= GRADE_MIN_MAX_FROM_GRADE_ITEM
) {
562 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM
);
565 } else if (($version >= $version28start && $version < $version28last) ||
566 ($version >= $version29start && $version < $version29last)) {
567 // They should be using grade_grade when the course has inconsistencies.
570 FROM {grade_items} gi
571 JOIN {grade_grades} gg
573 WHERE gi.courseid = ?
574 AND (gi.itemtype != ? AND gi.itemtype != ?)
575 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
577 // The course can only have inconsistencies when we restore the user info,
578 // we do not need to act on existing grades that were not restored as part of this backup.
579 if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
581 // Display the notice as we do during upgrade.
582 set_config('show_min_max_grades_changed_' . $courseid, 1);
584 if ($CFG->grade_minmaxtouse
!= GRADE_MIN_MAX_FROM_GRADE_GRADE
) {
585 // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
586 // If they are using the site-wide grade_grade setting, we only want to notice them.
587 grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE
);
592 // This should never happen because from now on minmaxtouse is always saved in backups.
598 * Rewrite step definition to handle the legacy freeze attribute.
600 * In previous backups the calculations_freeze property was stored as an attribute of the
601 * top level node <gradebook>. The backup API, however, do not process grandparent nodes.
602 * It only processes definitive children, and their parent attributes.
606 * <gradebook calculations_freeze="20160511">
608 * <grade_category id="10">
612 * </grade_categories>
616 * And this method will convert it to:
620 * <calculations_freeze>20160511</calculations_freeze>
623 * <grade_category id="10">
627 * </grade_categories>
631 * Note that we cannot just load the XML file in memory as it could potentially be huge.
632 * We can also completely ignore if the node <attributes> is already in the backup
633 * file as it never existed before.
635 * @param string $filepath The absolute path to the XML file.
638 protected function rewrite_step_backup_file_for_legacy_freeze($filepath) {
640 $newfile = make_request_directory(true) . DIRECTORY_SEPARATOR
. 'file.xml';
641 $fr = fopen($filepath, 'r');
642 $fw = fopen($newfile, 'w');
644 while (($line = fgets($fr, 4096)) !== false) {
645 if (!$foundnode && strpos($line, '<gradebook ') === 0) {
648 $pattern = '@calculations_freeze=.([0-9]+).@';
649 if (preg_match($pattern, $line, $matches)) {
650 $freeze = $matches[1];
651 $line = preg_replace($pattern, '', $line);
652 $line .= " <attributes>\n <calculations_freeze>$freeze</calculations_freeze>\n </attributes>\n";
658 throw new restore_step_exception('Error while attempting to rewrite the gradebook step file.');
662 if (!rename($newfile, $filepath)) {
663 throw new restore_step_exception('Error while attempting to rename the gradebook step file.');
678 * Step in charge of restoring the grade history of a course.
680 * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
681 * we do not want to restore the history if the gradebook and its content has not been
682 * restored. At least for now.
684 class restore_grade_history_structure_step
extends restore_structure_step
{
686 protected function execute_condition() {
689 if ($this->get_courseid() == SITEID
) {
693 // No gradebook info found, don't execute.
694 $fullpath = $this->task
->get_taskbasepath();
695 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
696 if (!file_exists($fullpath)) {
700 // Some module present in backup file isn't available to restore in this site, don't execute.
701 if ($this->task
->is_missing_modules()) {
705 // Some activity has been excluded to be restored, don't execute.
706 if ($this->task
->is_excluding_activities()) {
710 // There should only be one grade category (the 1 associated with the course itself).
711 $category = new stdclass();
712 $category->courseid
= $this->get_courseid();
713 $catcount = $DB->count_records('grade_categories', (array)$category);
718 // Arrived here, execute the step.
722 protected function define_structure() {
726 $userinfo = $this->get_setting_value('users');
727 $history = $this->get_setting_value('grade_histories');
729 if ($userinfo && $history) {
730 $paths[] = new restore_path_element('grade_grade',
731 '/grade_history/grade_grades/grade_grade');
737 protected function process_grade_grade($data) {
740 $data = (object)($data);
741 $olduserid = $data->userid
;
744 $data->userid
= $this->get_mappingid('user', $data->userid
, null);
745 if (!empty($data->userid
)) {
746 // Do not apply the date offsets as this is history.
747 $data->itemid
= $this->get_mappingid('grade_item', $data->itemid
);
748 $data->oldid
= $this->get_mappingid('grade_grades', $data->oldid
);
749 $data->usermodified
= $this->get_mappingid('user', $data->usermodified
, null);
750 $data->rawscaleid
= $this->get_mappingid('scale', $data->rawscaleid
);
751 $DB->insert_record('grade_grades_history', $data);
753 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
754 $this->log($message, backup
::LOG_DEBUG
);
761 * decode all the interlinks present in restored content
762 * relying 100% in the restore_decode_processor that handles
763 * both the contents to modify and the rules to be applied
765 class restore_decode_interlinks
extends restore_execution_step
{
767 protected function define_execution() {
768 // Get the decoder (from the plan)
769 $decoder = $this->task
->get_decoder();
770 restore_decode_processor
::register_link_decoders($decoder); // Add decoder contents and rules
771 // And launch it, everything will be processed
777 * first, ensure that we have no gaps in section numbers
778 * and then, rebuid the course cache
780 class restore_rebuild_course_cache
extends restore_execution_step
{
782 protected function define_execution() {
785 // Although there is some sort of auto-recovery of missing sections
786 // present in course/formats... here we check that all the sections
787 // from 0 to MAX(section->section) exist, creating them if necessary
788 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
789 // Iterate over all sections
790 for ($i = 0; $i <= $maxsection; $i++
) {
791 // If the section $i doesn't exist, create it
792 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
794 'course' => $this->get_courseid(),
796 'timemodified' => time());
797 $DB->insert_record('course_sections', $sectionrec); // missing section created
801 // Rebuild cache now that all sections are in place
802 rebuild_course_cache($this->get_courseid());
803 cache_helper
::purge_by_event('changesincourse');
804 cache_helper
::purge_by_event('changesincoursecat');
809 * Review all the tasks having one after_restore method
810 * executing it to perform some final adjustments of information
811 * not available when the task was executed.
813 class restore_execute_after_restore
extends restore_execution_step
{
815 protected function define_execution() {
817 // Simply call to the execute_after_restore() method of the task
818 // that always is the restore_final_task
819 $this->task
->launch_execute_after_restore();
825 * Review all the (pending) block positions in backup_ids, matching by
826 * contextid, creating positions as needed. This is executed by the
827 * final task, once all the contexts have been created
829 class restore_review_pending_block_positions
extends restore_execution_step
{
831 protected function define_execution() {
834 // Get all the block_position objects pending to match
835 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
836 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
837 // Process block positions, creating them or accumulating for final step
838 foreach($rs as $posrec) {
839 // Get the complete position object out of the info field.
840 $position = backup_controller_dbops
::decode_backup_temp_info($posrec->info
);
841 // If position is for one already mapped (known) contextid
842 // process it now, creating the position, else nothing to
843 // do, position finally discarded
844 if ($newctx = restore_dbops
::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid
)) {
845 $position->contextid
= $newctx->newitemid
;
846 // Create the block position
847 $DB->insert_record('block_positions', $position);
856 * Updates the availability data for course modules and sections.
858 * Runs after the restore of all course modules, sections, and grade items has
859 * completed. This is necessary in order to update IDs that have changed during
862 * @package core_backup
863 * @copyright 2014 The Open University
864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
866 class restore_update_availability
extends restore_execution_step
{
868 protected function define_execution() {
871 // Note: This code runs even if availability is disabled when restoring.
872 // That will ensure that if you later turn availability on for the site,
873 // there will be no incorrect IDs. (It doesn't take long if the restored
874 // data does not contain any availability information.)
876 // Get modinfo with all data after resetting cache.
877 rebuild_course_cache($this->get_courseid(), true);
878 $modinfo = get_fast_modinfo($this->get_courseid());
880 // Get the date offset for this restore.
881 $dateoffset = $this->apply_date_offset(1) - 1;
883 // Update all sections that were restored.
884 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
885 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
886 $sectionsbyid = null;
887 foreach ($rs as $rec) {
888 if (is_null($sectionsbyid)) {
889 $sectionsbyid = array();
890 foreach ($modinfo->get_section_info_all() as $section) {
891 $sectionsbyid[$section->id
] = $section;
894 if (!array_key_exists($rec->newitemid
, $sectionsbyid)) {
895 // If the section was not fully restored for some reason
896 // (e.g. due to an earlier error), skip it.
897 $this->get_logger()->process('Section not fully restored: id ' .
898 $rec->newitemid
, backup
::LOG_WARNING
);
901 $section = $sectionsbyid[$rec->newitemid
];
902 if (!is_null($section->availability
)) {
903 $info = new \core_availability\
info_section($section);
904 $info->update_after_restore($this->get_restoreid(),
905 $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task
);
910 // Update all modules that were restored.
911 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
912 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
913 foreach ($rs as $rec) {
914 if (!array_key_exists($rec->newitemid
, $modinfo->cms
)) {
915 // If the module was not fully restored for some reason
916 // (e.g. due to an earlier error), skip it.
917 $this->get_logger()->process('Module not fully restored: id ' .
918 $rec->newitemid
, backup
::LOG_WARNING
);
921 $cm = $modinfo->get_cm($rec->newitemid
);
922 if (!is_null($cm->availability
)) {
923 $info = new \core_availability\
info_module($cm);
924 $info->update_after_restore($this->get_restoreid(),
925 $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task
);
934 * Process legacy module availability records in backup_ids.
936 * Matches course modules and grade item id once all them have been already restored.
937 * Only if all matchings are satisfied the availability condition will be created.
938 * At the same time, it is required for the site to have that functionality enabled.
940 * This step is included only to handle legacy backups (2.6 and before). It does not
941 * do anything for newer backups.
943 * @copyright 2014 The Open University
944 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
946 class restore_process_course_modules_availability
extends restore_execution_step
{
948 protected function define_execution() {
951 // Site hasn't availability enabled
952 if (empty($CFG->enableavailability
)) {
956 // Do both modules and sections.
957 foreach (array('module', 'section') as $table) {
958 // Get all the availability objects to process.
959 $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
960 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
961 // Process availabilities, creating them if everything matches ok.
962 foreach ($rs as $availrec) {
963 $allmatchesok = true;
964 // Get the complete legacy availability object.
965 $availability = backup_controller_dbops
::decode_backup_temp_info($availrec->info
);
967 // Note: This code used to update IDs, but that is now handled by the
968 // current code (after restore) instead of this legacy code.
970 // Get showavailability option.
971 $thingid = ($table === 'module') ?
$availability->coursemoduleid
:
972 $availability->coursesectionid
;
973 $showrec = restore_dbops
::get_backup_ids_record($this->get_restoreid(),
974 $table . '_showavailability', $thingid);
976 // Should not happen.
977 throw new coding_exception('No matching showavailability record');
979 $show = $showrec->info
->showavailability
;
981 // The $availability object is now in the format used in the old
982 // system. Interpret this and convert to new system.
983 $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
984 array('id' => $thingid), MUST_EXIST
);
985 $newvalue = \core_availability\info
::add_legacy_availability_condition(
986 $currentvalue, $availability, $show);
987 $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
988 array('id' => $thingid));
997 * Execution step that, *conditionally* (if there isn't preloaded information)
998 * will load the inforef files for all the included course/section/activity tasks
999 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
1001 class restore_load_included_inforef_records
extends restore_execution_step
{
1003 protected function define_execution() {
1005 if ($this->task
->get_preloaded_information()) { // if info is already preloaded, nothing to do
1009 // Get all the included tasks
1010 $tasks = restore_dbops
::get_included_tasks($this->get_restoreid());
1011 $progress = $this->task
->get_progress();
1012 $progress->start_progress($this->get_name(), count($tasks));
1013 foreach ($tasks as $task) {
1014 // Load the inforef.xml file if exists
1015 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
1016 if (file_exists($inforefpath)) {
1017 // Load each inforef file to temp_ids.
1018 restore_dbops
::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
1021 $progress->end_progress();
1026 * Execution step that will load all the needed files into backup_files_temp
1027 * - info: contains the whole original object (times, names...)
1028 * (all them being original ids as loaded from xml)
1030 class restore_load_included_files
extends restore_structure_step
{
1032 protected function define_structure() {
1034 $file = new restore_path_element('file', '/files/file');
1036 return array($file);
1040 * Process one <file> element from files.xml
1042 * @param array $data the element data
1044 public function process_file($data) {
1046 $data = (object)$data; // handy
1048 // load it if needed:
1049 // - it it is one of the annotated inforef files (course/section/activity/block)
1050 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
1051 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
1052 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
1053 $isfileref = restore_dbops
::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id
);
1054 $iscomponent = ($data->component
== 'user' ||
$data->component
== 'group' ||
$data->component
== 'badges' ||
1055 $data->component
== 'grouping' ||
$data->component
== 'grade' ||
1056 $data->component
== 'question' ||
substr($data->component
, 0, 5) == 'qtype');
1057 if ($isfileref ||
$iscomponent) {
1058 restore_dbops
::set_backup_files_record($this->get_restoreid(), $data);
1064 * Execution step that, *conditionally* (if there isn't preloaded information),
1065 * will load all the needed roles to backup_temp_ids. They will be stored with
1066 * "role" itemname. Also it will perform one automatic mapping to roles existing
1067 * in the target site, based in permissions of the user performing the restore,
1068 * archetypes and other bits. At the end, each original role will have its associated
1069 * target role or 0 if it's going to be skipped. Note we wrap everything over one
1070 * restore_dbops method, as far as the same stuff is going to be also executed
1071 * by restore prechecks
1073 class restore_load_and_map_roles
extends restore_execution_step
{
1075 protected function define_execution() {
1076 if ($this->task
->get_preloaded_information()) { // if info is already preloaded
1080 $file = $this->get_basepath() . '/roles.xml';
1081 // Load needed toles to temp_ids
1082 restore_dbops
::load_roles_to_tempids($this->get_restoreid(), $file);
1084 // Process roles, mapping/skipping. Any error throws exception
1085 // Note we pass controller's info because it can contain role mapping information
1086 // about manual mappings performed by UI
1087 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
);
1092 * Execution step that, *conditionally* (if there isn't preloaded information
1093 * and users have been selected in settings, will load all the needed users
1094 * to backup_temp_ids. They will be stored with "user" itemname and with
1095 * their original contextid as paremitemid
1097 class restore_load_included_users
extends restore_execution_step
{
1099 protected function define_execution() {
1101 if ($this->task
->get_preloaded_information()) { // if info is already preloaded, nothing to do
1104 if (!$this->task
->get_setting_value('users')) { // No userinfo being restored, nothing to do
1107 $file = $this->get_basepath() . '/users.xml';
1108 // Load needed users to temp_ids.
1109 restore_dbops
::load_users_to_tempids($this->get_restoreid(), $file, $this->task
->get_progress());
1114 * Execution step that, *conditionally* (if there isn't preloaded information
1115 * and users have been selected in settings, will process all the needed users
1116 * in order to decide and perform any action with them (create / map / error)
1117 * Note: Any error will cause exception, as far as this is the same processing
1118 * than the one into restore prechecks (that should have stopped process earlier)
1120 class restore_process_included_users
extends restore_execution_step
{
1122 protected function define_execution() {
1124 if ($this->task
->get_preloaded_information()) { // if info is already preloaded, nothing to do
1127 if (!$this->task
->get_setting_value('users')) { // No userinfo being restored, nothing to do
1130 restore_dbops
::process_included_users($this->get_restoreid(), $this->task
->get_courseid(),
1131 $this->task
->get_userid(), $this->task
->is_samesite(), $this->task
->get_progress());
1136 * Execution step that will create all the needed users as calculated
1137 * by @restore_process_included_users (those having newiteind = 0)
1139 class restore_create_included_users
extends restore_execution_step
{
1141 protected function define_execution() {
1143 restore_dbops
::create_included_users($this->get_basepath(), $this->get_restoreid(),
1144 $this->task
->get_userid(), $this->task
->get_progress());
1149 * Structure step that will create all the needed groups and groupings
1150 * by loading them from the groups.xml file performing the required matches.
1151 * Note group members only will be added if restoring user info
1153 class restore_groups_structure_step
extends restore_structure_step
{
1155 protected function define_structure() {
1157 $paths = array(); // Add paths here
1159 // Do not include group/groupings information if not requested.
1160 $groupinfo = $this->get_setting_value('groups');
1162 $paths[] = new restore_path_element('group', '/groups/group');
1163 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
1164 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
1169 // Processing functions go here
1170 public function process_group($data) {
1173 $data = (object)$data; // handy
1174 $data->courseid
= $this->get_courseid();
1176 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1177 // another a group in the same course
1178 $context = context_course
::instance($data->courseid
);
1179 if (isset($data->idnumber
) and has_capability('moodle/course:changeidnumber', $context, $this->task
->get_userid())) {
1180 if (groups_get_group_by_idnumber($data->courseid
, $data->idnumber
)) {
1181 unset($data->idnumber
);
1184 unset($data->idnumber
);
1187 $oldid = $data->id
; // need this saved for later
1189 $restorefiles = false; // Only if we end creating the group
1191 // Search if the group already exists (by name & description) in the target course
1192 $description_clause = '';
1193 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name
);
1194 if (!empty($data->description
)) {
1195 $description_clause = ' AND ' .
1196 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1197 $params['description'] = $data->description
;
1199 if (!$groupdb = $DB->get_record_sql("SELECT *
1201 WHERE courseid = :courseid
1202 AND name = :grname $description_clause", $params)) {
1203 // group doesn't exist, create
1204 $newitemid = $DB->insert_record('groups', $data);
1205 $restorefiles = true; // We'll restore the files
1207 // group exists, use it
1208 $newitemid = $groupdb->id
;
1210 // Save the id mapping
1211 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
1212 // Invalidate the course group data cache just in case.
1213 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid
));
1216 public function process_grouping($data) {
1219 $data = (object)$data; // handy
1220 $data->courseid
= $this->get_courseid();
1222 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1223 // another a grouping in the same course
1224 $context = context_course
::instance($data->courseid
);
1225 if (isset($data->idnumber
) and has_capability('moodle/course:changeidnumber', $context, $this->task
->get_userid())) {
1226 if (groups_get_grouping_by_idnumber($data->courseid
, $data->idnumber
)) {
1227 unset($data->idnumber
);
1230 unset($data->idnumber
);
1233 $oldid = $data->id
; // need this saved for later
1234 $restorefiles = false; // Only if we end creating the grouping
1236 // Search if the grouping already exists (by name & description) in the target course
1237 $description_clause = '';
1238 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name
);
1239 if (!empty($data->description
)) {
1240 $description_clause = ' AND ' .
1241 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1242 $params['description'] = $data->description
;
1244 if (!$groupingdb = $DB->get_record_sql("SELECT *
1246 WHERE courseid = :courseid
1247 AND name = :grname $description_clause", $params)) {
1248 // grouping doesn't exist, create
1249 $newitemid = $DB->insert_record('groupings', $data);
1250 $restorefiles = true; // We'll restore the files
1252 // grouping exists, use it
1253 $newitemid = $groupingdb->id
;
1255 // Save the id mapping
1256 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1257 // Invalidate the course group data cache just in case.
1258 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid
));
1261 public function process_grouping_group($data) {
1264 require_once($CFG->dirroot
.'/group/lib.php');
1266 $data = (object)$data;
1267 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid
), $data->timeadded
);
1270 protected function after_execute() {
1271 // Add group related files, matching with "group" mappings
1272 $this->add_related_files('group', 'icon', 'group');
1273 $this->add_related_files('group', 'description', 'group');
1274 // Add grouping related files, matching with "grouping" mappings
1275 $this->add_related_files('grouping', 'description', 'grouping');
1276 // Invalidate the course group data.
1277 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1283 * Structure step that will create all the needed group memberships
1284 * by loading them from the groups.xml file performing the required matches.
1286 class restore_groups_members_structure_step
extends restore_structure_step
{
1288 protected $plugins = null;
1290 protected function define_structure() {
1292 $paths = array(); // Add paths here
1294 if ($this->get_setting_value('groups') && $this->get_setting_value('users')) {
1295 $paths[] = new restore_path_element('group', '/groups/group');
1296 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1302 public function process_group($data) {
1303 $data = (object)$data; // handy
1306 // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1307 // Let's fake internal state to make $this->get_new_parentid('group') work.
1309 $this->set_mapping('group', $data->id
, $this->get_mappingid('group', $data->id
));
1312 public function process_member($data) {
1314 require_once("$CFG->dirroot/group/lib.php");
1316 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1318 $data = (object)$data; // handy
1320 // get parent group->id
1321 $data->groupid
= $this->get_new_parentid('group');
1323 // map user newitemid and insert if not member already
1324 if ($data->userid
= $this->get_mappingid('user', $data->userid
)) {
1325 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid
, 'userid' => $data->userid
))) {
1326 // Check the component, if any, exists.
1327 if (empty($data->component
)) {
1328 groups_add_member($data->groupid
, $data->userid
);
1330 } else if ((strpos($data->component
, 'enrol_') === 0)) {
1331 // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1332 // it is possible that enrolment was restored using different plugin type.
1333 if (!isset($this->plugins
)) {
1334 $this->plugins
= enrol_get_plugins(true);
1336 if ($enrolid = $this->get_mappingid('enrol', $data->itemid
)) {
1337 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1338 if (isset($this->plugins
[$instance->enrol
])) {
1339 $this->plugins
[$instance->enrol
]->restore_group_member($instance, $data->groupid
, $data->userid
);
1345 $dir = core_component
::get_component_directory($data->component
);
1346 if ($dir and is_dir($dir)) {
1347 if (component_callback($data->component
, 'restore_group_member', array($this, $data), true)) {
1351 // Bad luck, plugin could not restore the data, let's add normal membership.
1352 groups_add_member($data->groupid
, $data->userid
);
1353 $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1354 $this->log($message, backup
::LOG_WARNING
);
1362 * Structure step that will create all the needed scales
1363 * by loading them from the scales.xml
1365 class restore_scales_structure_step
extends restore_structure_step
{
1367 protected function define_structure() {
1369 $paths = array(); // Add paths here
1370 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1374 protected function process_scale($data) {
1377 $data = (object)$data;
1379 $restorefiles = false; // Only if we end creating the group
1381 $oldid = $data->id
; // need this saved for later
1383 // Look for scale (by 'scale' both in standard (course=0) and current course
1384 // with priority to standard scales (ORDER clause)
1385 // scale is not course unique, use get_record_sql to suppress warning
1386 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1387 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
1388 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale
);
1389 if (!$scadb = $DB->get_record_sql("SELECT *
1391 WHERE courseid IN (0, :courseid)
1392 AND $compare_scale_clause
1393 ORDER BY courseid", $params, IGNORE_MULTIPLE
)) {
1394 // Remap the user if possible, defaut to user performing the restore if not
1395 $userid = $this->get_mappingid('user', $data->userid
);
1396 $data->userid
= $userid ?
$userid : $this->task
->get_userid();
1397 // Remap the course if course scale
1398 $data->courseid
= $data->courseid ?
$this->get_courseid() : 0;
1399 // If global scale (course=0), check the user has perms to create it
1400 // falling to course scale if not
1401 $systemctx = context_system
::instance();
1402 if ($data->courseid
== 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task
->get_userid())) {
1403 $data->courseid
= $this->get_courseid();
1405 // scale doesn't exist, create
1406 $newitemid = $DB->insert_record('scale', $data);
1407 $restorefiles = true; // We'll restore the files
1409 // scale exists, use it
1410 $newitemid = $scadb->id
;
1412 // Save the id mapping (with files support at system context)
1413 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task
->get_old_system_contextid());
1416 protected function after_execute() {
1417 // Add scales related files, matching with "scale" mappings
1418 $this->add_related_files('grade', 'scale', 'scale', $this->task
->get_old_system_contextid());
1424 * Structure step that will create all the needed outocomes
1425 * by loading them from the outcomes.xml
1427 class restore_outcomes_structure_step
extends restore_structure_step
{
1429 protected function define_structure() {
1431 $paths = array(); // Add paths here
1432 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1436 protected function process_outcome($data) {
1439 $data = (object)$data;
1441 $restorefiles = false; // Only if we end creating the group
1443 $oldid = $data->id
; // need this saved for later
1445 // Look for outcome (by shortname both in standard (courseid=null) and current course
1446 // with priority to standard outcomes (ORDER clause)
1447 // outcome is not course unique, use get_record_sql to suppress warning
1448 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname
);
1449 if (!$outdb = $DB->get_record_sql('SELECT *
1450 FROM {grade_outcomes}
1451 WHERE shortname = :shortname
1452 AND (courseid = :courseid OR courseid IS NULL)
1453 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE
)) {
1455 $userid = $this->get_mappingid('user', $data->usermodified
);
1456 $data->usermodified
= $userid ?
$userid : $this->task
->get_userid();
1458 $data->scaleid
= $this->get_mappingid('scale', $data->scaleid
);
1459 // Remap the course if course outcome
1460 $data->courseid
= $data->courseid ?
$this->get_courseid() : null;
1461 // If global outcome (course=null), check the user has perms to create it
1462 // falling to course outcome if not
1463 $systemctx = context_system
::instance();
1464 if (is_null($data->courseid
) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task
->get_userid())) {
1465 $data->courseid
= $this->get_courseid();
1467 // outcome doesn't exist, create
1468 $newitemid = $DB->insert_record('grade_outcomes', $data);
1469 $restorefiles = true; // We'll restore the files
1471 // scale exists, use it
1472 $newitemid = $outdb->id
;
1474 // Set the corresponding grade_outcomes_courses record
1475 $outcourserec = new stdclass();
1476 $outcourserec->courseid
= $this->get_courseid();
1477 $outcourserec->outcomeid
= $newitemid;
1478 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1479 $DB->insert_record('grade_outcomes_courses', $outcourserec);
1481 // Save the id mapping (with files support at system context)
1482 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task
->get_old_system_contextid());
1485 protected function after_execute() {
1486 // Add outcomes related files, matching with "outcome" mappings
1487 $this->add_related_files('grade', 'outcome', 'outcome', $this->task
->get_old_system_contextid());
1492 * Execution step that, *conditionally* (if there isn't preloaded information
1493 * will load all the question categories and questions (header info only)
1494 * to backup_temp_ids. They will be stored with "question_category" and
1495 * "question" itemnames and with their original contextid and question category
1496 * id as paremitemids
1498 class restore_load_categories_and_questions
extends restore_execution_step
{
1500 protected function define_execution() {
1502 if ($this->task
->get_preloaded_information()) { // if info is already preloaded, nothing to do
1505 $file = $this->get_basepath() . '/questions.xml';
1506 restore_dbops
::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1511 * Execution step that, *conditionally* (if there isn't preloaded information)
1512 * will process all the needed categories and questions
1513 * in order to decide and perform any action with them (create / map / error)
1514 * Note: Any error will cause exception, as far as this is the same processing
1515 * than the one into restore prechecks (that should have stopped process earlier)
1517 class restore_process_categories_and_questions
extends restore_execution_step
{
1519 protected function define_execution() {
1521 if ($this->task
->get_preloaded_information()) { // if info is already preloaded, nothing to do
1524 restore_dbops
::process_categories_and_questions($this->get_restoreid(), $this->task
->get_courseid(), $this->task
->get_userid(), $this->task
->is_samesite());
1529 * Structure step that will read the section.xml creating/updating sections
1530 * as needed, rebuilding course cache and other friends
1532 class restore_section_structure_step
extends restore_structure_step
{
1533 /** @var array Cache: Array of id => course format */
1534 private static $courseformats = array();
1537 * Resets a static cache of course formats. Required for unit testing.
1539 public static function reset_caches() {
1540 self
::$courseformats = array();
1543 protected function define_structure() {
1548 $section = new restore_path_element('section', '/section');
1549 $paths[] = $section;
1550 if ($CFG->enableavailability
) {
1551 $paths[] = new restore_path_element('availability', '/section/availability');
1552 $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1554 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1556 // Apply for 'format' plugins optional paths at section level
1557 $this->add_plugin_structure('format', $section);
1559 // Apply for 'local' plugins optional paths at section level
1560 $this->add_plugin_structure('local', $section);
1565 public function process_section($data) {
1567 $data = (object)$data;
1568 $oldid = $data->id
; // We'll need this later
1570 $restorefiles = false;
1572 // Look for the section
1573 $section = new stdclass();
1574 $section->course
= $this->get_courseid();
1575 $section->section
= $data->number
;
1576 $section->timemodified
= $data->timemodified ??
0;
1577 // Section doesn't exist, create it with all the info from backup
1578 if (!$secrec = $DB->get_record('course_sections', ['course' => $this->get_courseid(), 'section' => $data->number
])) {
1579 $section->name
= $data->name
;
1580 $section->summary
= $data->summary
;
1581 $section->summaryformat
= $data->summaryformat
;
1582 $section->sequence
= '';
1583 $section->visible
= $data->visible
;
1584 if (empty($CFG->enableavailability
)) { // Process availability information only if enabled.
1585 $section->availability
= null;
1587 $section->availability
= isset($data->availabilityjson
) ?
$data->availabilityjson
: null;
1588 // Include legacy [<2.7] availability data if provided.
1589 if (is_null($section->availability
)) {
1590 $section->availability
= \core_availability\info
::convert_legacy_fields(
1594 $newitemid = $DB->insert_record('course_sections', $section);
1595 $section->id
= $newitemid;
1597 core\event\course_section_created
::create_from_section($section)->trigger();
1599 $restorefiles = true;
1601 // Section exists, update non-empty information
1603 $section->id
= $secrec->id
;
1604 if ((string)$secrec->name
=== '') {
1605 $section->name
= $data->name
;
1607 if (empty($secrec->summary
)) {
1608 $section->summary
= $data->summary
;
1609 $section->summaryformat
= $data->summaryformat
;
1610 $restorefiles = true;
1613 // Don't update availability (I didn't see a useful way to define
1614 // whether existing or new one should take precedence).
1616 $DB->update_record('course_sections', $section);
1617 $newitemid = $secrec->id
;
1619 // Trigger an event for course section update.
1620 $event = \core\event\course_section_updated
::create(
1622 'objectid' => $section->id
,
1623 'courseid' => $section->course
,
1624 'context' => context_course
::instance($section->course
),
1625 'other' => array('sectionnum' => $section->section
)
1631 // Annotate the section mapping, with restorefiles option if needed
1632 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1634 // set the new course_section id in the task
1635 $this->task
->set_sectionid($newitemid);
1637 // If there is the legacy showavailability data, store this for later use.
1638 // (This data is not present when restoring 'new' backups.)
1639 if (isset($data->showavailability
)) {
1640 // Cache the showavailability flag using the backup_ids data field.
1641 restore_dbops
::set_backup_ids_record($this->get_restoreid(),
1642 'section_showavailability', $newitemid, 0, null,
1643 (object)array('showavailability' => $data->showavailability
));
1646 // Commented out. We never modify course->numsections as far as that is used
1647 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1648 // Note: We keep the code here, to know about and because of the possibility of making this
1649 // optional based on some setting/attribute in the future
1650 // If needed, adjust course->numsections
1651 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1652 // if ($numsections < $section->section) {
1653 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1659 * Process the legacy availability table record. This table does not exist
1660 * in Moodle 2.7+ but we still support restore.
1662 * @param stdClass $data Record data
1664 public function process_availability($data) {
1665 $data = (object)$data;
1666 // Simply going to store the whole availability record now, we'll process
1667 // all them later in the final task (once all activities have been restored)
1668 // Let's call the low level one to be able to store the whole object.
1669 $data->coursesectionid
= $this->task
->get_sectionid();
1670 restore_dbops
::set_backup_ids_record($this->get_restoreid(),
1671 'section_availability', $data->id
, 0, null, $data);
1675 * Process the legacy availability fields table record. This table does not
1676 * exist in Moodle 2.7+ but we still support restore.
1678 * @param stdClass $data Record data
1680 public function process_availability_field($data) {
1682 $data = (object)$data;
1683 // Mark it is as passed by default
1685 $customfieldid = null;
1687 // If a customfield has been used in order to pass we must be able to match an existing
1688 // customfield by name (data->customfield) and type (data->customfieldtype)
1689 if (is_null($data->customfield
) xor is_null($data->customfieldtype
)) {
1690 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1691 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1693 } else if (!is_null($data->customfield
)) {
1694 $params = array('shortname' => $data->customfield
, 'datatype' => $data->customfieldtype
);
1695 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1696 $passed = ($customfieldid !== false);
1700 // Create the object to insert into the database
1701 $availfield = new stdClass();
1702 $availfield->coursesectionid
= $this->task
->get_sectionid();
1703 $availfield->userfield
= $data->userfield
;
1704 $availfield->customfieldid
= $customfieldid;
1705 $availfield->operator
= $data->operator
;
1706 $availfield->value
= $data->value
;
1708 // Get showavailability option.
1709 $showrec = restore_dbops
::get_backup_ids_record($this->get_restoreid(),
1710 'section_showavailability', $availfield->coursesectionid
);
1712 // Should not happen.
1713 throw new coding_exception('No matching showavailability record');
1715 $show = $showrec->info
->showavailability
;
1717 // The $availfield object is now in the format used in the old
1718 // system. Interpret this and convert to new system.
1719 $currentvalue = $DB->get_field('course_sections', 'availability',
1720 array('id' => $availfield->coursesectionid
), MUST_EXIST
);
1721 $newvalue = \core_availability\info
::add_legacy_availability_field_condition(
1722 $currentvalue, $availfield, $show);
1724 $section = new stdClass();
1725 $section->id
= $availfield->coursesectionid
;
1726 $section->availability
= $newvalue;
1727 $section->timemodified
= time();
1728 $DB->update_record('course_sections', $section);
1732 public function process_course_format_options($data) {
1734 $courseid = $this->get_courseid();
1735 if (!array_key_exists($courseid, self
::$courseformats)) {
1736 // It is safe to have a static cache of course formats because format can not be changed after this point.
1737 self
::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1739 $data = (array)$data;
1740 if (self
::$courseformats[$courseid] === $data['format']) {
1741 // Import section format options only if both courses (the one that was backed up
1742 // and the one we are restoring into) have same formats.
1744 'courseid' => $this->get_courseid(),
1745 'sectionid' => $this->task
->get_sectionid(),
1746 'format' => $data['format'],
1747 'name' => $data['name']
1749 if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1750 // Do not overwrite existing information.
1751 $newid = $record->id
;
1753 $params['value'] = $data['value'];
1754 $newid = $DB->insert_record('course_format_options', $params);
1756 $this->set_mapping('course_format_options', $data['id'], $newid);
1760 protected function after_execute() {
1761 // Add section related files, with 'course_section' itemid to match
1762 $this->add_related_files('course', 'section', 'course_section');
1767 * Structure step that will read the course.xml file, loading it and performing
1768 * various actions depending of the site/restore settings. Note that target
1769 * course always exist before arriving here so this step will be updating
1770 * the course record (never inserting)
1772 class restore_course_structure_step
extends restore_structure_step
{
1774 * @var bool this gets set to true by {@link process_course()} if we are
1775 * restoring an old coures that used the legacy 'module security' feature.
1776 * If so, we have to do more work in {@link after_execute()}.
1778 protected $legacyrestrictmodules = false;
1781 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1782 * array with array keys the module names ('forum', 'quiz', etc.). These are
1783 * the modules that are allowed according to the data in the backup file.
1784 * In {@link after_execute()} we then have to prevent adding of all the other
1785 * types of activity.
1787 protected $legacyallowedmodules = array();
1789 protected function define_structure() {
1791 $course = new restore_path_element('course', '/course');
1792 $category = new restore_path_element('category', '/course/category');
1793 $tag = new restore_path_element('tag', '/course/tags/tag');
1794 $customfield = new restore_path_element('customfield', '/course/customfields/customfield');
1795 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1797 // Apply for 'format' plugins optional paths at course level
1798 $this->add_plugin_structure('format', $course);
1800 // Apply for 'theme' plugins optional paths at course level
1801 $this->add_plugin_structure('theme', $course);
1803 // Apply for 'report' plugins optional paths at course level
1804 $this->add_plugin_structure('report', $course);
1806 // Apply for 'course report' plugins optional paths at course level
1807 $this->add_plugin_structure('coursereport', $course);
1809 // Apply for plagiarism plugins optional paths at course level
1810 $this->add_plugin_structure('plagiarism', $course);
1812 // Apply for local plugins optional paths at course level
1813 $this->add_plugin_structure('local', $course);
1815 // Apply for admin tool plugins optional paths at course level.
1816 $this->add_plugin_structure('tool', $course);
1818 return array($course, $category, $tag, $customfield, $allowed_module);
1822 * Processing functions go here
1824 * @global moodledatabase $DB
1825 * @param stdClass $data
1827 public function process_course($data) {
1829 $context = context
::instance_by_id($this->task
->get_contextid());
1830 $userid = $this->task
->get_userid();
1831 $target = $this->get_task()->get_target();
1832 $isnewcourse = $target == backup
::TARGET_NEW_COURSE
;
1834 // When restoring to a new course we can set all the things except for the ID number.
1835 $canchangeidnumber = $isnewcourse ||
has_capability('moodle/course:changeidnumber', $context, $userid);
1836 $canchangesummary = $isnewcourse ||
has_capability('moodle/course:changesummary', $context, $userid);
1837 $canforcelanguage = has_capability('moodle/course:setforcedlanguage', $context, $userid);
1839 $data = (object)$data;
1840 $data->id
= $this->get_courseid();
1842 // Calculate final course names, to avoid dupes.
1843 $fullname = $this->get_setting_value('course_fullname');
1844 $shortname = $this->get_setting_value('course_shortname');
1845 list($data->fullname
, $data->shortname
) = restore_dbops
::calculate_course_names($this->get_courseid(),
1846 $fullname === false ?
$data->fullname
: $fullname,
1847 $shortname === false ?
$data->shortname
: $shortname);
1848 // Do not modify the course names at all when merging and user selected to keep the names (or prohibited by cap).
1849 if (!$isnewcourse && $fullname === false) {
1850 unset($data->fullname
);
1852 if (!$isnewcourse && $shortname === false) {
1853 unset($data->shortname
);
1856 // Unset summary if user can't change it.
1857 if (!$canchangesummary) {
1858 unset($data->summary
);
1859 unset($data->summaryformat
);
1862 // Unset lang if user can't change it.
1863 if (!$canforcelanguage) {
1867 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1868 // another course on this site.
1869 if (!empty($data->idnumber
) && $canchangeidnumber && $this->task
->is_samesite()
1870 && !$DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
1871 // Do not reset idnumber.
1873 } else if (!$isnewcourse) {
1874 // Prevent override when restoring as merge.
1875 unset($data->idnumber
);
1878 $data->idnumber
= '';
1881 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1882 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1883 if (empty($data->hiddensections
)) {
1884 $data->hiddensections
= 0;
1887 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1888 // then we will need to process restricted modules after execution.
1889 $this->legacyrestrictmodules
= !empty($data->restrictmodules
);
1891 $data->startdate
= $this->apply_date_offset($data->startdate
);
1892 if (isset($data->enddate
)) {
1893 $data->enddate
= $this->apply_date_offset($data->enddate
);
1896 if ($data->defaultgroupingid
) {
1897 $data->defaultgroupingid
= $this->get_mappingid('grouping', $data->defaultgroupingid
);
1899 if (empty($CFG->enablecompletion
)) {
1900 $data->enablecompletion
= 0;
1901 $data->completionstartonenrol
= 0;
1902 $data->completionnotify
= 0;
1904 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1905 if (isset($data->lang
) && !array_key_exists($data->lang
, $languages)) {
1909 $themes = get_list_of_themes(); // Get themes for quick search later
1910 if (!array_key_exists($data->theme
, $themes) ||
empty($CFG->allowcoursethemes
)) {
1914 // Check if this is an old SCORM course format.
1915 if ($data->format
== 'scorm') {
1916 $data->format
= 'singleactivity';
1917 $data->activitytype
= 'scorm';
1920 // Course record ready, update it
1921 $DB->update_record('course', $data);
1923 course_get_format($data)->update_course_format_options($data);
1925 // Role name aliases
1926 restore_dbops
::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1929 public function process_category($data) {
1930 // Nothing to do with the category. UI sets it before restore starts
1933 public function process_tag($data) {
1936 $data = (object)$data;
1938 core_tag_tag
::add_item_tag('core', 'course', $this->get_courseid(),
1939 context_course
::instance($this->get_courseid()), $data->rawname
);
1943 * Process custom fields
1945 * @param array $data
1947 public function process_customfield($data) {
1948 $handler = core_course\customfield\course_handler
::create();
1949 $handler->restore_instance_data_from_backup($this->task
, $data);
1952 public function process_allowed_module($data) {
1953 $data = (object)$data;
1955 // Backwards compatiblity support for the data that used to be in the
1956 // course_allowed_modules table.
1957 if ($this->legacyrestrictmodules
) {
1958 $this->legacyallowedmodules
[$data->modulename
] = 1;
1962 protected function after_execute() {
1965 // Add course related files, without itemid to match
1966 $this->add_related_files('course', 'summary', null);
1967 $this->add_related_files('course', 'overviewfiles', null);
1969 // Deal with legacy allowed modules.
1970 if ($this->legacyrestrictmodules
) {
1971 $context = context_course
::instance($this->get_courseid());
1973 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1974 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1975 foreach ($managerroleids as $roleid) {
1976 unset($roleids[$roleid]);
1979 foreach (core_component
::get_plugin_list('mod') as $modname => $notused) {
1980 if (isset($this->legacyallowedmodules
[$modname])) {
1981 // Module is allowed, no worries.
1985 $capability = 'mod/' . $modname . ':addinstance';
1987 if (!get_capability_info($capability)) {
1988 $this->log("Capability '{$capability}' was not found!", backup
::LOG_WARNING
);
1992 foreach ($roleids as $roleid) {
1993 assign_capability($capability, CAP_PREVENT
, $roleid, $context);
2001 * Execution step that will migrate legacy files if present.
2003 class restore_course_legacy_files_step
extends restore_execution_step
{
2004 public function define_execution() {
2007 // Do a check for legacy files and skip if there are none.
2008 $sql = 'SELECT count(*)
2009 FROM {backup_files_temp}
2014 $params = array($this->get_restoreid(), $this->task
->get_old_contextid(), 'course', 'legacy');
2016 if ($DB->count_records_sql($sql, $params)) {
2017 $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
2018 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
2019 'legacy', $this->task
->get_old_contextid(), $this->task
->get_userid());
2025 * Structure step that will read the roles.xml file (at course/activity/block levels)
2026 * containing all the role_assignments and overrides for that context. If corresponding to
2027 * one mapped role, they will be applied to target context. Will observe the role_assignments
2028 * setting to decide if ras are restored.
2030 * Note: this needs to be executed after all users are enrolled.
2032 class restore_ras_and_caps_structure_step
extends restore_structure_step
{
2033 protected $plugins = null;
2035 protected function define_structure() {
2039 // Observe the role_assignments setting
2040 if ($this->get_setting_value('role_assignments')) {
2041 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
2043 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
2051 * This has to be called after enrolments processing.
2053 * @param mixed $data
2056 public function process_assignment($data) {
2059 $data = (object)$data;
2061 // Check roleid, userid are one of the mapped ones
2062 if (!$newroleid = $this->get_mappingid('role', $data->roleid
)) {
2065 if (!$newuserid = $this->get_mappingid('user', $data->userid
)) {
2068 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
2069 // Only assign roles to not deleted users
2072 if (!$contextid = $this->task
->get_contextid()) {
2076 if (empty($data->component
)) {
2077 // assign standard manual roles
2078 // TODO: role_assign() needs one userid param to be able to specify our restore userid
2079 role_assign($newroleid, $newuserid, $contextid);
2081 } else if ((strpos($data->component
, 'enrol_') === 0)) {
2082 // Deal with enrolment roles - ignore the component and just find out the instance via new id,
2083 // it is possible that enrolment was restored using different plugin type.
2084 if (!isset($this->plugins
)) {
2085 $this->plugins
= enrol_get_plugins(true);
2087 if ($enrolid = $this->get_mappingid('enrol', $data->itemid
)) {
2088 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2089 if (isset($this->plugins
[$instance->enrol
])) {
2090 $this->plugins
[$instance->enrol
]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
2096 $data->roleid
= $newroleid;
2097 $data->userid
= $newuserid;
2098 $data->contextid
= $contextid;
2099 $dir = core_component
::get_component_directory($data->component
);
2100 if ($dir and is_dir($dir)) {
2101 if (component_callback($data->component
, 'restore_role_assignment', array($this, $data), true)) {
2105 // Bad luck, plugin could not restore the data, let's add normal membership.
2106 role_assign($data->roleid
, $data->userid
, $data->contextid
);
2107 $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
2108 $this->log($message, backup
::LOG_WARNING
);
2112 public function process_override($data) {
2113 $data = (object)$data;
2115 // Check roleid is one of the mapped ones
2116 $newroleid = $this->get_mappingid('role', $data->roleid
);
2117 // If newroleid and context are valid assign it via API (it handles dupes and so on)
2118 if ($newroleid && $this->task
->get_contextid()) {
2119 if (!get_capability_info($data->capability
)) {
2120 $this->log("Capability '{$data->capability}' was not found!", backup
::LOG_WARNING
);
2122 // TODO: assign_capability() needs one userid param to be able to specify our restore userid.
2123 assign_capability($data->capability
, $data->permission
, $newroleid, $this->task
->get_contextid());
2130 * If no instances yet add default enrol methods the same way as when creating new course in UI.
2132 class restore_default_enrolments_step
extends restore_execution_step
{
2134 public function define_execution() {
2137 // No enrolments in front page.
2138 if ($this->get_courseid() == SITEID
) {
2142 $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST
);
2144 if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
2145 // Something already added instances, do not add default instances.
2146 $plugins = enrol_get_plugins(true);
2147 foreach ($plugins as $plugin) {
2148 $plugin->restore_sync_course($course);
2152 // Looks like a newly created course.
2153 enrol_course_updated(true, $course, null);
2159 * This structure steps restores the enrol plugins and their underlying
2160 * enrolments, performing all the mappings and/or movements required
2162 class restore_enrolments_structure_step
extends restore_structure_step
{
2163 protected $enrolsynced = false;
2164 protected $plugins = null;
2165 protected $originalstatus = array();
2168 * Conditionally decide if this step should be executed.
2170 * This function checks the following parameter:
2172 * 1. the course/enrolments.xml file exists
2174 * @return bool true is safe to execute, false otherwise
2176 protected function execute_condition() {
2178 if ($this->get_courseid() == SITEID
) {
2182 // Check it is included in the backup
2183 $fullpath = $this->task
->get_taskbasepath();
2184 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
2185 if (!file_exists($fullpath)) {
2186 // Not found, can't restore enrolments info
2193 protected function define_structure() {
2195 $userinfo = $this->get_setting_value('users');
2198 $paths[] = $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2200 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2202 // Attach local plugin stucture to enrol element.
2203 $this->add_plugin_structure('enrol', $enrol);
2209 * Create enrolment instances.
2211 * This has to be called after creation of roles
2212 * and before adding of role assignments.
2214 * @param mixed $data
2217 public function process_enrol($data) {
2220 $data = (object)$data;
2221 $oldid = $data->id
; // We'll need this later.
2224 $this->originalstatus
[$oldid] = $data->status
;
2226 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2227 $this->set_mapping('enrol', $oldid, 0);
2231 if (!isset($this->plugins
)) {
2232 $this->plugins
= enrol_get_plugins(true);
2235 if (!$this->enrolsynced
) {
2236 // Make sure that all plugin may create instances and enrolments automatically
2237 // before the first instance restore - this is suitable especially for plugins
2238 // that synchronise data automatically using course->idnumber or by course categories.
2239 foreach ($this->plugins
as $plugin) {
2240 $plugin->restore_sync_course($courserec);
2242 $this->enrolsynced
= true;
2245 // Map standard fields - plugin has to process custom fields manually.
2246 $data->roleid
= $this->get_mappingid('role', $data->roleid
);
2247 $data->courseid
= $courserec->id
;
2249 if (!$this->get_setting_value('users') && $this->get_setting_value('enrolments') == backup
::ENROL_WITHUSERS
) {
2250 $converttomanual = true;
2252 $converttomanual = ($this->get_setting_value('enrolments') == backup
::ENROL_NEVER
);
2255 if ($converttomanual) {
2256 // Restore enrolments as manual enrolments.
2257 unset($data->sortorder
); // Remove useless sortorder from <2.4 backups.
2258 if (!enrol_is_enabled('manual')) {
2259 $this->set_mapping('enrol', $oldid, 0);
2262 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid
, 'enrol'=>'manual'), 'id')) {
2263 $instance = reset($instances);
2264 $this->set_mapping('enrol', $oldid, $instance->id
);
2266 if ($data->enrol
=== 'manual') {
2267 $instanceid = $this->plugins
['manual']->add_instance($courserec, (array)$data);
2269 $instanceid = $this->plugins
['manual']->add_default_instance($courserec);
2271 $this->set_mapping('enrol', $oldid, $instanceid);
2275 if (!enrol_is_enabled($data->enrol
) or !isset($this->plugins
[$data->enrol
])) {
2276 $this->set_mapping('enrol', $oldid, 0);
2277 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, consider restoring without enrolment methods";
2278 $this->log($message, backup
::LOG_WARNING
);
2281 if ($task = $this->get_task() and $task->get_target() == backup
::TARGET_NEW_COURSE
) {
2282 // Let's keep the sortorder in old backups.
2284 // Prevent problems with colliding sortorders in old backups,
2285 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2286 unset($data->sortorder
);
2288 // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2289 $this->plugins
[$data->enrol
]->restore_instance($this, $data, $courserec, $oldid);
2294 * Create user enrolments.
2296 * This has to be called after creation of enrolment instances
2297 * and before adding of role assignments.
2299 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2301 * @param mixed $data
2304 public function process_enrolment($data) {
2307 if (!isset($this->plugins
)) {
2308 $this->plugins
= enrol_get_plugins(true);
2311 $data = (object)$data;
2313 // Process only if parent instance have been mapped.
2314 if ($enrolid = $this->get_new_parentid('enrol')) {
2315 $oldinstancestatus = ENROL_INSTANCE_ENABLED
;
2316 $oldenrolid = $this->get_old_parentid('enrol');
2317 if (isset($this->originalstatus
[$oldenrolid])) {
2318 $oldinstancestatus = $this->originalstatus
[$oldenrolid];
2320 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2321 // And only if user is a mapped one.
2322 if ($userid = $this->get_mappingid('user', $data->userid
)) {
2323 if (isset($this->plugins
[$instance->enrol
])) {
2324 $this->plugins
[$instance->enrol
]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2334 * Make sure the user restoring the course can actually access it.
2336 class restore_fix_restorer_access_step
extends restore_execution_step
{
2337 protected function define_execution() {
2340 if (!$userid = $this->task
->get_userid()) {
2344 if (empty($CFG->restorernewroleid
)) {
2345 // Bad luck, no fallback role for restorers specified
2349 $courseid = $this->get_courseid();
2350 $context = context_course
::instance($courseid);
2352 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2353 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2357 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2358 role_assign($CFG->restorernewroleid
, $userid, $context);
2360 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2361 // Extra role is enough, yay!
2365 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2366 // hopefully admin selected suitable $CFG->restorernewroleid ...
2367 if (!enrol_is_enabled('manual')) {
2370 if (!$enrol = enrol_get_plugin('manual')) {
2373 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2374 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST
);
2375 $fields = array('status'=>ENROL_INSTANCE_ENABLED
, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2376 $enrol->add_instance($course, $fields);
2379 enrol_try_internal_enrol($courseid, $userid);
2385 * This structure steps restores the filters and their configs
2387 class restore_filters_structure_step
extends restore_structure_step
{
2389 protected function define_structure() {
2393 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2394 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2399 public function process_active($data) {
2401 $data = (object)$data;
2403 if (strpos($data->filter
, 'filter/') === 0) {
2404 $data->filter
= substr($data->filter
, 7);
2406 } else if (strpos($data->filter
, '/') !== false) {
2407 // Unsupported old filter.
2411 if (!filter_is_enabled($data->filter
)) { // Not installed or not enabled, nothing to do
2414 filter_set_local_state($data->filter
, $this->task
->get_contextid(), $data->active
);
2417 public function process_config($data) {
2419 $data = (object)$data;
2421 if (strpos($data->filter
, 'filter/') === 0) {
2422 $data->filter
= substr($data->filter
, 7);
2424 } else if (strpos($data->filter
, '/') !== false) {
2425 // Unsupported old filter.
2429 if (!filter_is_enabled($data->filter
)) { // Not installed or not enabled, nothing to do
2432 filter_set_local_config($data->filter
, $this->task
->get_contextid(), $data->name
, $data->value
);
2438 * This structure steps restores the comments
2439 * Note: Cannot use the comments API because defaults to USER->id.
2440 * That should change allowing to pass $userid
2442 class restore_comments_structure_step
extends restore_structure_step
{
2444 protected function define_structure() {
2448 $paths[] = new restore_path_element('comment', '/comments/comment');
2453 public function process_comment($data) {
2456 $data = (object)$data;
2458 // First of all, if the comment has some itemid, ask to the task what to map
2460 if ($data->itemid
) {
2461 $mapping = $this->task
->get_comment_mapping_itemname($data->commentarea
);
2462 $data->itemid
= $this->get_mappingid($mapping, $data->itemid
);
2464 // Only restore the comment if has no mapping OR we have found the matching mapping
2465 if (!$mapping ||
$data->itemid
) {
2466 // Only if user mapping and context
2467 $data->userid
= $this->get_mappingid('user', $data->userid
);
2468 if ($data->userid
&& $this->task
->get_contextid()) {
2469 $data->contextid
= $this->task
->get_contextid();
2470 // Only if there is another comment with same context/user/timecreated
2471 $params = array('contextid' => $data->contextid
, 'userid' => $data->userid
, 'timecreated' => $data->timecreated
);
2472 if (!$DB->record_exists('comments', $params)) {
2473 $DB->insert_record('comments', $data);
2481 * This structure steps restores the badges and their configs
2483 class restore_badges_structure_step
extends restore_structure_step
{
2486 * Conditionally decide if this step should be executed.
2488 * This function checks the following parameters:
2490 * 1. Badges and course badges are enabled on the site.
2491 * 2. The course/badges.xml file exists.
2492 * 3. All modules are restorable.
2493 * 4. All modules are marked for restore.
2495 * @return bool True is safe to execute, false otherwise
2497 protected function execute_condition() {
2500 // First check is badges and course level badges are enabled on this site.
2501 if (empty($CFG->enablebadges
) ||
empty($CFG->badges_allowcoursebadges
)) {
2502 // Disabled, don't restore course badges.
2506 // Check if badges.xml is included in the backup.
2507 $fullpath = $this->task
->get_taskbasepath();
2508 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
2509 if (!file_exists($fullpath)) {
2510 // Not found, can't restore course badges.
2514 // Check we are able to restore all backed up modules.
2515 if ($this->task
->is_missing_modules()) {
2519 // Finally check all modules within the backup are being restored.
2520 if ($this->task
->is_excluding_activities()) {
2527 protected function define_structure() {
2529 $paths[] = new restore_path_element('badge', '/badges/badge');
2530 $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2531 $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2532 $paths[] = new restore_path_element('endorsement', '/badges/badge/endorsement');
2533 $paths[] = new restore_path_element('alignment', '/badges/badge/alignments/alignment');
2534 $paths[] = new restore_path_element('relatedbadge', '/badges/badge/relatedbadges/relatedbadge');
2535 $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2540 public function process_badge($data) {
2543 require_once($CFG->libdir
. '/badgeslib.php');
2545 $data = (object)$data;
2546 $data->usercreated
= $this->get_mappingid('user', $data->usercreated
);
2547 if (empty($data->usercreated
)) {
2548 $data->usercreated
= $this->task
->get_userid();
2550 $data->usermodified
= $this->get_mappingid('user', $data->usermodified
);
2551 if (empty($data->usermodified
)) {
2552 $data->usermodified
= $this->task
->get_userid();
2555 // We'll restore the badge image.
2556 $restorefiles = true;
2558 $courseid = $this->get_courseid();
2561 'name' => $data->name
,
2562 'description' => $data->description
,
2563 'timecreated' => $data->timecreated
,
2564 'timemodified' => $data->timemodified
,
2565 'usercreated' => $data->usercreated
,
2566 'usermodified' => $data->usermodified
,
2567 'issuername' => $data->issuername
,
2568 'issuerurl' => $data->issuerurl
,
2569 'issuercontact' => $data->issuercontact
,
2570 'expiredate' => $this->apply_date_offset($data->expiredate
),
2571 'expireperiod' => $data->expireperiod
,
2572 'type' => BADGE_TYPE_COURSE
,
2573 'courseid' => $courseid,
2574 'message' => $data->message
,
2575 'messagesubject' => $data->messagesubject
,
2576 'attachment' => $data->attachment
,
2577 'notification' => $data->notification
,
2578 'status' => BADGE_STATUS_INACTIVE
,
2579 'nextcron' => $data->nextcron
,
2580 'version' => $data->version
,
2581 'language' => $data->language
,
2582 'imageauthorname' => $data->imageauthorname
,
2583 'imageauthoremail' => $data->imageauthoremail
,
2584 'imageauthorurl' => $data->imageauthorurl
,
2585 'imagecaption' => $data->imagecaption
2588 $newid = $DB->insert_record('badge', $params);
2589 $this->set_mapping('badge', $data->id
, $newid, $restorefiles);
2593 * Create an endorsement for a badge.
2595 * @param mixed $data
2598 public function process_endorsement($data) {
2601 $data = (object)$data;
2604 'badgeid' => $this->get_new_parentid('badge'),
2605 'issuername' => $data->issuername
,
2606 'issuerurl' => $data->issuerurl
,
2607 'issueremail' => $data->issueremail
,
2608 'claimid' => $data->claimid
,
2609 'claimcomment' => $data->claimcomment
,
2610 'dateissued' => $this->apply_date_offset($data->dateissued
)
2612 $newid = $DB->insert_record('badge_endorsement', $params);
2613 $this->set_mapping('endorsement', $data->id
, $newid);
2617 * Link to related badges for a badge. This relies on post processing in after_execute().
2619 * @param mixed $data
2622 public function process_relatedbadge($data) {
2625 $data = (object)$data;
2626 $relatedbadgeid = $data->relatedbadgeid
;
2628 if ($relatedbadgeid) {
2629 // Only backup and restore related badges if they are contained in the backup file.
2631 'badgeid' => $this->get_new_parentid('badge'),
2632 'relatedbadgeid' => $relatedbadgeid
2634 $newid = $DB->insert_record('badge_related', $params);
2639 * Link to an alignment for a badge.
2641 * @param mixed $data
2644 public function process_alignment($data) {
2647 $data = (object)$data;
2649 'badgeid' => $this->get_new_parentid('badge'),
2650 'targetname' => $data->targetname
,
2651 'targeturl' => $data->targeturl
,
2652 'targetdescription' => $data->targetdescription
,
2653 'targetframework' => $data->targetframework
,
2654 'targetcode' => $data->targetcode
2656 $newid = $DB->insert_record('badge_alignment', $params);
2657 $this->set_mapping('alignment', $data->id
, $newid);
2660 public function process_criterion($data) {
2663 $data = (object)$data;
2666 'badgeid' => $this->get_new_parentid('badge'),
2667 'criteriatype' => $data->criteriatype
,
2668 'method' => $data->method
,
2669 'description' => isset($data->description
) ?
$data->description
: '',
2670 'descriptionformat' => isset($data->descriptionformat
) ?
$data->descriptionformat
: 0,
2673 $newid = $DB->insert_record('badge_criteria', $params);
2674 $this->set_mapping('criterion', $data->id
, $newid);
2677 public function process_parameter($data) {
2680 require_once($CFG->libdir
. '/badgeslib.php');
2682 $data = (object)$data;
2683 $criteriaid = $this->get_new_parentid('criterion');
2685 // Parameter array that will go to database.
2687 $params['critid'] = $criteriaid;
2689 $oldparam = explode('_', $data->name
);
2691 if ($data->criteriatype
== BADGE_CRITERIA_TYPE_ACTIVITY
) {
2692 $module = $this->get_mappingid('course_module', $oldparam[1]);
2693 $params['name'] = $oldparam[0] . '_' . $module;
2694 $params['value'] = $oldparam[0] == 'module' ?
$module : $data->value
;
2695 } else if ($data->criteriatype
== BADGE_CRITERIA_TYPE_COURSE
) {
2696 $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2697 $params['value'] = $oldparam[0] == 'course' ?
$this->get_courseid() : $data->value
;
2698 } else if ($data->criteriatype
== BADGE_CRITERIA_TYPE_MANUAL
) {
2699 $role = $this->get_mappingid('role', $data->value
);
2700 if (!empty($role)) {
2701 $params['name'] = 'role_' . $role;
2702 $params['value'] = $role;
2706 } else if ($data->criteriatype
== BADGE_CRITERIA_TYPE_COMPETENCY
) {
2707 $competencyid = $this->get_mappingid('competency', $data->value
);
2708 if (!empty($competencyid)) {
2709 $params['name'] = 'competency_' . $competencyid;
2710 $params['value'] = $competencyid;
2716 if (!$DB->record_exists('badge_criteria_param', $params)) {
2717 $DB->insert_record('badge_criteria_param', $params);
2721 public function process_manual_award($data) {
2724 $data = (object)$data;
2725 $role = $this->get_mappingid('role', $data->issuerrole
);
2727 if (!empty($role)) {
2729 'badgeid' => $this->get_new_parentid('badge'),
2730 'recipientid' => $this->get_mappingid('user', $data->recipientid
),
2731 'issuerid' => $this->get_mappingid('user', $data->issuerid
),
2732 'issuerrole' => $role,
2733 'datemet' => $this->apply_date_offset($data->datemet
)
2736 // Skip the manual award if recipient or issuer can not be mapped to.
2737 if (empty($award['recipientid']) ||
empty($award['issuerid'])) {
2741 $DB->insert_record('badge_manual_award', $award);
2745 protected function after_execute() {
2747 // Add related files.
2748 $this->add_related_files('badges', 'badgeimage', 'badge');
2750 $badgeid = $this->get_new_parentid('badge');
2751 // Remap any related badges.
2752 // We do this in the DB directly because this is backup/restore it is not valid to call into
2753 // the component API.
2754 $params = array('badgeid' => $badgeid);
2755 $query = "SELECT DISTINCT br.id, br.badgeid, br.relatedbadgeid
2756 FROM {badge_related} br
2757 WHERE (br.badgeid = :badgeid)";
2758 $relatedbadges = $DB->get_records_sql($query, $params);
2759 $newrelatedids = [];
2760 foreach ($relatedbadges as $relatedbadge) {
2761 $relatedid = $this->get_mappingid('badge', $relatedbadge->relatedbadgeid
);
2762 $params['relatedbadgeid'] = $relatedbadge->relatedbadgeid
;
2763 $DB->delete_records_select('badge_related', '(badgeid = :badgeid AND relatedbadgeid = :relatedbadgeid)', $params);
2765 $newrelatedids[] = $relatedid;
2768 if (!empty($newrelatedids)) {
2769 $relatedbadges = [];
2770 foreach ($newrelatedids as $relatedid) {
2771 $relatedbadge = new stdClass();
2772 $relatedbadge->badgeid
= $badgeid;
2773 $relatedbadge->relatedbadgeid
= $relatedid;
2774 $relatedbadges[] = $relatedbadge;
2776 $DB->insert_records('badge_related', $relatedbadges);
2782 * This structure steps restores the calendar events
2784 class restore_calendarevents_structure_step
extends restore_structure_step
{
2786 protected function define_structure() {
2790 $paths[] = new restore_path_element('calendarevents', '/events/event');
2795 public function process_calendarevents($data) {
2796 global $DB, $SITE, $USER;
2798 $data = (object)$data;
2800 $restorefiles = true; // We'll restore the files
2802 // If this is a new action event, it will automatically be populated by the adhoc task.
2803 // Nothing to do here.
2804 if (isset($data->type
) && $data->type
== CALENDAR_EVENT_TYPE_ACTION
) {
2808 // User overrides for activities are identified by having a courseid of zero with
2809 // both a modulename and instance value set.
2810 $isuseroverride = !$data->courseid
&& $data->modulename
&& $data->instance
;
2812 // If we don't want to include user data and this record is a user override event
2813 // for an activity then we should not create it. (Only activity events can be user override events - which must have this
2815 if ($isuseroverride && $this->task
->setting_exists('userinfo') && !$this->task
->get_setting_value('userinfo')) {
2819 // Find the userid and the groupid associated with the event.
2820 $data->userid
= $this->get_mappingid('user', $data->userid
);
2821 if ($data->userid
=== false) {
2822 // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2823 // Use the current user ID for these events.
2824 $data->userid
= $USER->id
;
2826 if (!empty($data->groupid
)) {
2827 $data->groupid
= $this->get_mappingid('group', $data->groupid
);
2828 if ($data->groupid
=== false) {
2832 // Handle events with empty eventtype //MDL-32827
2833 if(empty($data->eventtype
)) {
2834 if ($data->courseid
== $SITE->id
) { // Site event
2835 $data->eventtype
= "site";
2836 } else if ($data->courseid
!= 0 && $data->groupid
== 0 && ($data->modulename
== 'assignment' ||
$data->modulename
== 'assign')) {
2837 // Course assingment event
2838 $data->eventtype
= "due";
2839 } else if ($data->courseid
!= 0 && $data->groupid
== 0) { // Course event
2840 $data->eventtype
= "course";
2841 } else if ($data->groupid
) { // Group event
2842 $data->eventtype
= "group";
2843 } else if ($data->userid
) { // User event
2844 $data->eventtype
= "user";
2851 'name' => $data->name
,
2852 'description' => $data->description
,
2853 'format' => $data->format
,
2854 // User overrides in activities use a course id of zero. All other event types
2855 // must use the mapped course id.
2856 'courseid' => $data->courseid ?
$this->get_courseid() : 0,
2857 'groupid' => $data->groupid
,
2858 'userid' => $data->userid
,
2859 'repeatid' => $this->get_mappingid('event', $data->repeatid
),
2860 'modulename' => $data->modulename
,
2861 'type' => isset($data->type
) ?
$data->type
: 0,
2862 'eventtype' => $data->eventtype
,
2863 'timestart' => $this->apply_date_offset($data->timestart
),
2864 'timeduration' => $data->timeduration
,
2865 'timesort' => isset($data->timesort
) ?
$this->apply_date_offset($data->timesort
) : null,
2866 'visible' => $data->visible
,
2867 'uuid' => $data->uuid
,
2868 'sequence' => $data->sequence
,
2869 'timemodified' => $data->timemodified
,
2870 'priority' => isset($data->priority
) ?
$data->priority
: null,
2871 'location' => isset($data->location
) ?
$data->location
: null);
2872 if ($this->name
== 'activity_calendar') {
2873 $params['instance'] = $this->task
->get_activityid();
2875 $params['instance'] = 0;
2879 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2884 AND timeduration = ?
2885 AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2886 $arg = array ($params['name'], $params['courseid'], $params['modulename'], $params['instance'], $params['timestart'], $params['timeduration'], $params['description']);
2887 $result = $DB->record_exists_sql($sql, $arg);
2888 if (empty($result)) {
2889 $newitemid = $DB->insert_record('event', $params);
2890 $this->set_mapping('event', $oldid, $newitemid);
2891 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2893 // With repeating events, each event has the repeatid pointed at the first occurrence.
2894 // Since the repeatid will be empty when the first occurrence is restored,
2895 // Get the repeatid from the second occurrence of the repeating event and use that to update the first occurrence.
2896 // Then keep a list of repeatids so we only perform this update once.
2897 static $repeatids = array();
2898 if (!empty($params['repeatid']) && !in_array($params['repeatid'], $repeatids)) {
2899 // This entry is repeated so the repeatid field must be set.
2900 $DB->set_field('event', 'repeatid', $params['repeatid'], array('id' => $params['repeatid']));
2901 $repeatids[] = $params['repeatid'];
2905 protected function after_execute() {
2906 // Add related files
2907 $this->add_related_files('calendar', 'event_description', 'event_description');
2911 class restore_course_completion_structure_step
extends restore_structure_step
{
2914 * Conditionally decide if this step should be executed.
2916 * This function checks parameters that are not immediate settings to ensure
2917 * that the enviroment is suitable for the restore of course completion info.
2919 * This function checks the following four parameters:
2921 * 1. Course completion is enabled on the site
2922 * 2. The backup includes course completion information
2923 * 3. All modules are restorable
2924 * 4. All modules are marked for restore.
2925 * 5. No completion criteria already exist for the course.
2927 * @return bool True is safe to execute, false otherwise
2929 protected function execute_condition() {
2932 // First check course completion is enabled on this site
2933 if (empty($CFG->enablecompletion
)) {
2934 // Disabled, don't restore course completion
2938 // No course completion on the front page.
2939 if ($this->get_courseid() == SITEID
) {
2943 // Check it is included in the backup
2944 $fullpath = $this->task
->get_taskbasepath();
2945 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
2946 if (!file_exists($fullpath)) {
2947 // Not found, can't restore course completion
2951 // Check we are able to restore all backed up modules
2952 if ($this->task
->is_missing_modules()) {
2956 // Check all modules within the backup are being restored.
2957 if ($this->task
->is_excluding_activities()) {
2961 // Check that no completion criteria is already set for the course.
2962 if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
2970 * Define the course completion structure
2972 * @return array Array of restore_path_element
2974 protected function define_structure() {
2976 // To know if we are including user completion info
2977 $userinfo = $this->get_setting_value('userscompletion');
2980 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2981 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2984 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2985 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2993 * Process course completion criteria
2995 * @global moodle_database $DB
2996 * @param stdClass $data
2998 public function process_course_completion_criteria($data) {
3001 $data = (object)$data;
3002 $data->course
= $this->get_courseid();
3004 // Apply the date offset to the time end field
3005 $data->timeend
= $this->apply_date_offset($data->timeend
);
3007 // Map the role from the criteria
3008 if (isset($data->role
) && $data->role
!= '') {
3009 // Newer backups should include roleshortname, which makes this much easier.
3010 if (!empty($data->roleshortname
)) {
3011 $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname
));
3012 if (!$roleinstanceid) {
3014 'Could not match the role shortname in course_completion_criteria, so skipping',
3019 $data->role
= $roleinstanceid;
3021 $data->role
= $this->get_mappingid('role', $data->role
);
3024 // Check we have an id, otherwise it causes all sorts of bugs.
3027 'Could not match role in course_completion_criteria, so skipping',
3034 // If the completion criteria is for a module we need to map the module instance
3035 // to the new module id.
3036 if (!empty($data->moduleinstance
) && !empty($data->module
)) {
3037 $data->moduleinstance
= $this->get_mappingid('course_module', $data->moduleinstance
);
3038 if (empty($data->moduleinstance
)) {
3040 'Could not match the module instance in course_completion_criteria, so skipping',
3046 $data->module
= null;
3047 $data->moduleinstance
= null;
3050 // We backup the course shortname rather than the ID so that we can match back to the course
3051 if (!empty($data->courseinstanceshortname
)) {
3052 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname
));
3053 if (!$courseinstanceid) {
3055 'Could not match the course instance in course_completion_criteria, so skipping',
3061 $courseinstanceid = null;
3063 $data->courseinstance
= $courseinstanceid;
3066 'course' => $data->course
,
3067 'criteriatype' => $data->criteriatype
,
3068 'enrolperiod' => $data->enrolperiod
,
3069 'courseinstance' => $data->courseinstance
,
3070 'module' => $data->module
,
3071 'moduleinstance' => $data->moduleinstance
,
3072 'timeend' => $data->timeend
,
3073 'gradepass' => $data->gradepass
,
3074 'role' => $data->role
3076 $newid = $DB->insert_record('course_completion_criteria', $params);
3077 $this->set_mapping('course_completion_criteria', $data->id
, $newid);
3081 * Processes course compltion criteria complete records
3083 * @global moodle_database $DB
3084 * @param stdClass $data
3086 public function process_course_completion_crit_compl($data) {
3089 $data = (object)$data;
3091 // This may be empty if criteria could not be restored
3092 $data->criteriaid
= $this->get_mappingid('course_completion_criteria', $data->criteriaid
);
3094 $data->course
= $this->get_courseid();
3095 $data->userid
= $this->get_mappingid('user', $data->userid
);
3097 if (!empty($data->criteriaid
) && !empty($data->userid
)) {
3099 'userid' => $data->userid
,
3100 'course' => $data->course
,
3101 'criteriaid' => $data->criteriaid
,
3102 'timecompleted' => $data->timecompleted
3104 if (isset($data->gradefinal
)) {
3105 $params['gradefinal'] = $data->gradefinal
;
3107 if (isset($data->unenroled
)) {
3108 $params['unenroled'] = $data->unenroled
;
3110 $DB->insert_record('course_completion_crit_compl', $params);
3115 * Process course completions
3117 * @global moodle_database $DB
3118 * @param stdClass $data
3120 public function process_course_completions($data) {
3123 $data = (object)$data;
3125 $data->course
= $this->get_courseid();
3126 $data->userid
= $this->get_mappingid('user', $data->userid
);
3128 if (!empty($data->userid
)) {
3130 'userid' => $data->userid
,
3131 'course' => $data->course
,
3132 'timeenrolled' => $data->timeenrolled
,
3133 'timestarted' => $data->timestarted
,
3134 'timecompleted' => $data->timecompleted
,
3135 'reaggregate' => $data->reaggregate
3138 $existing = $DB->get_record('course_completions', array(
3139 'userid' => $data->userid
,
3140 'course' => $data->course
3143 // MDL-46651 - If cron writes out a new record before we get to it
3144 // then we should replace it with the Truth data from the backup.
3145 // This may be obsolete after MDL-48518 is resolved
3147 $params['id'] = $existing->id
;
3148 $DB->update_record('course_completions', $params);
3150 $DB->insert_record('course_completions', $params);
3156 * Process course completion aggregate methods
3158 * @global moodle_database $DB
3159 * @param stdClass $data
3161 public function process_course_completion_aggr_methd($data) {
3164 $data = (object)$data;
3166 $data->course
= $this->get_courseid();
3168 // Only create the course_completion_aggr_methd records if
3169 // the target course has not them defined. MDL-28180
3170 if (!$DB->record_exists('course_completion_aggr_methd', array(
3171 'course' => $data->course
,
3172 'criteriatype' => $data->criteriatype
))) {
3174 'course' => $data->course
,
3175 'criteriatype' => $data->criteriatype
,
3176 'method' => $data->method
,
3177 'value' => $data->value
,
3179 $DB->insert_record('course_completion_aggr_methd', $params);
3186 * This structure step restores course logs (cmid = 0), delegating
3187 * the hard work to the corresponding {@link restore_logs_processor} passing the
3188 * collection of {@link restore_log_rule} rules to be observed as they are defined
3189 * by the task. Note this is only executed based in the 'logs' setting.
3191 * NOTE: This is executed by final task, to have all the activities already restored
3193 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
3194 * records are. There are others like 'calendar' and 'upload' that will be handled
3197 * NOTE: All the missing actions (not able to be restored) are sent to logs for
3198 * debugging purposes
3200 class restore_course_logs_structure_step
extends restore_structure_step
{
3203 * Conditionally decide if this step should be executed.
3205 * This function checks the following parameter:
3207 * 1. the course/logs.xml file exists
3209 * @return bool true is safe to execute, false otherwise
3211 protected function execute_condition() {
3213 // Check it is included in the backup
3214 $fullpath = $this->task
->get_taskbasepath();
3215 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
3216 if (!file_exists($fullpath)) {
3217 // Not found, can't restore course logs
3224 protected function define_structure() {
3228 // Simple, one plain level of information contains them
3229 $paths[] = new restore_path_element('log', '/logs/log');
3234 protected function process_log($data) {
3237 $data = (object)($data);
3239 // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3241 $data->userid
= $this->get_mappingid('user', $data->userid
);
3242 $data->course
= $this->get_courseid();
3245 // For any reason user wasn't remapped ok, stop processing this
3246 if (empty($data->userid
)) {
3250 // Everything ready, let's delegate to the restore_logs_processor
3252 // Set some fixed values that will save tons of DB requests
3254 'course' => $this->get_courseid());
3255 // Get instance and process log record
3256 $data = restore_logs_processor
::get_instance($this->task
, $values)->process_log_record($data);
3258 // If we have data, insert it, else something went wrong in the restore_logs_processor
3260 if (empty($data->url
)) {
3263 if (empty($data->info
)) {
3266 // Store the data in the legacy log table if we are still using it.
3267 $manager = get_log_manager();
3268 if (method_exists($manager, 'legacy_add_to_log')) {
3269 $manager->legacy_add_to_log($data->course
, $data->module
, $data->action
, $data->url
,
3270 $data->info
, $data->cmid
, $data->userid
, $data->ip
, $data->time
);
3277 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
3278 * sharing its same structure but modifying the way records are handled
3280 class restore_activity_logs_structure_step
extends restore_course_logs_structure_step
{
3282 protected function process_log($data) {
3285 $data = (object)($data);
3287 // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3289 $data->userid
= $this->get_mappingid('user', $data->userid
);
3290 $data->course
= $this->get_courseid();
3291 $data->cmid
= $this->task
->get_moduleid();
3293 // For any reason user wasn't remapped ok, stop processing this
3294 if (empty($data->userid
)) {
3298 // Everything ready, let's delegate to the restore_logs_processor
3300 // Set some fixed values that will save tons of DB requests
3302 'course' => $this->get_courseid(),
3303 'course_module' => $this->task
->get_moduleid(),
3304 $this->task
->get_modulename() => $this->task
->get_activityid());
3305 // Get instance and process log record
3306 $data = restore_logs_processor
::get_instance($this->task
, $values)->process_log_record($data);
3308 // If we have data, insert it, else something went wrong in the restore_logs_processor
3310 if (empty($data->url
)) {
3313 if (empty($data->info
)) {
3316 // Store the data in the legacy log table if we are still using it.
3317 $manager = get_log_manager();
3318 if (method_exists($manager, 'legacy_add_to_log')) {
3319 $manager->legacy_add_to_log($data->course
, $data->module
, $data->action
, $data->url
,
3320 $data->info
, $data->cmid
, $data->userid
, $data->ip
, $data->time
);
3327 * Structure step in charge of restoring the logstores.xml file for the course logs.
3329 * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3330 * it, for logs belonging to the course level.
3332 class restore_course_logstores_structure_step
extends restore_structure_step
{
3335 * Conditionally decide if this step should be executed.
3337 * This function checks the following parameter:
3339 * 1. the logstores.xml file exists
3341 * @return bool true is safe to execute, false otherwise
3343 protected function execute_condition() {
3345 // Check it is included in the backup.
3346 $fullpath = $this->task
->get_taskbasepath();
3347 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
3348 if (!file_exists($fullpath)) {
3349 // Not found, can't restore logstores.xml information.
3357 * Return the elements to be processed on restore of logstores.
3359 * @return restore_path_element[] array of elements to be processed on restore.
3361 protected function define_structure() {
3365 $logstore = new restore_path_element('logstore', '/logstores/logstore');
3366 $paths[] = $logstore;
3368 // Add logstore subplugin support to the 'logstore' element.
3369 $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3371 return array($logstore);
3375 * Process the 'logstore' element,
3377 * Note: This is empty by definition in backup, because stores do not share any
3378 * data between them, so there is nothing to process here.
3380 * @param array $data element data
3382 protected function process_logstore($data) {
3388 * Structure step in charge of restoring the logstores.xml file for the activity logs.
3390 * Note: Activity structure is completely equivalent to the course one, so just extend it.
3392 class restore_activity_logstores_structure_step
extends restore_course_logstores_structure_step
{
3396 * Restore course competencies structure step.
3398 class restore_course_competencies_structure_step
extends restore_structure_step
{
3401 * Returns the structure.
3405 protected function define_structure() {
3406 $userinfo = $this->get_setting_value('users');
3408 new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3409 new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3412 $paths[] = new restore_path_element('user_competency_course',
3413 '/course_competencies/user_competencies/user_competency');
3419 * Process a course competency settings.
3421 * @param array $data The data.
3423 public function process_course_competency_settings($data) {
3425 $data = (object) $data;
3427 // We do not restore the course settings during merge.
3428 $target = $this->get_task()->get_target();
3429 if ($target == backup
::TARGET_CURRENT_ADDING ||
$target == backup
::TARGET_EXISTING_ADDING
) {
3433 $courseid = $this->task
->get_courseid();
3434 $exists = \core_competency\course_competency_settings
::record_exists_select('courseid = :courseid',
3435 array('courseid' => $courseid));
3437 // Strangely the course settings already exist, let's just leave them as is then.
3439 $this->log('Course competency settings not restored, existing settings have been found.', backup
::LOG_WARNING
);
3443 $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans
);
3444 $settings = new \core_competency\
course_competency_settings(0, $data);
3445 $settings->create();
3449 * Process a course competency.
3451 * @param array $data The data.
3453 public function process_course_competency($data) {
3454 $data = (object) $data;
3456 // Mapping the competency by ID numbers.
3457 $framework = \core_competency\competency_framework
::get_record(array('idnumber' => $data->frameworkidnumber
));
3461 $competency = \core_competency\competency
::get_record(array('idnumber' => $data->idnumber
,
3462 'competencyframeworkid' => $framework->get('id')));
3466 $this->set_mapping(\core_competency\competency
::TABLE
, $data->id
, $competency->get('id'));
3469 'competencyid' => $competency->get('id'),
3470 'courseid' => $this->task
->get_courseid()
3472 $query = 'competencyid = :competencyid AND courseid = :courseid';
3473 $existing = \core_competency\course_competency
::record_exists_select($query, $params);
3476 // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3477 $record = (object) $params;
3478 $record->ruleoutcome
= $data->ruleoutcome
;
3479 $coursecompetency = new \core_competency\
course_competency(0, $record);
3480 $coursecompetency->create();
3485 * Process the user competency course.
3487 * @param array $data The data.
3489 public function process_user_competency_course($data) {
3491 $data = (object) $data;
3493 $data->competencyid
= $this->get_mappingid(\core_competency\competency
::TABLE
, $data->competencyid
);
3494 if (!$data->competencyid
) {
3495 // This is strange, the competency does not belong to the course.
3497 } else if ($data->grade
=== null) {
3498 // We do not need to do anything when there is no grade.
3502 $data->userid
= $this->get_mappingid('user', $data->userid
);
3503 $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task
->get_courseid()), MUST_EXIST
);
3505 // The method add_evidence also sets the course rating.
3506 \core_competency\api
::add_evidence($data->userid
,
3507 $data->competencyid
,
3508 $this->task
->get_contextid(),
3509 \core_competency\evidence
::ACTION_OVERRIDE
,
3510 'evidence_courserestored',
3520 * Execute conditions.
3524 protected function execute_condition() {
3526 // Do not execute if competencies are not included.
3527 if (!$this->get_setting_value('competencies')) {
3531 // Do not execute if the competencies XML file is not found.
3532 $fullpath = $this->task
->get_taskbasepath();
3533 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
3534 if (!file_exists($fullpath)) {
3543 * Restore activity competencies structure step.
3545 class restore_activity_competencies_structure_step
extends restore_structure_step
{
3548 * Defines the structure.
3552 protected function define_structure() {
3554 new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3560 * Process a course module competency.
3562 * @param array $data The data.
3564 public function process_course_module_competency($data) {
3565 $data = (object) $data;
3567 // Mapping the competency by ID numbers.
3568 $framework = \core_competency\competency_framework
::get_record(array('idnumber' => $data->frameworkidnumber
));
3572 $competency = \core_competency\competency
::get_record(array('idnumber' => $data->idnumber
,
3573 'competencyframeworkid' => $framework->get('id')));
3579 'competencyid' => $competency->get('id'),
3580 'cmid' => $this->task
->get_moduleid()
3582 $query = 'competencyid = :competencyid AND cmid = :cmid';
3583 $existing = \core_competency\course_module_competency
::record_exists_select($query, $params);
3586 // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3587 $record = (object) $params;
3588 $record->ruleoutcome
= $data->ruleoutcome
;
3589 $coursemodulecompetency = new \core_competency\
course_module_competency(0, $record);
3590 $coursemodulecompetency->create();
3595 * Execute conditions.
3599 protected function execute_condition() {
3601 // Do not execute if competencies are not included.
3602 if (!$this->get_setting_value('competencies')) {
3606 // Do not execute if the competencies XML file is not found.
3607 $fullpath = $this->task
->get_taskbasepath();
3608 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
3609 if (!file_exists($fullpath)) {
3618 * Defines the restore step for advanced grading methods attached to the activity module
3620 class restore_activity_grading_structure_step
extends restore_structure_step
{
3623 * This step is executed only if the grading file is present
3625 protected function execute_condition() {
3627 if ($this->get_courseid() == SITEID
) {
3631 $fullpath = $this->task
->get_taskbasepath();
3632 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
3633 if (!file_exists($fullpath)) {
3642 * Declares paths in the grading.xml file we are interested in
3644 protected function define_structure() {
3647 $userinfo = $this->get_setting_value('userinfo');
3649 $area = new restore_path_element('grading_area', '/areas/area');
3651 // attach local plugin stucture to $area element
3652 $this->add_plugin_structure('local', $area);
3654 $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
3655 $paths[] = $definition;
3656 $this->add_plugin_structure('gradingform', $definition);
3657 // attach local plugin stucture to $definition element
3658 $this->add_plugin_structure('local', $definition);
3662 $instance = new restore_path_element('grading_instance',
3663 '/areas/area/definitions/definition/instances/instance');
3664 $paths[] = $instance;
3665 $this->add_plugin_structure('gradingform', $instance);
3666 // attach local plugin stucture to $intance element
3667 $this->add_plugin_structure('local', $instance);
3674 * Processes one grading area element
3676 * @param array $data element data
3678 protected function process_grading_area($data) {
3681 $task = $this->get_task();
3682 $data = (object)$data;
3684 $data->component
= 'mod_'.$task->get_modulename();
3685 $data->contextid
= $task->get_contextid();
3687 $newid = $DB->insert_record('grading_areas', $data);
3688 $this->set_mapping('grading_area', $oldid, $newid);
3692 * Processes one grading definition element
3694 * @param array $data element data
3696 protected function process_grading_definition($data) {
3699 $task = $this->get_task();
3700 $data = (object)$data;
3702 $data->areaid
= $this->get_new_parentid('grading_area');
3703 $data->copiedfromid
= null;
3704 $data->timecreated
= time();
3705 $data->usercreated
= $task->get_userid();
3706 $data->timemodified
= $data->timecreated
;
3707 $data->usermodified
= $data->usercreated
;
3709 $newid = $DB->insert_record('grading_definitions', $data);
3710 $this->set_mapping('grading_definition', $oldid, $newid, true);
3714 * Processes one grading form instance element
3716 * @param array $data element data
3718 protected function process_grading_instance($data) {
3721 $data = (object)$data;
3723 // new form definition id
3724 $newformid = $this->get_new_parentid('grading_definition');
3726 // get the name of the area we are restoring to
3727 $sql = "SELECT ga.areaname
3728 FROM {grading_definitions} gd
3729 JOIN {grading_areas} ga ON gd.areaid = ga.id
3731 $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST
);
3733 // get the mapped itemid - the activity module is expected to define the mappings
3734 // for each gradable area
3735 $newitemid = $this->get_mappingid(restore_gradingform_plugin
::itemid_mapping($areaname), $data->itemid
);
3738 $data->definitionid
= $newformid;
3739 $data->raterid
= $this->get_mappingid('user', $data->raterid
);
3740 $data->itemid
= $newitemid;
3742 $newid = $DB->insert_record('grading_instances', $data);
3743 $this->set_mapping('grading_instance', $oldid, $newid);
3747 * Final operations when the database records are inserted
3749 protected function after_execute() {
3750 // Add files embedded into the definition description
3751 $this->add_related_files('grading', 'description', 'grading_definition');
3757 * This structure step restores the grade items associated with one activity
3758 * All the grade items are made child of the "course" grade item but the original
3759 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3760 * the complete gradebook (categories and calculations), that information is
3763 class restore_activity_grades_structure_step
extends restore_structure_step
{
3766 * No grades in front page.
3769 protected function execute_condition() {
3770 return ($this->get_courseid() != SITEID
);
3773 protected function define_structure() {
3776 $userinfo = $this->get_setting_value('userinfo');
3778 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3779 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3781 $paths[] = new restore_path_element('grade_grade',
3782 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
3787 protected function process_grade_item($data) {
3790 $data = (object)($data);
3791 $oldid = $data->id
; // We'll need these later
3792 $oldparentid = $data->categoryid
;
3793 $courseid = $this->get_courseid();
3796 if (!empty($data->idnumber
)) {
3797 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
3798 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
3799 // so the best is to keep the ones already in the gradebook
3800 // Potential problem: duplicates if same items are restored more than once. :-(
3801 // This needs to be fixed in some way (outcomes & activities with multiple items)
3802 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
3803 // In any case, verify always for uniqueness
3804 $sql = "SELECT cm.id
3805 FROM {course_modules} cm
3806 WHERE cm.course = :courseid AND
3807 cm.idnumber = :idnumber AND
3810 'courseid' => $courseid,
3811 'idnumber' => $data->idnumber
,
3812 'cmid' => $this->task
->get_moduleid()
3814 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber
))) {
3815 $idnumber = $data->idnumber
;
3819 if (!empty($data->categoryid
)) {
3820 // If the grade category id of the grade item being restored belongs to this course
3821 // then it is a fair assumption that this is the correct grade category for the activity
3822 // and we should leave it in place, if not then unset it.
3823 // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
3824 $conditions = array('id' => $data->categoryid
, 'courseid' => $courseid);
3825 if (!$this->task
->is_samesite() ||
!$DB->record_exists('grade_categories', $conditions)) {
3826 unset($data->categoryid
);
3831 $data->courseid
= $this->get_courseid();
3832 $data->iteminstance
= $this->task
->get_activityid();
3833 $data->idnumber
= $idnumber;
3834 $data->scaleid
= $this->get_mappingid('scale', $data->scaleid
);
3835 $data->outcomeid
= $this->get_mappingid('outcome', $data->outcomeid
);
3837 $gradeitem = new grade_item($data, false);
3838 $gradeitem->insert('restore');
3840 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
3841 $gradeitem->sortorder
= $data->sortorder
;
3842 $gradeitem->update('restore');
3844 // Set mapping, saving the original category id into parentitemid
3845 // gradebook restore (final task) will need it to reorganise items
3846 $this->set_mapping('grade_item', $oldid, $gradeitem->id
, false, null, $oldparentid);
3849 protected function process_grade_grade($data) {
3852 require_once($CFG->libdir
. '/grade/constants.php');
3854 $data = (object)($data);
3855 $olduserid = $data->userid
;
3859 $data->itemid
= $this->get_new_parentid('grade_item');
3861 $data->userid
= $this->get_mappingid('user', $data->userid
, null);
3862 if (!empty($data->userid
)) {
3863 $data->usermodified
= $this->get_mappingid('user', $data->usermodified
, null);
3864 $data->rawscaleid
= $this->get_mappingid('scale', $data->rawscaleid
);
3866 $grade = new grade_grade($data, false);
3867 $grade->insert('restore');
3869 $this->set_mapping('grade_grades', $oldid, $grade->id
, true);
3871 $this->add_related_files(
3872 GRADE_FILE_COMPONENT
,
3873 GRADE_FEEDBACK_FILEAREA
,
3879 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
3884 * process activity grade_letters. Note that, while these are possible,
3885 * because grade_letters are contextid based, in practice, only course
3886 * context letters can be defined. So we keep here this method knowing
3887 * it won't be executed ever. gradebook restore will restore course letters.
3889 protected function process_grade_letter($data) {
3892 $data['contextid'] = $this->task
->get_contextid();
3893 $gradeletter = (object)$data;
3895 // Check if it exists before adding it
3897 if (!$DB->record_exists('grade_letters', $data)) {
3898 $newitemid = $DB->insert_record('grade_letters', $gradeletter);
3900 // no need to save any grade_letter mapping
3903 public function after_restore() {
3904 // Fix grade item's sortorder after restore, as it might have duplicates.
3905 $courseid = $this->get_task()->get_courseid();
3906 grade_item
::fix_duplicate_sortorder($courseid);
3911 * Step in charge of restoring the grade history of an activity.
3913 * This step is added to the task regardless of the setting 'grade_histories'.
3914 * The reason is to allow for a more flexible step in case the logic needs to be
3915 * split accross different settings to control the history of items and/or grades.
3917 class restore_activity_grade_history_structure_step
extends restore_structure_step
{
3920 * This step is executed only if the grade history file is present.
3922 protected function execute_condition() {
3924 if ($this->get_courseid() == SITEID
) {
3928 $fullpath = $this->task
->get_taskbasepath();
3929 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
3930 if (!file_exists($fullpath)) {
3936 protected function define_structure() {
3940 $userinfo = $this->get_setting_value('userinfo');
3941 $history = $this->get_setting_value('grade_histories');
3943 if ($userinfo && $history) {
3944 $paths[] = new restore_path_element('grade_grade',
3945 '/grade_history/grade_grades/grade_grade');
3951 protected function process_grade_grade($data) {
3954 require_once($CFG->libdir
. '/grade/constants.php');
3956 $data = (object) $data;
3957 $oldhistoryid = $data->id
;
3958 $olduserid = $data->userid
;
3961 $data->userid
= $this->get_mappingid('user', $data->userid
, null);
3962 if (!empty($data->userid
)) {
3963 // Do not apply the date offsets as this is history.
3964 $data->itemid
= $this->get_mappingid('grade_item', $data->itemid
);
3965 $data->oldid
= $this->get_mappingid('grade_grades', $data->oldid
);
3966 $data->usermodified
= $this->get_mappingid('user', $data->usermodified
, null);
3967 $data->rawscaleid
= $this->get_mappingid('scale', $data->rawscaleid
);
3969 $newhistoryid = $DB->insert_record('grade_grades_history', $data);
3971 $this->set_mapping('grade_grades_history', $oldhistoryid, $newhistoryid, true);
3973 $this->add_related_files(
3974 GRADE_FILE_COMPONENT
,
3975 GRADE_HISTORY_FEEDBACK_FILEAREA
,
3976 'grade_grades_history',
3981 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
3982 $this->log($message, backup
::LOG_DEBUG
);
3988 * This structure steps restores one instance + positions of one block
3989 * Note: Positions corresponding to one existing context are restored
3990 * here, but all the ones having unknown contexts are sent to backup_ids
3991 * for a later chance to be restored at the end (final task)
3993 class restore_block_instance_structure_step
extends restore_structure_step
{
3995 protected function define_structure() {
3999 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
4000 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
4005 public function process_block($data) {
4008 $data = (object)$data; // Handy
4009 $oldcontextid = $data->contextid
;
4011 $positions = isset($data->block_positions
['block_position']) ?
$data->block_positions
['block_position'] : array();
4013 // Look for the parent contextid
4014 if (!$data->parentcontextid
= $this->get_mappingid('context', $data->parentcontextid
)) {
4015 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid
);
4018 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
4019 // If there is already one block of that type in the parent context
4020 // and the block is not multiple, stop processing
4021 // Use blockslib loader / method executor
4022 if (!$bi = block_instance($data->blockname
)) {
4026 if (!$bi->instance_allow_multiple()) {
4027 // The block cannot be added twice, so we will check if the same block is already being
4028 // displayed on the same page. For this, rather than mocking a page and using the block_manager
4029 // we use a similar query to the one in block_manager::load_blocks(), this will give us
4030 // a very good idea of the blocks already displayed in the context.
4032 'blockname' => $data->blockname
4035 // Context matching test.
4036 $context = context
::instance_by_id($data->parentcontextid
);
4037 $contextsql = 'bi.parentcontextid = :contextid';
4038 $params['contextid'] = $context->id
;
4040 $parentcontextids = $context->get_parent_context_ids();
4041 if ($parentcontextids) {
4042 list($parentcontextsql, $parentcontextparams) =
4043 $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED
);
4044 $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
4045 $params = array_merge($params, $parentcontextparams);
4048 // Page type pattern test.
4049 $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern
);
4050 list($pagetypepatternsql, $pagetypepatternparams) =
4051 $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED
);
4052 $params = array_merge($params, $pagetypepatternparams);
4054 // Sub page pattern test.
4055 $subpagepatternsql = 'bi.subpagepattern IS NULL';
4056 if ($data->subpagepattern
!== null) {
4057 $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
4058 $params['subpagepattern'] = $data->subpagepattern
;
4061 $exists = $DB->record_exists_sql("SELECT bi.id
4062 FROM {block_instances} bi
4063 JOIN {block} b ON b.name = bi.blockname
4064 WHERE bi.blockname = :blockname
4066 AND bi.pagetypepattern $pagetypepatternsql
4067 AND $subpagepatternsql", $params);
4069 // There is at least one very similar block visible on the page where we
4070 // are trying to restore the block. In these circumstances the block API
4071 // would not allow the user to add another instance of the block, so we
4072 // apply the same rule here.
4077 // If there is already one block of that type in the parent context
4078 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
4081 'blockname' => $data->blockname
, 'parentcontextid' => $data->parentcontextid
,
4082 'showinsubcontexts' => $data->showinsubcontexts
, 'pagetypepattern' => $data->pagetypepattern
,
4083 'subpagepattern' => $data->subpagepattern
, 'defaultregion' => $data->defaultregion
);
4084 if ($birecs = $DB->get_records('block_instances', $params)) {
4085 foreach($birecs as $birec) {
4086 if ($birec->configdata
== $data->configdata
) {
4092 // Set task old contextid, blockid and blockname once we know them
4093 $this->task
->set_old_contextid($oldcontextid);
4094 $this->task
->set_old_blockid($oldid);
4095 $this->task
->set_blockname($data->blockname
);
4097 // Let's look for anything within configdata neededing processing
4098 // (nulls and uses of legacy file.php)
4099 if ($attrstotransform = $this->task
->get_configdata_encoded_attributes()) {
4100 $configdata = (array)unserialize(base64_decode($data->configdata
));
4101 foreach ($configdata as $attribute => $value) {
4102 if (in_array($attribute, $attrstotransform)) {
4103 $configdata[$attribute] = $this->contentprocessor
->process_cdata($value);
4106 $data->configdata
= base64_encode(serialize((object)$configdata));
4109 // Set timecreated, timemodified if not included (older backup).
4110 if (empty($data->timecreated
)) {
4111 $data->timecreated
= time();
4113 if (empty($data->timemodified
)) {
4114 $data->timemodified
= $data->timecreated
;
4117 // Create the block instance
4118 $newitemid = $DB->insert_record('block_instances', $data);
4119 // Save the mapping (with restorefiles support)
4120 $this->set_mapping('block_instance', $oldid, $newitemid, true);
4121 // Create the block context
4122 $newcontextid = context_block
::instance($newitemid)->id
;
4123 // Save the block contexts mapping and sent it to task
4124 $this->set_mapping('context', $oldcontextid, $newcontextid);
4125 $this->task
->set_contextid($newcontextid);
4126 $this->task
->set_blockid($newitemid);
4128 // Restore block fileareas if declared
4129 $component = 'block_' . $this->task
->get_blockname();
4130 foreach ($this->task
->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
4131 $this->add_related_files($component, $filearea, null);
4134 // Process block positions, creating them or accumulating for final step
4135 foreach($positions as $position) {
4136 $position = (object)$position;
4137 $position->blockinstanceid
= $newitemid; // The instance is always the restored one
4138 // If position is for one already mapped (known) contextid
4139 // process it now, creating the position
4140 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid
)) {
4141 $position->contextid
= $newpositionctxid;
4142 // Create the block position
4143 $DB->insert_record('block_positions', $position);
4145 // The position belongs to an unknown context, send it to backup_ids
4146 // to process them as part of the final steps of restore. We send the
4147 // whole $position object there, hence use the low level method.
4149 restore_dbops
::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id
, 0, null, $position);
4156 * Structure step to restore common course_module information
4158 * This step will process the module.xml file for one activity, in order to restore
4159 * the corresponding information to the course_modules table, skipping various bits
4160 * of information based on CFG settings (groupings, completion...) in order to fullfill
4161 * all the reqs to be able to create the context to be used by all the rest of steps
4162 * in the activity restore task
4164 class restore_module_structure_step
extends restore_structure_step
{
4166 protected function define_structure() {
4171 $module = new restore_path_element('module', '/module');
4173 if ($CFG->enableavailability
) {
4174 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
4175 $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
4178 $paths[] = new restore_path_element('tag', '/module/tags/tag');
4180 // Apply for 'format' plugins optional paths at module level
4181 $this->add_plugin_structure('format', $module);
4183 // Apply for 'report' plugins optional paths at module level.
4184 $this->add_plugin_structure('report', $module);
4186 // Apply for 'plagiarism' plugins optional paths at module level
4187 $this->add_plugin_structure('plagiarism', $module);
4189 // Apply for 'local' plugins optional paths at module level
4190 $this->add_plugin_structure('local', $module);
4192 // Apply for 'admin tool' plugins optional paths at module level.
4193 $this->add_plugin_structure('tool', $module);
4198 protected function process_module($data) {
4201 $data = (object)$data;
4203 $this->task
->set_old_moduleversion($data->version
);
4205 $data->course
= $this->task
->get_courseid();
4206 $data->module
= $DB->get_field('modules', 'id', array('name' => $data->modulename
));
4207 // Map section (first try by course_section mapping match. Useful in course and section restores)
4208 $data->section
= $this->get_mappingid('course_section', $data->sectionid
);
4209 if (!$data->section
) { // mapping failed, try to get section by sectionnumber matching
4211 'course' => $this->get_courseid(),
4212 'section' => $data->sectionnumber
);
4213 $data->section
= $DB->get_field('course_sections', 'id', $params);
4215 if (!$data->section
) { // sectionnumber failed, try to get first section in course
4217 'course' => $this->get_courseid());
4218 $data->section
= $DB->get_field('course_sections', 'MIN(id)', $params);
4220 if (!$data->section
) { // no sections in course, create section 0 and 1 and assign module to 1
4221 $sectionrec = array(
4222 'course' => $this->get_courseid(),
4224 'timemodified' => time());
4225 $DB->insert_record('course_sections', $sectionrec); // section 0
4226 $sectionrec = array(
4227 'course' => $this->get_courseid(),
4229 'timemodified' => time());
4230 $data->section
= $DB->insert_record('course_sections', $sectionrec); // section 1
4232 $data->groupingid
= $this->get_mappingid('grouping', $data->groupingid
); // grouping
4233 if (!grade_verify_idnumber($data->idnumber
, $this->get_courseid())) { // idnumber uniqueness
4234 $data->idnumber
= '';
4236 if (empty($CFG->enablecompletion
)) { // completion
4237 $data->completion
= 0;
4238 $data->completiongradeitemnumber
= null;
4239 $data->completionview
= 0;
4240 $data->completionexpected
= 0;
4242 $data->completionexpected
= $this->apply_date_offset($data->completionexpected
);
4244 if (empty($CFG->enableavailability
)) {
4245 $data->availability
= null;
4247 // Backups that did not include showdescription, set it to default 0
4248 // (this is not totally necessary as it has a db default, but just to
4250 if (!isset($data->showdescription
)) {
4251 $data->showdescription
= 0;
4253 $data->instance
= 0; // Set to 0 for now, going to create it soon (next step)
4255 if (empty($data->availability
)) {
4256 // If there are legacy availablility data fields (and no new format data),
4257 // convert the old fields.
4258 $data->availability
= \core_availability\info
::convert_legacy_fields(
4260 } else if (!empty($data->groupmembersonly
)) {
4261 // There is current availability data, but it still has groupmembersonly
4262 // as well (2.7 backups), convert just that part.
4263 require_once($CFG->dirroot
. '/lib/db/upgradelib.php');
4264 $data->availability
= upgrade_group_members_only($data->groupingid
, $data->availability
);
4267 // course_module record ready, insert it
4268 $newitemid = $DB->insert_record('course_modules', $data);
4270 $this->set_mapping('course_module', $oldid, $newitemid);
4271 // set the new course_module id in the task
4272 $this->task
->set_moduleid($newitemid);
4273 // we can now create the context safely
4274 $ctxid = context_module
::instance($newitemid)->id
;
4275 // set the new context id in the task
4276 $this->task
->set_contextid($ctxid);
4277 // update sequence field in course_section
4278 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section
))) {
4279 $sequence .= ',' . $newitemid;
4281 $sequence = $newitemid;
4284 $updatesection = new \
stdClass();
4285 $updatesection->id
= $data->section
;
4286 $updatesection->sequence
= $sequence;
4287 $updatesection->timemodified
= time();
4288 $DB->update_record('course_sections', $updatesection);
4290 // If there is the legacy showavailability data, store this for later use.
4291 // (This data is not present when restoring 'new' backups.)
4292 if (isset($data->showavailability
)) {
4293 // Cache the showavailability flag using the backup_ids data field.
4294 restore_dbops
::set_backup_ids_record($this->get_restoreid(),
4295 'module_showavailability', $newitemid, 0, null,
4296 (object)array('showavailability' => $data->showavailability
));
4301 * Fetch all the existing because tag_set() deletes them
4302 * so everything must be reinserted on each call.
4304 * @param stdClass $data Record data
4306 protected function process_tag($data) {
4309 $data = (object)$data;
4311 if (core_tag_tag
::is_enabled('core', 'course_modules')) {
4312 $modcontext = context
::instance_by_id($this->task
->get_contextid());
4313 $instanceid = $this->task
->get_moduleid();
4315 core_tag_tag
::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname
);
4320 * Process the legacy availability table record. This table does not exist
4321 * in Moodle 2.7+ but we still support restore.
4323 * @param stdClass $data Record data
4325 protected function process_availability($data) {
4326 $data = (object)$data;
4327 // Simply going to store the whole availability record now, we'll process
4328 // all them later in the final task (once all activities have been restored)
4329 // Let's call the low level one to be able to store the whole object
4330 $data->coursemoduleid
= $this->task
->get_moduleid(); // Let add the availability cmid
4331 restore_dbops
::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id
, 0, null, $data);
4335 * Process the legacy availability fields table record. This table does not
4336 * exist in Moodle 2.7+ but we still support restore.
4338 * @param stdClass $data Record data
4340 protected function process_availability_field($data) {
4342 $data = (object)$data;
4343 // Mark it is as passed by default
4345 $customfieldid = null;
4347 // If a customfield has been used in order to pass we must be able to match an existing
4348 // customfield by name (data->customfield) and type (data->customfieldtype)
4349 if (!empty($data->customfield
) xor !empty($data->customfieldtype
)) {
4350 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
4351 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
4353 } else if (!empty($data->customfield
)) {
4354 $params = array('shortname' => $data->customfield
, 'datatype' => $data->customfieldtype
);
4355 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
4356 $passed = ($customfieldid !== false);
4360 // Create the object to insert into the database
4361 $availfield = new stdClass();
4362 $availfield->coursemoduleid
= $this->task
->get_moduleid(); // Lets add the availability cmid
4363 $availfield->userfield
= $data->userfield
;
4364 $availfield->customfieldid
= $customfieldid;
4365 $availfield->operator
= $data->operator
;
4366 $availfield->value
= $data->value
;
4368 // Get showavailability option.
4369 $showrec = restore_dbops
::get_backup_ids_record($this->get_restoreid(),
4370 'module_showavailability', $availfield->coursemoduleid
);
4372 // Should not happen.
4373 throw new coding_exception('No matching showavailability record');
4375 $show = $showrec->info
->showavailability
;
4377 // The $availfieldobject is now in the format used in the old
4378 // system. Interpret this and convert to new system.
4379 $currentvalue = $DB->get_field('course_modules', 'availability',
4380 array('id' => $availfield->coursemoduleid
), MUST_EXIST
);
4381 $newvalue = \core_availability\info
::add_legacy_availability_field_condition(
4382 $currentvalue, $availfield, $show);
4383 $DB->set_field('course_modules', 'availability', $newvalue,
4384 array('id' => $availfield->coursemoduleid
));
4388 * This method will be executed after the rest of the restore has been processed.
4390 * Update old tag instance itemid(s).
4392 protected function after_restore() {
4395 $contextid = $this->task
->get_contextid();
4396 $instanceid = $this->task
->get_activityid();
4397 $olditemid = $this->task
->get_old_activityid();
4399 $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
4404 * Structure step that will process the user activity completion
4405 * information if all these conditions are met:
4406 * - Target site has completion enabled ($CFG->enablecompletion)
4407 * - Activity includes completion info (file_exists)
4409 class restore_userscompletion_structure_step
extends restore_structure_step
{
4411 * To conditionally decide if this step must be executed
4412 * Note the "settings" conditions are evaluated in the
4413 * corresponding task. Here we check for other conditions
4414 * not being restore settings (files, site settings...)
4416 protected function execute_condition() {
4419 // Completion disabled in this site, don't execute
4420 if (empty($CFG->enablecompletion
)) {
4424 // No completion on the front page.
4425 if ($this->get_courseid() == SITEID
) {
4429 // No user completion info found, don't execute
4430 $fullpath = $this->task
->get_taskbasepath();
4431 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
4432 if (!file_exists($fullpath)) {
4436 // Arrived here, execute the step
4440 protected function define_structure() {
4444 $paths[] = new restore_path_element('completion', '/completions/completion');
4449 protected function process_completion($data) {
4452 $data = (object)$data;
4454 $data->coursemoduleid
= $this->task
->get_moduleid();
4455 $data->userid
= $this->get_mappingid('user', $data->userid
);
4457 // Find the existing record
4458 $existing = $DB->get_record('course_modules_completion', array(
4459 'coursemoduleid' => $data->coursemoduleid
,
4460 'userid' => $data->userid
), 'id, timemodified');
4461 // Check we didn't already insert one for this cmid and userid
4462 // (there aren't supposed to be duplicates in that field, but
4463 // it was possible until MDL-28021 was fixed).
4465 // Update it to these new values, but only if the time is newer
4466 if ($existing->timemodified
< $data->timemodified
) {
4467 $data->id
= $existing->id
;
4468 $DB->update_record('course_modules_completion', $data);
4471 // Normal entry where it doesn't exist already
4472 $DB->insert_record('course_modules_completion', $data);
4478 * Abstract structure step, parent of all the activity structure steps. Used to support
4479 * the main <activity ...> tag and process it.
4481 abstract class restore_activity_structure_step
extends restore_structure_step
{
4484 * Adds support for the 'activity' path that is common to all the activities
4485 * and will be processed globally here
4487 protected function prepare_activity_structure($paths) {
4489 $paths[] = new restore_path_element('activity', '/activity');
4495 * Process the activity path, informing the task about various ids, needed later
4497 protected function process_activity($data) {
4498 $data = (object)$data;
4499 $this->task
->set_old_contextid($data->contextid
); // Save old contextid in task
4500 $this->set_mapping('context', $data->contextid
, $this->task
->get_contextid()); // Set the mapping
4501 $this->task
->set_old_activityid($data->id
); // Save old activityid in task
4505 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
4506 * and will adjust the new activity id (the instance) in various places
4508 protected function apply_activity_instance($newitemid) {
4511 $this->task
->set_activityid($newitemid); // Save activity id in task
4512 // Apply the id to course_sections->instanceid
4513 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task
->get_moduleid()));
4514 // Do the mapping for modulename, preparing it for files by oldcontext
4515 $modulename = $this->task
->get_modulename();
4516 $oldid = $this->task
->get_old_activityid();
4517 $this->set_mapping($modulename, $oldid, $newitemid, true);
4522 * Structure step in charge of creating/mapping all the qcats and qs
4523 * by parsing the questions.xml file and checking it against the
4524 * results calculated by {@link restore_process_categories_and_questions}
4525 * and stored in backup_ids_temp
4527 class restore_create_categories_and_questions
extends restore_structure_step
{
4529 /** @var array $cachecategory store a question category */
4530 protected $cachedcategory = null;
4532 protected function define_structure() {
4534 $category = new restore_path_element('question_category', '/question_categories/question_category');
4535 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
4536 $hint = new restore_path_element('question_hint',
4537 '/question_categories/question_category/questions/question/question_hints/question_hint');
4539 $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag');
4541 // Apply for 'qtype' plugins optional paths at question level
4542 $this->add_plugin_structure('qtype', $question);
4544 // Apply for 'local' plugins optional paths at question level
4545 $this->add_plugin_structure('local', $question);
4547 return array($category, $question, $hint, $tag);
4550 protected function process_question_category($data) {
4553 $data = (object)$data;
4556 // Check we have one mapping for this category
4557 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
4558 return self
::SKIP_ALL_CHILDREN
; // No mapping = this category doesn't need to be created/mapped
4561 // Check we have to create the category (newitemid = 0)
4562 if ($mapping->newitemid
) {
4563 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4564 // children elements of the 'question_category' one.
4565 $this->set_mapping('question_category', $oldid, $mapping->newitemid
);
4566 return; // newitemid != 0, this category is going to be mapped. Nothing to do
4569 // Arrived here, newitemid = 0, we need to create the category
4570 // we'll do it at parentitemid context, but for CONTEXT_MODULE
4571 // categories, that will be created at CONTEXT_COURSE and moved
4572 // to module context later when the activity is created
4573 if ($mapping->info
->contextlevel
== CONTEXT_MODULE
) {
4574 $mapping->parentitemid
= $this->get_mappingid('context', $this->task
->get_old_contextid());
4576 $data->contextid
= $mapping->parentitemid
;
4578 // Before 3.5, question categories could be created at top level.
4579 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
4580 $backuprelease = floatval($this->get_task()->get_info()->backup_release
);
4581 preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release
, $matches);
4582 $backupbuild = (int)$matches[1];
4584 if ($backuprelease < 3.5 ||
$backupbuild < 20180205) {
4587 if (empty($mapping->info
->parent
) && $before35) {
4588 $top = question_get_top_category($data->contextid
, true);
4589 $data->parent
= $top->id
;
4592 if (empty($data->parent
)) {
4593 if (!$top = question_get_top_category($data->contextid
)) {
4594 $top = question_get_top_category($data->contextid
, true);
4595 $this->set_mapping('question_category_created', $oldid, $top->id
, false, null, $data->contextid
);
4597 $this->set_mapping('question_category', $oldid, $top->id
);
4600 // Before 3.1, the 'stamp' field could be erroneously duplicated.
4601 // From 3.1 onwards, there's a unique index of (contextid, stamp).
4602 // If we encounter a duplicate in an old restore file, just generate a new stamp.
4603 // This is the same as what happens during an upgrade to 3.1+ anyway.
4604 if ($DB->record_exists('question_categories', ['stamp' => $data->stamp
, 'contextid' => $data->contextid
])) {
4605 $data->stamp
= make_unique_id_code();
4608 // The idnumber if it exists also needs to be unique within a context or reset it to null.
4609 if (!empty($data->idnumber
) && $DB->record_exists('question_categories',
4610 ['idnumber' => $data->idnumber
, 'contextid' => $data->contextid
])) {
4611 unset($data->idnumber
);
4614 // Let's create the question_category and save mapping.
4615 $newitemid = $DB->insert_record('question_categories', $data);
4616 $this->set_mapping('question_category', $oldid, $newitemid);
4617 // Also annotate them as question_category_created, we need
4618 // that later when remapping parents.
4619 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid
);
4623 protected function process_question($data) {
4626 $data = (object)$data;
4629 // Check we have one mapping for this question
4630 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
4631 return; // No mapping = this question doesn't need to be created/mapped
4634 // Get the mapped category (cannot use get_new_parentid() because not
4635 // all the categories have been created, so it is not always available
4636 // Instead we get the mapping for the question->parentitemid because
4637 // we have loaded qcatids there for all parsed questions
4638 $data->category
= $this->get_mappingid('question_category', $questionmapping->parentitemid
);
4640 // In the past, there were some very sloppy values of penalty. Fix them.
4641 if ($data->penalty
>= 0.33 && $data->penalty
<= 0.34) {
4642 $data->penalty
= 0.3333333;
4644 if ($data->penalty
>= 0.66 && $data->penalty
<= 0.67) {
4645 $data->penalty
= 0.6666667;
4647 if ($data->penalty
>= 1) {
4651 $userid = $this->get_mappingid('user', $data->createdby
);
4652 $data->createdby
= $userid ?
$userid : $this->task
->get_userid();
4654 $userid = $this->get_mappingid('user', $data->modifiedby
);
4655 $data->modifiedby
= $userid ?
$userid : $this->task
->get_userid();
4657 // With newitemid = 0, let's create the question
4658 if (!$questionmapping->newitemid
) {
4660 // The idnumber if it exists also needs to be unique within a category or reset it to null.
4661 if (!empty($data->idnumber
) && $DB->record_exists('question',
4662 ['idnumber' => $data->idnumber
, 'category' => $data->category
])) {
4663 unset($data->idnumber
);
4666 if ($data->qtype
=== 'random') {
4667 // Ensure that this newly created question is considered by
4668 // \qtype_random\task\remove_unused_questions.
4672 $newitemid = $DB->insert_record('question', $data);
4673 $this->set_mapping('question', $oldid, $newitemid);
4674 // Also annotate them as question_created, we need
4675 // that later when remapping parents (keeping the old categoryid as parentid)
4676 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid
);
4678 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4679 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
4680 $this->set_mapping('question', $oldid, $questionmapping->newitemid
);
4683 // Note, we don't restore any question files yet
4684 // as far as the CONTEXT_MODULE categories still
4685 // haven't their contexts to be restored to
4686 // The {@link restore_create_question_files}, executed in the final step
4687 // step will be in charge of restoring all the question files
4690 protected function process_question_hint($data) {
4693 $data = (object)$data;
4696 // Detect if the question is created or mapped
4697 $oldquestionid = $this->get_old_parentid('question');
4698 $newquestionid = $this->get_new_parentid('question');
4699 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ?
true : false;
4701 // If the question has been created by restore, we need to create its question_answers too
4702 if ($questioncreated) {
4703 // Adjust some columns
4704 $data->questionid
= $newquestionid;
4706 $newitemid = $DB->insert_record('question_hints', $data);
4708 // The question existed, we need to map the existing question_hints
4710 // Look in question_hints by hint text matching
4712 FROM {question_hints}
4713 WHERE questionid = ?
4714 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
4715 $params = array($newquestionid, $data->hint
);
4716 $newitemid = $DB->get_field_sql($sql, $params);
4718 // Not able to find the hint, let's try cleaning the hint text
4719 // of all the question's hints in DB as slower fallback. MDL-33863.
4721 $potentialhints = $DB->get_records('question_hints',
4722 array('questionid' => $newquestionid), '', 'id, hint');
4723 foreach ($potentialhints as $potentialhint) {
4724 // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
4725 $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint
); // Clean CTRL chars.
4726 $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
4727 if ($cleanhint === $data->hint
) {
4728 $newitemid = $data->id
;
4733 // If we haven't found the newitemid, something has gone really wrong, question in DB
4734 // is missing hints, exception
4736 $info = new stdClass();
4737 $info->filequestionid
= $oldquestionid;
4738 $info->dbquestionid
= $newquestionid;
4739 $info->hint
= $data->hint
;
4740 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
4743 // Create mapping (I'm not sure if this is really needed?)
4744 $this->set_mapping('question_hint', $oldid, $newitemid);
4747 protected function process_tag($data) {
4750 $data = (object)$data;
4751 $newquestion = $this->get_new_parentid('question');
4752 $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
4753 if (!$questioncreated) {
4754 // This question already exists in the question bank. Nothing for us to do.
4758 if (core_tag_tag
::is_enabled('core_question', 'question')) {
4759 $tagname = $data->rawname
;
4760 if (!empty($data->contextid
) && $newcontextid = $this->get_mappingid('context', $data->contextid
)) {
4761 $tagcontextid = $newcontextid;
4763 // Get the category, so we can then later get the context.
4764 $categoryid = $this->get_new_parentid('question_category');
4765 if (empty($this->cachedcategory
) ||
$this->cachedcategory
->id
!= $categoryid) {
4766 $this->cachedcategory
= $DB->get_record('question_categories', array('id' => $categoryid));
4768 $tagcontextid = $this->cachedcategory
->contextid
;
4770 // Add the tag to the question.
4771 core_tag_tag
::add_item_tag('core_question', 'question', $newquestion,
4772 context
::instance_by_id($tagcontextid),
4777 protected function after_execute() {
4780 // First of all, recode all the created question_categories->parent fields
4781 $qcats = $DB->get_records('backup_ids_temp', array(
4782 'backupid' => $this->get_restoreid(),
4783 'itemname' => 'question_category_created'));
4784 foreach ($qcats as $qcat) {
4785 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid
));
4786 // Get new parent (mapped or created, so we look in quesiton_category mappings)
4787 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
4788 'backupid' => $this->get_restoreid(),
4789 'itemname' => 'question_category',
4790 'itemid' => $dbcat->parent
))) {
4791 // contextids must match always, as far as we always include complete qbanks, just check it
4792 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
4793 if ($dbcat->contextid
== $newparentctxid) {
4794 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id
));
4796 $newparent = 0; // No ctx match for both cats, no parent relationship
4799 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
4800 if (!$newparent && $dbcat->parent
) {
4801 $topcat = question_get_top_category($dbcat->contextid
, true);
4802 if ($dbcat->parent
!= $topcat->id
) {
4803 $DB->set_field('question_categories', 'parent', $topcat->id
, array('id' => $dbcat->id
));
4808 // Now, recode all the created question->parent fields
4809 $qs = $DB->get_records('backup_ids_temp', array(
4810 'backupid' => $this->get_restoreid(),
4811 'itemname' => 'question_created'));
4812 foreach ($qs as $q) {
4813 $dbq = $DB->get_record('question', array('id' => $q->newitemid
));
4814 // Get new parent (mapped or created, so we look in question mappings)
4815 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
4816 'backupid' => $this->get_restoreid(),
4817 'itemname' => 'question',
4818 'itemid' => $dbq->parent
))) {
4819 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id
));
4823 // Note, we don't restore any question files yet
4824 // as far as the CONTEXT_MODULE categories still
4825 // haven't their contexts to be restored to
4826 // The {@link restore_create_question_files}, executed in the final step
4827 // step will be in charge of restoring all the question files
4832 * Execution step that will move all the CONTEXT_MODULE question categories
4833 * created at early stages of restore in course context (because modules weren't
4834 * created yet) to their target module (matching by old-new-contextid mapping)
4836 class restore_move_module_questions_categories
extends restore_execution_step
{
4838 protected function define_execution() {
4841 $backuprelease = floatval($this->task
->get_info()->backup_release
);
4842 preg_match('/(\d{8})/', $this->task
->get_info()->moodle_release
, $matches);
4843 $backupbuild = (int)$matches[1];
4845 if ($backuprelease >= 3.5 && $backupbuild > 20180205) {
4849 $contexts = restore_dbops
::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE
);
4850 foreach ($contexts as $contextid => $contextlevel) {
4851 // Only if context mapping exists (i.e. the module has been restored)
4852 if ($newcontext = restore_dbops
::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
4853 // Update all the qcats having their parentitemid set to the original contextid
4854 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid, info
4855 FROM {backup_ids_temp}
4857 AND itemname = 'question_category'
4858 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
4859 $top = question_get_top_category($newcontext->newitemid
, true);
4861 foreach ($modulecats as $modulecat) {
4862 // Before 3.5, question categories could be created at top level.
4863 // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
4864 $info = backup_controller_dbops
::decode_backup_temp_info($modulecat->info
);
4865 if ($after35 && empty($info->parent
)) {
4866 $oldtopid = $modulecat->newitemid
;
4867 $modulecat->newitemid
= $top->id
;
4869 $cat = new stdClass();
4870 $cat->id
= $modulecat->newitemid
;
4871 $cat->contextid
= $newcontext->newitemid
;
4872 if (empty($info->parent
)) {
4873 $cat->parent
= $top->id
;
4875 $DB->update_record('question_categories', $cat);
4878 // And set new contextid (and maybe update newitemid) also in question_category mapping (will be
4879 // used by {@link restore_create_question_files} later.
4880 restore_dbops
::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid
,
4881 $modulecat->newitemid
, $newcontext->newitemid
);
4884 // Now set the parent id for the question categories that were in the top category in the course context
4885 // and have been moved now.
4887 $DB->set_field('question_categories', 'parent', $top->id
,
4888 array('contextid' => $newcontext->newitemid
, 'parent' => $oldtopid));
4896 * Execution step that will create all the question/answers/qtype-specific files for the restored
4897 * questions. It must be executed after {@link restore_move_module_questions_categories}
4898 * because only then each question is in its final category and only then the
4899 * contexts can be determined.
4901 class restore_create_question_files
extends restore_execution_step
{
4903 /** @var array Question-type specific component items cache. */
4904 private $qtypecomponentscache = array();
4907 * Preform the restore_create_question_files step.
4909 protected function define_execution() {
4912 // Track progress, as this task can take a long time.
4913 $progress = $this->task
->get_progress();
4914 $progress->start_progress($this->get_name(), \core\progress\base
::INDETERMINATE
);
4916 // Parentitemids of question_createds in backup_ids_temp are the category it is in.
4917 // MUST use a recordset, as there is no unique key in the first (or any) column.
4918 $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
4919 FROM {backup_ids_temp} bi
4920 JOIN {question} q ON q.id = bi.newitemid
4921 WHERE bi.backupid = ?
4922 AND bi.itemname = 'question_created'
4923 ORDER BY categoryid ASC", array($this->get_restoreid()));
4926 foreach ($catqtypes as $categoryid => $row) {
4927 $qtype = $row->qtype
;
4929 // Check if we are in a new category.
4930 if ($currentcatid !== $categoryid) {
4931 // Report progress for each category.
4932 $progress->progress();
4934 if (!$qcatmapping = restore_dbops
::get_backup_ids_record($this->get_restoreid(),
4935 'question_category', $categoryid)) {
4936 // Something went really wrong, cannot find the question_category for the question_created records.
4937 debugging('Error fetching target context for question', DEBUG_DEVELOPER
);
4941 // Calculate source and target contexts.
4942 $oldctxid = $qcatmapping->info
->contextid
;
4943 $newctxid = $qcatmapping->parentitemid
;
4945 $this->send_common_files($oldctxid, $newctxid, $progress);
4946 $currentcatid = $categoryid;
4949 $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
4951 $catqtypes->close();
4952 $progress->end_progress();
4956 * Send the common question files to a new context.
4958 * @param int $oldctxid Old context id.
4959 * @param int $newctxid New context id.
4960 * @param \core\progress $progress Progress object to use.
4962 private function send_common_files($oldctxid, $newctxid, $progress) {
4963 // Add common question files (question and question_answer ones).
4964 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
4965 $oldctxid, $this->task
->get_userid(), 'question_created', null, $newctxid, true, $progress);
4966 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
4967 $oldctxid, $this->task
->get_userid(), 'question_created', null, $newctxid, true, $progress);
4968 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
4969 $oldctxid, $this->task
->get_userid(), 'question_answer', null, $newctxid, true, $progress);
4970 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
4971 $oldctxid, $this->task
->get_userid(), 'question_answer', null, $newctxid, true, $progress);
4972 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
4973 $oldctxid, $this->task
->get_userid(), 'question_hint', null, $newctxid, true, $progress);
4974 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
4975 $oldctxid, $this->task
->get_userid(), 'question_created', null, $newctxid, true, $progress);
4976 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
4977 $oldctxid, $this->task
->get_userid(), 'question_created', null, $newctxid, true, $progress);
4978 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
4979 $oldctxid, $this->task
->get_userid(), 'question_created', null, $newctxid, true, $progress);
4983 * Send the question type specific files to a new context.
4985 * @param text $qtype The qtype name to send.
4986 * @param int $oldctxid Old context id.
4987 * @param int $newctxid New context id.
4988 * @param \core\progress $progress Progress object to use.
4990 private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
4991 if (!isset($this->qtypecomponentscache
[$qtype])) {
4992 $this->qtypecomponentscache
[$qtype] = backup_qtype_plugin
::get_components_and_fileareas($qtype);
4994 $components = $this->qtypecomponentscache
[$qtype];
4995 foreach ($components as $component => $fileareas) {
4996 foreach ($fileareas as $filearea => $mapping) {
4997 restore_dbops
::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
4998 $oldctxid, $this->task
->get_userid(), $mapping, null, $newctxid, true, $progress);
5005 * Try to restore aliases and references to external files.
5007 * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
5008 * We expect that all regular (non-alias) files have already been restored. Make sure
5009 * there is no restore step executed after this one that would call send_files_to_pool() again.
5011 * You may notice we have hardcoded support for Server files, Legacy course files
5012 * and user Private files here at the moment. This could be eventually replaced with a set of
5013 * callbacks in the future if needed.
5015 * @copyright 2012 David Mudrak <david@moodle.com>
5016 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5018 class restore_process_file_aliases_queue
extends restore_execution_step
{
5020 /** @var array internal cache for {@link choose_repository()} */
5021 private $cachereposbyid = array();
5023 /** @var array internal cache for {@link choose_repository()} */
5024 private $cachereposbytype = array();
5027 * What to do when this step is executed.
5029 protected function define_execution() {
5032 $this->log('processing file aliases queue', backup
::LOG_DEBUG
);
5034 $fs = get_file_storage();
5037 $rs = $DB->get_recordset('backup_ids_temp',
5038 array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'),
5041 // Iterate over aliases in the queue.
5042 foreach ($rs as $record) {
5043 $info = backup_controller_dbops
::decode_backup_temp_info($record->info
);
5045 // Try to pick a repository instance that should serve the alias.
5046 $repository = $this->choose_repository($info);
5048 if (is_null($repository)) {
5049 $this->notify_failure($info, 'unable to find a matching repository instance');
5053 if ($info->oldfile
->repositorytype
=== 'local' or $info->oldfile
->repositorytype
=== 'coursefiles') {
5054 // Aliases to Server files and Legacy course files may refer to a file
5055 // contained in the backup file or to some existing file (if we are on the
5058 $reference = file_storage
::unpack_reference($info->oldfile
->reference
);
5059 } catch (Exception
$e) {
5060 $this->notify_failure($info, 'invalid reference field format');
5064 // Let's see if the referred source file was also included in the backup.
5065 $candidates = $DB->get_recordset('backup_files_temp', array(
5066 'backupid' => $this->get_restoreid(),
5067 'contextid' => $reference['contextid'],
5068 'component' => $reference['component'],
5069 'filearea' => $reference['filearea'],
5070 'itemid' => $reference['itemid'],
5071 ), '', 'info, newcontextid, newitemid');
5075 foreach ($candidates as $candidate) {
5076 $candidateinfo = backup_controller_dbops
::decode_backup_temp_info($candidate->info
);
5077 if ($candidateinfo->filename
=== $reference['filename']
5078 and $candidateinfo->filepath
=== $reference['filepath']
5079 and !is_null($candidate->newcontextid
)
5080 and !is_null($candidate->newitemid
) ) {
5081 $source = $candidateinfo;
5082 $source->contextid
= $candidate->newcontextid
;
5083 $source->itemid
= $candidate->newitemid
;
5087 $candidates->close();
5090 // We have an alias that refers to another file also included in
5091 // the backup. Let us change the reference field so that it refers
5092 // to the restored copy of the original file.
5093 $reference = file_storage
::pack_reference($source);
5095 // Send the new alias to the filepool.
5096 $fs->create_file_from_reference($info->newfile
, $repository->id
, $reference);
5097 $this->notify_success($info);
5101 // This is a reference to some moodle file that was not contained in the backup
5102 // file. If we are restoring to the same site, keep the reference untouched
5103 // and restore the alias as is if the referenced file exists.
5104 if ($this->task
->is_samesite()) {
5105 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5106 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5107 $reference = file_storage
::pack_reference($reference);
5108 $fs->create_file_from_reference($info->newfile
, $repository->id
, $reference);
5109 $this->notify_success($info);
5112 $this->notify_failure($info, 'referenced file not found');
5116 // If we are at other site, we can't restore this alias.
5118 $this->notify_failure($info, 'referenced file not included');
5123 } else if ($info->oldfile
->repositorytype
=== 'user') {
5124 if ($this->task
->is_samesite()) {
5125 // For aliases to user Private files at the same site, we have a chance to check
5126 // if the referenced file still exists.
5128 $reference = file_storage
::unpack_reference($info->oldfile
->reference
);
5129 } catch (Exception
$e) {
5130 $this->notify_failure($info, 'invalid reference field format');
5133 if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5134 $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5135 $reference = file_storage
::pack_reference($reference);
5136 $fs->create_file_from_reference($info->newfile
, $repository->id
, $reference);
5137 $this->notify_success($info);
5140 $this->notify_failure($info, 'referenced file not found');
5144 // If we are at other site, we can't restore this alias.
5146 $this->notify_failure($info, 'restoring at another site');
5151 // This is a reference to some external file such as in boxnet or dropbox.
5152 // If we are restoring to the same site, keep the reference untouched and
5153 // restore the alias as is.
5154 if ($this->task
->is_samesite()) {
5155 $fs->create_file_from_reference($info->newfile
, $repository->id
, $info->oldfile
->reference
);
5156 $this->notify_success($info);
5159 // If we are at other site, we can't restore this alias.
5161 $this->notify_failure($info, 'restoring at another site');
5170 * Choose the repository instance that should handle the alias.
5172 * At the same site, we can rely on repository instance id and we just
5173 * check it still exists. On other site, try to find matching Server files or
5174 * Legacy course files repository instance. Return null if no matching
5175 * repository instance can be found.
5177 * @param stdClass $info
5178 * @return repository|null
5180 private function choose_repository(stdClass
$info) {
5182 require_once($CFG->dirroot
.'/repository/lib.php');
5184 if ($this->task
->is_samesite()) {
5185 // We can rely on repository instance id.
5187 if (array_key_exists($info->oldfile
->repositoryid
, $this->cachereposbyid
)) {
5188 return $this->cachereposbyid
[$info->oldfile
->repositoryid
];
5191 $this->log('looking for repository instance by id', backup
::LOG_DEBUG
, $info->oldfile
->repositoryid
, 1);
5194 $this->cachereposbyid
[$info->oldfile
->repositoryid
] = repository
::get_repository_by_id($info->oldfile
->repositoryid
, SYSCONTEXTID
);
5195 return $this->cachereposbyid
[$info->oldfile
->repositoryid
];
5196 } catch (Exception
$e) {
5197 $this->cachereposbyid
[$info->oldfile
->repositoryid
] = null;
5202 // We can rely on repository type only.
5204 if (empty($info->oldfile
->repositorytype
)) {
5208 if (array_key_exists($info->oldfile
->repositorytype
, $this->cachereposbytype
)) {
5209 return $this->cachereposbytype
[$info->oldfile
->repositorytype
];
5212 $this->log('looking for repository instance by type', backup
::LOG_DEBUG
, $info->oldfile
->repositorytype
, 1);
5214 // Both Server files and Legacy course files repositories have a single
5215 // instance at the system context to use. Let us try to find it.
5216 if ($info->oldfile
->repositorytype
=== 'local' or $info->oldfile
->repositorytype
=== 'coursefiles') {
5217 $sql = "SELECT ri.id
5219 JOIN {repository_instances} ri ON ri.typeid = r.id
5220 WHERE r.type = ? AND ri.contextid = ?";
5221 $ris = $DB->get_records_sql($sql, array($info->oldfile
->repositorytype
, SYSCONTEXTID
));
5225 $repoids = array_keys($ris);
5226 $repoid = reset($repoids);
5228 $this->cachereposbytype
[$info->oldfile
->repositorytype
] = repository
::get_repository_by_id($repoid, SYSCONTEXTID
);
5229 return $this->cachereposbytype
[$info->oldfile
->repositorytype
];
5230 } catch (Exception
$e) {
5231 $this->cachereposbytype
[$info->oldfile
->repositorytype
] = null;
5236 $this->cachereposbytype
[$info->oldfile
->repositorytype
] = null;
5242 * Let the user know that the given alias was successfully restored
5244 * @param stdClass $info
5246 private function notify_success(stdClass
$info) {
5247 $filedesc = $this->describe_alias($info);
5248 $this->log('successfully restored alias', backup
::LOG_DEBUG
, $filedesc, 1);
5252 * Let the user know that the given alias can't be restored
5254 * @param stdClass $info
5255 * @param string $reason detailed reason to be logged
5257 private function notify_failure(stdClass
$info, $reason = '') {
5258 $filedesc = $this->describe_alias($info);
5260 $reason = ' ('.$reason.')';
5262 $this->log('unable to restore alias'.$reason, backup
::LOG_WARNING
, $filedesc, 1);
5263 $this->add_result_item('file_aliases_restore_failures', $filedesc);
5267 * Return a human readable description of the alias file
5269 * @param stdClass $info
5272 private function describe_alias(stdClass
$info) {
5274 $filedesc = $this->expected_alias_location($info->newfile
);
5276 if (!is_null($info->oldfile
->source
)) {
5277 $filedesc .= ' ('.$info->oldfile
->source
.')';
5284 * Return the expected location of a file
5286 * Please note this may and may not work as a part of URL to pluginfile.php
5287 * (depends on how the given component/filearea deals with the itemid).
5289 * @param stdClass $filerecord
5292 private function expected_alias_location($filerecord) {
5294 $filedesc = '/'.$filerecord->contextid
.'/'.$filerecord->component
.'/'.$filerecord->filearea
;
5295 if (!is_null($filerecord->itemid
)) {
5296 $filedesc .= '/'.$filerecord->itemid
;
5298 $filedesc .= $filerecord->filepath
.$filerecord->filename
;
5304 * Append a value to the given resultset
5306 * @param string $name name of the result containing a list of values
5307 * @param mixed $value value to add as another item in that result
5309 private function add_result_item($name, $value) {
5311 $results = $this->task
->get_results();
5313 if (isset($results[$name])) {
5314 if (!is_array($results[$name])) {
5315 throw new coding_exception('Unable to append a result item into a non-array structure.');
5317 $current = $results[$name];
5318 $current[] = $value;
5319 $this->task
->add_result(array($name => $current));
5322 $this->task
->add_result(array($name => array($value)));
5329 * Helper code for use by any plugin that stores question attempt data that it needs to back up.
5331 trait restore_questions_attempt_data_trait
{
5332 /** @var array question_attempt->id to qtype. */
5333 protected $qtypes = array();
5334 /** @var array question_attempt->id to questionid. */
5335 protected $newquestionids = array();
5338 * Attach below $element (usually attempts) the needed restore_path_elements
5339 * to restore question_usages and all they contain.
5341 * If you use the $nameprefix parameter, then you will need to implement some
5342 * extra methods in your class, like
5344 * protected function process_{nameprefix}question_attempt($data) {
5345 * $this->restore_question_usage_worker($data, '{nameprefix}');
5347 * protected function process_{nameprefix}question_attempt($data) {
5348 * $this->restore_question_attempt_worker($data, '{nameprefix}');
5350 * protected function process_{nameprefix}question_attempt_step($data) {
5351 * $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5354 * @param restore_path_element $element the parent element that the usages are stored inside.
5355 * @param array $paths the paths array that is being built.
5356 * @param string $nameprefix should match the prefix passed to the corresponding
5357 * backup_questions_activity_structure_step::add_question_usages call.
5359 protected function add_question_usages($element, &$paths, $nameprefix = '') {
5360 // Check $element is restore_path_element
5361 if (! $element instanceof restore_path_element
) {
5362 throw new restore_step_exception('element_must_be_restore_path_element', $element);
5365 // Check $paths is one array
5366 if (!is_array($paths)) {
5367 throw new restore_step_exception('paths_must_be_array', $paths);
5369 $paths[] = new restore_path_element($nameprefix . 'question_usage',
5370 $element->get_path() . "/{$nameprefix}question_usage");
5371 $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5372 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5373 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5374 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5376 $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5377 $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5381 * Process question_usages
5383 public function process_question_usage($data) {
5384 $this->restore_question_usage_worker($data, '');
5388 * Process question_attempts
5390 public function process_question_attempt($data) {
5391 $this->restore_question_attempt_worker($data, '');
5395 * Process question_attempt_steps
5397 public function process_question_attempt_step($data) {
5398 $this->restore_question_attempt_step_worker($data, '');
5402 * This method does the actual work for process_question_usage or
5403 * process_{nameprefix}_question_usage.
5404 * @param array $data the data from the XML file.
5405 * @param string $nameprefix the element name prefix.
5407 protected function restore_question_usage_worker($data, $nameprefix) {
5410 // Clear our caches.
5411 $this->qtypes
= array();
5412 $this->newquestionids
= array();
5414 $data = (object)$data;
5417 $data->contextid
= $this->task
->get_contextid();
5419 // Everything ready, insert (no mapping needed)
5420 $newitemid = $DB->insert_record('question_usages', $data);
5422 $this->inform_new_usage_id($newitemid);
5424 $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
5428 * When process_question_usage creates the new usage, it calls this method
5429 * to let the activity link to the new usage. For example, the quiz uses
5430 * this method to set quiz_attempts.uniqueid to the new usage id.
5431 * @param integer $newusageid
5433 abstract protected function inform_new_usage_id($newusageid);
5436 * This method does the actual work for process_question_attempt or
5437 * process_{nameprefix}_question_attempt.
5438 * @param array $data the data from the XML file.
5439 * @param string $nameprefix the element name prefix.
5441 protected function restore_question_attempt_worker($data, $nameprefix) {
5444 $data = (object)$data;
5446 $question = $this->get_mapping('question', $data->questionid
);
5448 $data->questionusageid
= $this->get_new_parentid($nameprefix . 'question_usage');
5449 $data->questionid
= $question->newitemid
;
5450 if (!property_exists($data, 'variant')) {
5454 if (!property_exists($data, 'maxfraction')) {
5455 $data->maxfraction
= 1;
5458 $newitemid = $DB->insert_record('question_attempts', $data);
5460 $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
5461 $this->qtypes
[$newitemid] = $question->info
->qtype
;
5462 $this->newquestionids
[$newitemid] = $data->questionid
;
5466 * This method does the actual work for process_question_attempt_step or
5467 * process_{nameprefix}_question_attempt_step.
5468 * @param array $data the data from the XML file.
5469 * @param string $nameprefix the element name prefix.
5471 protected function restore_question_attempt_step_worker($data, $nameprefix) {
5474 $data = (object)$data;
5477 // Pull out the response data.
5478 $response = array();
5479 if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
5480 foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
5481 $response[$variable['name']] = $variable['value'];
5484 unset($data->response
);
5486 $data->questionattemptid
= $this->get_new_parentid($nameprefix . 'question_attempt');
5487 $data->userid
= $this->get_mappingid('user', $data->userid
);
5489 // Everything ready, insert and create mapping (needed by question_sessions)
5490 $newitemid = $DB->insert_record('question_attempt_steps', $data);
5491 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
5493 // Now process the response data.
5494 $response = $this->questions_recode_response_data(
5495 $this->qtypes
[$data->questionattemptid
],
5496 $this->newquestionids
[$data->questionattemptid
],
5497 $data->sequencenumber
, $response);
5499 foreach ($response as $name => $value) {
5500 $row = new stdClass();
5501 $row->attemptstepid
= $newitemid;
5503 $row->value
= $value;
5504 $DB->insert_record('question_attempt_step_data', $row, false);
5509 * Recode the respones data for a particular step of an attempt at at particular question.
5510 * @param string $qtype the question type.
5511 * @param int $newquestionid the question id.
5512 * @param int $sequencenumber the sequence number.
5513 * @param array $response the response data to recode.
5515 public function questions_recode_response_data(
5516 $qtype, $newquestionid, $sequencenumber, array $response) {
5517 $qtyperestorer = $this->get_qtype_restorer($qtype);
5518 if ($qtyperestorer) {
5519 $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
5525 * Given a list of question->ids, separated by commas, returns the
5526 * recoded list, with all the restore question mappings applied.
5527 * Note: Used by quiz->questions and quiz_attempts->layout
5528 * Note: 0 = page break (unconverted)
5530 protected function questions_recode_layout($layout) {
5531 // Extracts question id from sequence
5532 if ($questionids = explode(',', $layout)) {
5533 foreach ($questionids as $id => $questionid) {
5534 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
5535 $newquestionid = $this->get_mappingid('question', $questionid);
5536 $questionids[$id] = $newquestionid;
5540 return implode(',', $questionids);
5544 * Get the restore_qtype_plugin subclass for a specific question type.
5545 * @param string $qtype e.g. multichoice.
5546 * @return restore_qtype_plugin instance.
5548 protected function get_qtype_restorer($qtype) {
5549 // Build one static cache to store {@link restore_qtype_plugin}
5550 // while we are needing them, just to save zillions of instantiations
5551 // or using static stuff that will break our nice API
5552 static $qtypeplugins = array();
5554 if (!isset($qtypeplugins[$qtype])) {
5555 $classname = 'restore_qtype_' . $qtype . '_plugin';
5556 if (class_exists($classname)) {
5557 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
5559 $qtypeplugins[$qtype] = null;
5562 return $qtypeplugins[$qtype];
5565 protected function after_execute() {
5566 parent
::after_execute();
5568 // Restore any files belonging to responses.
5569 foreach (question_engine
::get_all_response_file_areas() as $filearea) {
5570 $this->add_related_files('question', $filearea, 'question_attempt_step');
5577 * Abstract structure step to help activities that store question attempt data.
5579 * @copyright 2011 The Open University
5580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5582 abstract class restore_questions_activity_structure_step
extends restore_activity_structure_step
{
5583 use restore_questions_attempt_data_trait
;
5586 * Attach below $element (usually attempts) the needed restore_path_elements
5587 * to restore question attempt data from Moodle 2.0.
5589 * When using this method, the parent element ($element) must be defined with
5590 * $grouped = true. Then, in that elements process method, you must call
5591 * {@link process_legacy_attempt_data()} with the groupded data. See, for
5592 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
5593 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
5594 * @param array $paths the paths array that is being built to describe the
5597 protected function add_legacy_question_attempt_data($element, &$paths) {
5599 require_once($CFG->dirroot
. '/question/engine/upgrade/upgradelib.php');
5601 // Check $element is restore_path_element
5602 if (!($element instanceof restore_path_element
)) {
5603 throw new restore_step_exception('element_must_be_restore_path_element', $element);
5605 // Check $paths is one array
5606 if (!is_array($paths)) {
5607 throw new restore_step_exception('paths_must_be_array', $paths);
5610 $paths[] = new restore_path_element('question_state',
5611 $element->get_path() . '/states/state');
5612 $paths[] = new restore_path_element('question_session',
5613 $element->get_path() . '/sessions/session');
5616 protected function get_attempt_upgrader() {
5617 if (empty($this->attemptupgrader
)) {
5618 $this->attemptupgrader
= new question_engine_attempt_upgrader();
5619 $this->attemptupgrader
->prepare_to_restore();
5621 return $this->attemptupgrader
;
5625 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
5626 * @param object $data contains all the grouped attempt data to process.
5627 * @param object $quiz data about the activity the attempts belong to. Required
5628 * fields are (basically this only works for the quiz module):
5629 * oldquestions => list of question ids in this activity - using old ids.
5630 * preferredbehaviour => the behaviour to use for questionattempts.
5632 protected function process_legacy_quiz_attempt_data($data, $quiz) {
5634 $upgrader = $this->get_attempt_upgrader();
5636 $data = (object)$data;
5638 $layout = explode(',', $data->layout
);
5639 $newlayout = $layout;
5641 // Convert each old question_session into a question_attempt.
5643 foreach (explode(',', $quiz->oldquestions
) as $questionid) {
5644 if ($questionid == 0) {
5648 $newquestionid = $this->get_mappingid('question', $questionid);
5649 if (!$newquestionid) {
5650 throw new restore_step_exception('questionattemptreferstomissingquestion',
5651 $questionid, $questionid);
5654 $question = $upgrader->load_question($newquestionid, $quiz->id
);
5656 foreach ($layout as $key => $qid) {
5657 if ($qid == $questionid) {
5658 $newlayout[$key] = $newquestionid;
5662 list($qsession, $qstates) = $this->find_question_session_and_states(
5663 $data, $questionid);
5665 if (empty($qsession) ||
empty($qstates)) {
5666 throw new restore_step_exception('questionattemptdatamissing',
5667 $questionid, $questionid);
5670 list($qsession, $qstates) = $this->recode_legacy_response_data(
5671 $question, $qsession, $qstates);
5673 $data->layout
= implode(',', $newlayout);
5674 $qas[$newquestionid] = $upgrader->convert_question_attempt(
5675 $quiz, $data, $question, $qsession, $qstates);
5678 // Now create a new question_usage.
5679 $usage = new stdClass();
5680 $usage->component
= 'mod_quiz';
5681 $usage->contextid
= $this->get_mappingid('context', $this->task
->get_old_contextid());
5682 $usage->preferredbehaviour
= $quiz->preferredbehaviour
;
5683 $usage->id
= $DB->insert_record('question_usages', $usage);
5685 $this->inform_new_usage_id($usage->id
);
5687 $data->uniqueid
= $usage->id
;
5688 $upgrader->save_usage($quiz->preferredbehaviour
, $data, $qas,
5689 $this->questions_recode_layout($quiz->oldquestions
));
5692 protected function find_question_session_and_states($data, $questionid) {
5694 foreach ($data->sessions
['session'] as $session) {
5695 if ($session['questionid'] == $questionid) {
5696 $qsession = (object) $session;
5702 foreach ($data->states
['state'] as $state) {
5703 if ($state['question'] == $questionid) {
5704 // It would be natural to use $state['seq_number'] as the array-key
5705 // here, but it seems that buggy behaviour in 2.0 and early can
5706 // mean that that is not unique, so we use id, which is guaranteed
5708 $qstates[$state['id']] = (object) $state;
5712 $qstates = array_values($qstates);
5714 return array($qsession, $qstates);
5718 * Recode any ids in the response data
5719 * @param object $question the question data
5720 * @param object $qsession the question sessions.
5721 * @param array $qstates the question states.
5723 protected function recode_legacy_response_data($question, $qsession, $qstates) {
5724 $qsession->questionid
= $question->id
;
5726 foreach ($qstates as &$state) {
5727 $state->question
= $question->id
;
5728 $state->answer
= $this->restore_recode_legacy_answer($state, $question->qtype
);
5731 return array($qsession, $qstates);
5735 * Recode the legacy answer field.
5736 * @param object $state the state to recode the answer of.
5737 * @param string $qtype the question type.
5739 public function restore_recode_legacy_answer($state, $qtype) {
5740 $restorer = $this->get_qtype_restorer($qtype);
5742 return $restorer->recode_legacy_state_answer($state);
5744 return $state->answer
;
5751 * Restore completion defaults for each module type
5753 * @package core_backup
5754 * @copyright 2017 Marina Glancy
5755 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5757 class restore_completion_defaults_structure_step
extends restore_structure_step
{
5759 * To conditionally decide if this step must be executed.
5761 protected function execute_condition() {
5762 // No completion on the front page.
5763 if ($this->get_courseid() == SITEID
) {
5767 // No default completion info found, don't execute.
5768 $fullpath = $this->task
->get_taskbasepath();
5769 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename
;
5770 if (!file_exists($fullpath)) {
5774 // Arrived here, execute the step.
5779 * Function that will return the structure to be processed by this restore_step.
5781 * @return restore_path_element[]
5783 protected function define_structure() {
5784 return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
5788 * Processor for path element 'completion_defaults'
5790 * @param stdClass|array $data
5792 protected function process_completion_defaults($data) {
5795 $data = (array)$data;
5796 $oldid = $data['id'];
5799 // Find the module by name since id may be different in another site.
5800 if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
5803 unset($data['modulename']);
5805 // Find the existing record.
5806 $newid = $DB->get_field('course_completion_defaults', 'id',
5807 ['course' => $this->task
->get_courseid(), 'module' => $mod->id
]);
5809 $newid = $DB->insert_record('course_completion_defaults',
5810 ['course' => $this->task
->get_courseid(), 'module' => $mod->id
] +
$data);
5812 $DB->update_record('course_completion_defaults', ['id' => $newid] +
$data);
5815 // Save id mapping for restoring associated events.
5816 $this->set_mapping('course_completion_defaults', $oldid, $newid);
5821 * Index course after restore.
5823 * @package core_backup
5824 * @copyright 2017 The Open University
5825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5827 class restore_course_search_index
extends restore_execution_step
{
5829 * When this step is executed, we add the course context to the queue for reindexing.
5831 protected function define_execution() {
5832 $context = \context_course
::instance($this->task
->get_courseid());
5833 \core_search\manager
::request_index($context);
5838 * Index activity after restore (when not restoring whole course).
5840 * @package core_backup
5841 * @copyright 2017 The Open University
5842 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5844 class restore_activity_search_index
extends restore_execution_step
{
5846 * When this step is executed, we add the activity context to the queue for reindexing.
5848 protected function define_execution() {
5849 $context = \context
::instance_by_id($this->task
->get_contextid());
5850 \core_search\manager
::request_index($context);
5855 * Index block after restore (when not restoring whole course).
5857 * @package core_backup
5858 * @copyright 2017 The Open University
5859 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5861 class restore_block_search_index
extends restore_execution_step
{
5863 * When this step is executed, we add the block context to the queue for reindexing.
5865 protected function define_execution() {
5866 // A block in the restore list may be skipped because a duplicate is detected.
5867 // In this case, there is no new blockid (or context) to get.
5868 if (!empty($this->task
->get_blockid())) {
5869 $context = \context_block
::instance($this->task
->get_blockid());
5870 \core_search\manager
::request_index($context);
5876 * Restore action events.
5878 * @package core_backup
5879 * @copyright 2017 onwards Ankit Agarwal
5880 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5882 class restore_calendar_action_events
extends restore_execution_step
{
5884 * What to do when this step is executed.
5886 protected function define_execution() {
5887 // We just queue the task here rather trying to recreate everything manually.
5888 // The task will automatically populate all data.
5889 $task = new \core\task\refresh_mod_calendar_events_task
();
5890 $task->set_custom_data(array('courseid' => $this->get_courseid()));
5891 \core\task\manager
::queue_adhoc_task($task, true);