/backup/moodle2/restore_stepslib.php
PHP | 6123 lines | 3605 code | 891 blank | 1627 comment | 663 complexity | 25794f4809af045cc323c6189cf393bd MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- // This file is part of Moodle - http://moodle.org/
- //
- // Moodle is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // Moodle is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
- /**
- * Defines various restore steps that will be used by common tasks in restore
- *
- * @package core_backup
- * @subpackage moodle2
- * @category backup
- * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
- defined('MOODLE_INTERNAL') || die();
- /**
- * delete old directories and conditionally create backup_temp_ids table
- */
- class restore_create_and_clean_temp_stuff extends restore_execution_step {
- protected function define_execution() {
- $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
- // If the table already exists, it's because restore_prechecks have been executed in the same
- // request (without problems) and it already contains a bunch of preloaded information (users...)
- // that we aren't going to execute again
- if ($exists) { // Inform plan about preloaded information
- $this->task->set_preloaded_information();
- }
- // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
- $itemid = $this->task->get_old_contextid();
- $newitemid = context_course::instance($this->get_courseid())->id;
- restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
- // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
- $itemid = $this->task->get_old_system_contextid();
- $newitemid = context_system::instance()->id;
- restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
- // Create the old-course-id to new-course-id mapping, we need that available since the beginning
- $itemid = $this->task->get_old_courseid();
- $newitemid = $this->get_courseid();
- restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
- }
- }
- /**
- * Drop temp ids table and delete the temp dir used by backup/restore (conditionally).
- */
- class restore_drop_and_clean_temp_stuff extends restore_execution_step {
- protected function define_execution() {
- global $CFG;
- restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
- if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
- $progress = $this->task->get_progress();
- $progress->start_progress('Deleting backup dir');
- backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir
- $progress->end_progress();
- }
- }
- }
- /**
- * Restore calculated grade items, grade categories etc
- */
- class restore_gradebook_structure_step extends restore_structure_step {
- /**
- * To conditionally decide if this step must be executed
- * Note the "settings" conditions are evaluated in the
- * corresponding task. Here we check for other conditions
- * not being restore settings (files, site settings...)
- */
- protected function execute_condition() {
- global $CFG, $DB;
- if ($this->get_courseid() == SITEID) {
- return false;
- }
- // No gradebook info found, don't execute
- $fullpath = $this->task->get_taskbasepath();
- $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
- if (!file_exists($fullpath)) {
- return false;
- }
- // Some module present in backup file isn't available to restore
- // in this site, don't execute
- if ($this->task->is_missing_modules()) {
- return false;
- }
- // Some activity has been excluded to be restored, don't execute
- if ($this->task->is_excluding_activities()) {
- return false;
- }
- // There should only be one grade category (the 1 associated with the course itself)
- // If other categories already exist we're restoring into an existing course.
- // Restoring categories into a course with an existing category structure is unlikely to go well
- $category = new stdclass();
- $category->courseid = $this->get_courseid();
- $catcount = $DB->count_records('grade_categories', (array)$category);
- if ($catcount>1) {
- return false;
- }
- // Identify the backup we're dealing with.
- $backuprelease = $this->get_task()->get_info()->backup_release; // The major version: 2.9, 3.0, 3.10...
- $backupbuild = 0;
- preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
- if (!empty($matches[1])) {
- $backupbuild = (int) $matches[1]; // The date of Moodle build at the time of the backup.
- }
- // On older versions the freeze value has to be converted.
- // We do this from here as it is happening right before the file is read.
- // This only targets the backup files that can contain the legacy freeze.
- if ($backupbuild > 20150618 && (version_compare($backuprelease, '3.0', '<') || $backupbuild < 20160527)) {
- $this->rewrite_step_backup_file_for_legacy_freeze($fullpath);
- }
- // Arrived here, execute the step
- return true;
- }
- protected function define_structure() {
- $paths = array();
- $userinfo = $this->task->get_setting_value('users');
- $paths[] = new restore_path_element('attributes', '/gradebook/attributes');
- $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
- $gradeitem = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
- $paths[] = $gradeitem;
- $this->add_plugin_structure('local', $gradeitem);
- if ($userinfo) {
- $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
- }
- $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
- $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
- return $paths;
- }
- protected function process_attributes($data) {
- // For non-merge restore types:
- // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
- $target = $this->get_task()->get_target();
- if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) {
- set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
- }
- if (!empty($data['calculations_freeze'])) {
- if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING ||
- $target == backup::TARGET_EXISTING_DELETING) {
- set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
- }
- }
- }
- protected function process_grade_item($data) {
- global $DB;
- $data = (object)$data;
- $oldid = $data->id;
- $data->course = $this->get_courseid();
- $data->courseid = $this->get_courseid();
- if ($data->itemtype=='manual') {
- // manual grade items store category id in categoryid
- $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
- // if mapping failed put in course's grade category
- if (NULL == $data->categoryid) {
- $coursecat = grade_category::fetch_course_category($this->get_courseid());
- $data->categoryid = $coursecat->id;
- }
- } else if ($data->itemtype=='course') {
- // course grade item stores their category id in iteminstance
- $coursecat = grade_category::fetch_course_category($this->get_courseid());
- $data->iteminstance = $coursecat->id;
- } else if ($data->itemtype=='category') {
- // category grade items store their category id in iteminstance
- $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
- } else {
- throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
- }
- $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
- $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
- $data->locktime = $this->apply_date_offset($data->locktime);
- $coursecategory = $newitemid = null;
- //course grade item should already exist so updating instead of inserting
- if($data->itemtype=='course') {
- //get the ID of the already created grade item
- $gi = new stdclass();
- $gi->courseid = $this->get_courseid();
- $gi->itemtype = $data->itemtype;
- //need to get the id of the grade_category that was automatically created for the course
- $category = new stdclass();
- $category->courseid = $this->get_courseid();
- $category->parent = null;
- //course category fullname starts out as ? but may be edited
- //$category->fullname = '?';
- $coursecategory = $DB->get_record('grade_categories', (array)$category);
- $gi->iteminstance = $coursecategory->id;
- $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
- if (!empty($existinggradeitem)) {
- $data->id = $newitemid = $existinggradeitem->id;
- $DB->update_record('grade_items', $data);
- }
- } else if ($data->itemtype == 'manual') {
- // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
- $gi = array(
- 'itemtype' => $data->itemtype,
- 'courseid' => $data->courseid,
- 'itemname' => $data->itemname,
- 'categoryid' => $data->categoryid,
- );
- $newitemid = $DB->get_field('grade_items', 'id', $gi);
- }
- if (empty($newitemid)) {
- //in case we found the course category but still need to insert the course grade item
- if ($data->itemtype=='course' && !empty($coursecategory)) {
- $data->iteminstance = $coursecategory->id;
- }
- $newitemid = $DB->insert_record('grade_items', $data);
- $data->id = $newitemid;
- $gradeitem = new grade_item($data);
- core\event\grade_item_created::create_from_grade_item($gradeitem)->trigger();
- }
- $this->set_mapping('grade_item', $oldid, $newitemid);
- }
- protected function process_grade_grade($data) {
- global $DB;
- $data = (object)$data;
- $oldid = $data->id;
- $olduserid = $data->userid;
- $data->itemid = $this->get_new_parentid('grade_item');
- $data->userid = $this->get_mappingid('user', $data->userid, null);
- if (!empty($data->userid)) {
- $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
- $data->locktime = $this->apply_date_offset($data->locktime);
- $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
- if ($gradeexists) {
- $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
- $this->log($message, backup::LOG_DEBUG);
- } else {
- $newitemid = $DB->insert_record('grade_grades', $data);
- $this->set_mapping('grade_grades', $oldid, $newitemid);
- }
- } else {
- $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
- $this->log($message, backup::LOG_DEBUG);
- }
- }
- protected function process_grade_category($data) {
- global $DB;
- $data = (object)$data;
- $oldid = $data->id;
- $data->course = $this->get_courseid();
- $data->courseid = $data->course;
- $newitemid = null;
- //no parent means a course level grade category. That may have been created when the course was created
- if(empty($data->parent)) {
- //parent was being saved as 0 when it should be null
- $data->parent = null;
- //get the already created course level grade category
- $category = new stdclass();
- $category->courseid = $this->get_courseid();
- $category->parent = null;
- $coursecategory = $DB->get_record('grade_categories', (array)$category);
- if (!empty($coursecategory)) {
- $data->id = $newitemid = $coursecategory->id;
- $DB->update_record('grade_categories', $data);
- }
- }
- // Add a warning about a removed setting.
- if (!empty($data->aggregatesubcats)) {
- set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
- }
- //need to insert a course category
- if (empty($newitemid)) {
- $newitemid = $DB->insert_record('grade_categories', $data);
- }
- $this->set_mapping('grade_category', $oldid, $newitemid);
- }
- protected function process_grade_letter($data) {
- global $DB;
- $data = (object)$data;
- $oldid = $data->id;
- $data->contextid = context_course::instance($this->get_courseid())->id;
- $gradeletter = (array)$data;
- unset($gradeletter['id']);
- if (!$DB->record_exists('grade_letters', $gradeletter)) {
- $newitemid = $DB->insert_record('grade_letters', $data);
- } else {
- $newitemid = $data->id;
- }
- $this->set_mapping('grade_letter', $oldid, $newitemid);
- }
- protected function process_grade_setting($data) {
- global $DB;
- $data = (object)$data;
- $oldid = $data->id;
- $data->courseid = $this->get_courseid();
- $target = $this->get_task()->get_target();
- if ($data->name == 'minmaxtouse' &&
- ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) {
- // We never restore minmaxtouse during merge.
- return;
- }
- if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
- $newitemid = $DB->insert_record('grade_settings', $data);
- } else {
- $newitemid = $data->id;
- }
- if (!empty($oldid)) {
- // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
- $this->set_mapping('grade_setting', $oldid, $newitemid);
- }
- }
- /**
- * put all activity grade items in the correct grade category and mark all for recalculation
- */
- protected function after_execute() {
- global $DB;
- $conditions = array(
- 'backupid' => $this->get_restoreid(),
- 'itemname' => 'grade_item'//,
- //'itemid' => $itemid
- );
- $rs = $DB->get_recordset('backup_ids_temp', $conditions);
- // We need this for calculation magic later on.
- $mappings = array();
- if (!empty($rs)) {
- foreach($rs as $grade_item_backup) {
- // Store the oldid with the new id.
- $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
- $updateobj = new stdclass();
- $updateobj->id = $grade_item_backup->newitemid;
- //if this is an activity grade item that needs to be put back in its correct category
- if (!empty($grade_item_backup->parentitemid)) {
- $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
- if (!is_null($oldcategoryid)) {
- $updateobj->categoryid = $oldcategoryid;
- $DB->update_record('grade_items', $updateobj);
- }
- } else {
- //mark course and category items as needing to be recalculated
- $updateobj->needsupdate=1;
- $DB->update_record('grade_items', $updateobj);
- }
- }
- }
- $rs->close();
- // We need to update the calculations for calculated grade items that may reference old
- // grade item ids using ##gi\d+##.
- // $mappings can be empty, use 0 if so (won't match ever)
- list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
- $sql = "SELECT gi.id, gi.calculation
- FROM {grade_items} gi
- WHERE gi.id {$sql} AND
- calculation IS NOT NULL";
- $rs = $DB->get_recordset_sql($sql, $params);
- foreach ($rs as $gradeitem) {
- // Collect all of the used grade item id references
- if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
- // This calculation doesn't reference any other grade items... EASY!
- continue;
- }
- // For this next bit we are going to do the replacement of id's in two steps:
- // 1. We will replace all old id references with a special mapping reference.
- // 2. We will replace all mapping references with id's
- // Why do we do this?
- // Because there potentially there will be an overlap of ids within the query and we
- // we substitute the wrong id.. safest way around this is the two step system
- $calculationmap = array();
- $mapcount = 0;
- foreach ($matches[1] as $match) {
- // Check that the old id is known to us, if not it was broken to begin with and will
- // continue to be broken.
- if (!array_key_exists($match, $mappings)) {
- continue;
- }
- // Our special mapping key
- $mapping = '##MAPPING'.$mapcount.'##';
- // The old id that exists within the calculation now
- $oldid = '##gi'.$match.'##';
- // The new id that we want to replace the old one with.
- $newid = '##gi'.$mappings[$match].'##';
- // Replace in the special mapping key
- $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
- // And record the mapping
- $calculationmap[$mapping] = $newid;
- $mapcount++;
- }
- // Iterate all special mappings for this calculation and replace in the new id's
- foreach ($calculationmap as $mapping => $newid) {
- $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
- }
- // Update the calculation now that its being remapped
- $DB->update_record('grade_items', $gradeitem);
- }
- $rs->close();
- // Need to correct the grade category path and parent
- $conditions = array(
- 'courseid' => $this->get_courseid()
- );
- $rs = $DB->get_recordset('grade_categories', $conditions);
- // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
- foreach ($rs as $gc) {
- if (!empty($gc->parent)) {
- $grade_category = new stdClass();
- $grade_category->id = $gc->id;
- $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
- $DB->update_record('grade_categories', $grade_category);
- }
- }
- $rs->close();
- // Now we can rebuild all the paths
- $rs = $DB->get_recordset('grade_categories', $conditions);
- foreach ($rs as $gc) {
- $grade_category = new stdClass();
- $grade_category->id = $gc->id;
- $grade_category->path = grade_category::build_path($gc);
- $grade_category->depth = substr_count($grade_category->path, '/') - 1;
- $DB->update_record('grade_categories', $grade_category);
- }
- $rs->close();
- // Check what to do with the minmaxtouse setting.
- $this->check_minmaxtouse();
- // Freeze gradebook calculations if needed.
- $this->gradebook_calculation_freeze();
- // Ensure the module cache is current when recalculating grades.
- rebuild_course_cache($this->get_courseid(), true);
- // Restore marks items as needing update. Update everything now.
- grade_regrade_final_grades($this->get_courseid());
- }
- /**
- * Freeze gradebook calculation if needed.
- *
- * This is similar to various upgrade scripts that check if the freeze is needed.
- */
- protected function gradebook_calculation_freeze() {
- global $CFG;
- $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
- preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
- $backupbuild = (int)$matches[1];
- $backuprelease = $this->get_task()->get_info()->backup_release; // The major version: 2.9, 3.0, 3.10...
- // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
- if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) {
- require_once($CFG->libdir . '/db/upgradelib.php');
- upgrade_extra_credit_weightoverride($this->get_courseid());
- }
- // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
- if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) {
- require_once($CFG->libdir . '/db/upgradelib.php');
- upgrade_calculated_grade_items($this->get_courseid());
- }
- // Courses from before 3.1 (20160518) may have a letter boundary problem and should be checked for this issue.
- // Backups from before and including 2.9 could have a build number that is greater than 20160518 and should
- // be checked for this problem.
- if (!$gradebookcalculationsfreeze && ($backupbuild < 20160518 || version_compare($backuprelease, '2.9', '<='))) {
- require_once($CFG->libdir . '/db/upgradelib.php');
- upgrade_course_letter_boundary($this->get_courseid());
- }
- }
- /**
- * Checks what should happen with the course grade setting minmaxtouse.
- *
- * This is related to the upgrade step at the time the setting was added.
- *
- * @see MDL-48618
- * @return void
- */
- protected function check_minmaxtouse() {
- global $CFG, $DB;
- require_once($CFG->libdir . '/gradelib.php');
- $userinfo = $this->task->get_setting_value('users');
- $settingname = 'minmaxtouse';
- $courseid = $this->get_courseid();
- $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
- $version28start = 2014111000.00;
- $version28last = 2014111006.05;
- $version29start = 2015051100.00;
- $version29last = 2015060400.02;
- $target = $this->get_task()->get_target();
- if ($minmaxtouse === false &&
- ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
- // The setting was not found because this setting did not exist at the time the backup was made.
- // And we are not restoring as merge, in which case we leave the course as it was.
- $version = $this->get_task()->get_info()->moodle_version;
- if ($version < $version28start) {
- // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
- if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
- grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
- }
- } else if (($version >= $version28start && $version < $version28last) ||
- ($version >= $version29start && $version < $version29last)) {
- // They should be using grade_grade when the course has inconsistencies.
- $sql = "SELECT gi.id
- FROM {grade_items} gi
- JOIN {grade_grades} gg
- ON gg.itemid = gi.id
- WHERE gi.courseid = ?
- AND (gi.itemtype != ? AND gi.itemtype != ?)
- AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
- // The course can only have inconsistencies when we restore the user info,
- // we do not need to act on existing grades that were not restored as part of this backup.
- if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
- // Display the notice as we do during upgrade.
- set_config('show_min_max_grades_changed_' . $courseid, 1);
- if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
- // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
- // If they are using the site-wide grade_grade setting, we only want to notice them.
- grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
- }
- }
- } else {
- // This should never happen because from now on minmaxtouse is always saved in backups.
- }
- }
- }
- /**
- * Rewrite step definition to handle the legacy freeze attribute.
- *
- * In previous backups the calculations_freeze property was stored as an attribute of the
- * top level node <gradebook>. The backup API, however, do not process grandparent nodes.
- * It only processes definitive children, and their parent attributes.
- *
- * We had:
- *
- * <gradebook calculations_freeze="20160511">
- * <grade_categories>
- * <grade_category id="10">
- * <depth>1</depth>
- * ...
- * </grade_category>
- * </grade_categories>
- * ...
- * </gradebook>
- *
- * And this method will convert it to:
- *
- * <gradebook >
- * <attributes>
- * <calculations_freeze>20160511</calculations_freeze>
- * </attributes>
- * <grade_categories>
- * <grade_category id="10">
- * <depth>1</depth>
- * ...
- * </grade_category>
- * </grade_categories>
- * ...
- * </gradebook>
- *
- * Note that we cannot just load the XML file in memory as it could potentially be huge.
- * We can also completely ignore if the node <attributes> is already in the backup
- * file as it never existed before.
- *
- * @param string $filepath The absolute path to the XML file.
- * @return void
- */
- protected function rewrite_step_backup_file_for_legacy_freeze($filepath) {
- $foundnode = false;
- $newfile = make_request_directory(true) . DIRECTORY_SEPARATOR . 'file.xml';
- $fr = fopen($filepath, 'r');
- $fw = fopen($newfile, 'w');
- if ($fr && $fw) {
- while (($line = fgets($fr, 4096)) !== false) {
- if (!$foundnode && strpos($line, '<gradebook ') === 0) {
- $foundnode = true;
- $matches = array();
- $pattern = '@calculations_freeze=.([0-9]+).@';
- if (preg_match($pattern, $line, $matches)) {
- $freeze = $matches[1];
- $line = preg_replace($pattern, '', $line);
- $line .= " <attributes>\n <calculations_freeze>$freeze</calculations_freeze>\n </attributes>\n";
- }
- }
- fputs($fw, $line);
- }
- if (!feof($fr)) {
- throw new restore_step_exception('Error while attempting to rewrite the gradebook step file.');
- }
- fclose($fr);
- fclose($fw);
- if (!rename($newfile, $filepath)) {
- throw new restore_step_exception('Error while attempting to rename the gradebook step file.');
- }
- } else {
- if ($fr) {
- fclose($fr);
- }
- if ($fw) {
- fclose($fw);
- }
- }
- }
- }
- /**
- * Step in charge of restoring the grade history of a course.
- *
- * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
- * we do not want to restore the history if the gradebook and its content has not been
- * restored. At least for now.
- */
- class restore_grade_history_structure_step extends restore_structure_step {
- protected function execute_condition() {
- global $CFG, $DB;
- if ($this->get_courseid() == SITEID) {
- return false;
- }
- // No gradebook info found, don't execute.
- $fullpath = $this->task->get_taskbasepath();
- $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
- if (!file_exists($fullpath)) {
- return false;
- }
- // Some module present in backup file isn't available to restore in this site, don't execute.
- if ($this->task->is_missing_modules()) {
- return false;
- }
- // Some activity has been excluded to be restored, don't execute.
- if ($this->task->is_excluding_activities()) {
- return false;
- }
- // There should only be one grade category (the 1 associated with the course itself).
- $category = new stdclass();
- $category->courseid = $this->get_courseid();
- $catcount = $DB->count_records('grade_categories', (array)$category);
- if ($catcount > 1) {
- return false;
- }
- // Arrived here, execute the step.
- return true;
- }
- protected function define_structure() {
- $paths = array();
- // Settings to use.
- $userinfo = $this->get_setting_value('users');
- $history = $this->get_setting_value('grade_histories');
- if ($userinfo && $history) {
- $paths[] = new restore_path_element('grade_grade',
- '/grade_history/grade_grades/grade_grade');
- }
- return $paths;
- }
- protected function process_grade_grade($data) {
- global $DB;
- $data = (object)($data);
- $olduserid = $data->userid;
- unset($data->id);
- $data->userid = $this->get_mappingid('user', $data->userid, null);
- if (!empty($data->userid)) {
- // Do not apply the date offsets as this is history.
- $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
- $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
- $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
- $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
- $DB->insert_record('grade_grades_history', $data);
- } else {
- $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
- $this->log($message, backup::LOG_DEBUG);
- }
- }
- }
- /**
- * decode all the interlinks present in restored content
- * relying 100% in the restore_decode_processor that handles
- * both the contents to modify and the rules to be applied
- */
- class restore_decode_interlinks extends restore_execution_step {
- protected function define_execution() {
- // Get the decoder (from the plan)
- $decoder = $this->task->get_decoder();
- restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
- // And launch it, everything will be processed
- $decoder->execute();
- }
- }
- /**
- * first, ensure that we have no gaps in section numbers
- * and then, rebuid the course cache
- */
- class restore_rebuild_course_cache extends restore_execution_step {
- protected function define_execution() {
- global $DB;
- // Although there is some sort of auto-recovery of missing sections
- // present in course/formats... here we check that all the sections
- // from 0 to MAX(section->section) exist, creating them if necessary
- $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
- // Iterate over all sections
- for ($i = 0; $i <= $maxsection; $i++) {
- // If the section $i doesn't exist, create it
- if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
- $sectionrec = array(
- 'course' => $this->get_courseid(),
- 'section' => $i,
- 'timemodified' => time());
- $DB->insert_record('course_sections', $sectionrec); // missing section created
- }
- }
- // Rebuild cache now that all sections are in place
- rebuild_course_cache($this->get_courseid());
- cache_helper::purge_by_event('changesincourse');
- cache_helper::purge_by_event('changesincoursecat');
- }
- }
- /**
- * Review all the tasks having one after_restore method
- * executing it to perform some final adjustments of information
- * not available when the task was executed.
- */
- class restore_execute_after_restore extends restore_execution_step {
- protected function define_execution() {
- // Simply call to the execute_after_restore() method of the task
- // that always is the restore_final_task
- $this->task->launch_execute_after_restore();
- }
- }
- /**
- * Review all the (pending) block positions in backup_ids, matching by
- * contextid, creating positions as needed. This is executed by the
- * final task, once all the contexts have been created
- */
- class restore_review_pending_block_positions extends restore_execution_step {
- protected function define_execution() {
- global $DB;
- // Get all the block_position objects pending to match
- $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
- $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
- // Process block positions, creating them or accumulating for final step
- foreach($rs as $posrec) {
- // Get the complete position object out of the info field.
- $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
- // If position is for one already mapped (known) contextid
- // process it now, creating the position, else nothing to
- // do, position finally discarded
- if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
- $position->contextid = $newctx->newitemid;
- // Create the block position
- $DB->insert_record('block_positions', $position);
- }
- }
- $rs->close();
- }
- }
- /**
- * Updates the availability data for course modules and sections.
- *
- * Runs after the restore of all course modules, sections, and grade items has
- * completed. This is necessary in order to update IDs that have changed during
- * restore.
- *
- * @package core_backup
- * @copyright 2014 The Open University
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
- class restore_update_availability extends restore_execution_step {
- protected function define_execution() {
- global $CFG, $DB;
- // Note: This code runs even if availability is disabled when restoring.
- // That will ensure that if you later turn availability on for the site,
- // there will be no incorrect IDs. (It doesn't take long if the restored
- // data does not contain any availability information.)
- // Get modinfo with all data after resetting cache.
- rebuild_course_cache($this->get_courseid(), true);
- $modinfo = get_fast_modinfo($this->get_courseid());
- // Get the date offset for this restore.
- $dateoffset = $this->apply_date_offset(1) - 1;
- // Update all sections that were restored.
- $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
- $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
- $sectionsbyid = null;
- foreach ($rs as $rec) {
- if (is_null($sectionsbyid)) {
- $sectionsbyid = array();
- foreach ($modinfo->get_section_info_all() as $section) {
- $sectionsbyid[$section->id] = $section;
- }
- }
- if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
- // If the section was not fully restored for some reason
- // (e.g. due to an earlier error), skip it.
- $this->get_logger()->process('Section not fully restored: id ' .
- $rec->newitemid, backup::LOG_WARNING);
- continue;
- }
- $section = $sectionsbyid[$rec->newitemid];
- if (!is_null($section->availability)) {
- $info = new \core_availability\info_section($section);
- $info->update_after_restore($this->get_restoreid(),
- $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
- }
- }
- $rs->close();
- // Update all modules that were restored.
- $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
- $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
- foreach ($rs as $rec) {
- if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
- // If the module was not fully restored for some reason
- // (e.g. due to an earlier error), skip it.
- $this->get_logger()->process('Module not fully restored: id ' .
- $rec->newitemid, backup::LOG_WARNING);
- continue;
- }
- $cm = $modinfo->get_cm($rec->newitemid);
- if (!is_null($cm->availability)) {
- $info = new \core_availability\info_module($cm);
- $info->update_after_restore($this->get_restoreid(),
- $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
- }
- }
- $rs->close();
- }
- }
- /**
- * Process legacy module availability records in backup_ids.
- *
- * Matches course modules and grade item id once all them have been already restored.
- * Only if all matchings are satisfied the availability condition will be created.
- * At the same time, it is required for the site to have that functionality enabled.
- *
- * This step is included only to handle legacy backups (2.6 and before). It does not
- * do anything for newer backups.
- *
- * @copyright 2014 The Open University
- * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
- */
- class restore_process_course_modules_availability extends restore_execution_step {
- protected function define_execution() {
- global $CFG, $DB;
- // Site hasn't availability enabled
- if (empty($CFG->enableavailability)) {
- return;
- }
- // Do both modules and sections.
- foreach (array('module', 'section') as $table) {
- // Get all the availability objects to process.
- $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
- $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
- // Process availabilities, creating them if everything matches ok.
- foreach ($rs as $availrec) {
- $allmatchesok = true;
- // Get the complete legacy availability object.
- $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
- // Note: This code used to update IDs, but that is now handled by the
- // current code (after restore) instead of this legacy code.
- // Get showavailability option.
- $thingid = ($table === 'module') ? $availability->coursemoduleid :
- $availability->coursesectionid;
- $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
- $table . '_showavailability', $thingid);
- if (!$showrec) {
- // Should not happen.
- throw new coding_exception('No matching showavailability record');
- }
- $show = $showrec->info->showavailability;
- // The $availability object is now in the format used in the old
- // system. Interpret this and convert to new system.
- $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
- array('id' => $thingid), MUST_EXIST);
- $newvalue = \core_availability\info::add_legacy_availability_condition(
- $currentvalue, $availability, $show);
- $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
- array('id' => $thingid));
- }
- $rs->close();
- }
- }
- }
- /*
- * Execution step that, *conditionally* (if there isn't preloaded information)
- * will load the inforef files for all the included course/section/activity tasks
- * to backup_temp_ids. They will be stored with "xxxxref" as itemname
- */
- class restore_load_included_inforef_records extends restore_execution_step {
- protected function define_execution() {
- if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
- return;
- }
- // Get all the included tasks
- $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
- $progress = $this->task->get_progress();
- $progress->start_progress($this->get_name(), count($tasks));
- foreach ($tasks as $task) {
- // Load the inforef.xml file if exists
- $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
- if (file_exists($inforefpath)) {
- // Load each inforef file to temp_ids.
- restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
- }
- }
- $progress->end_progress();
- }
- }
- /*
- * Execution step that will load all the needed files into backup_files_temp
- * - info: contains the whole original object (times, names...)
- * (all them being original ids as loaded from xml)
- */
- class restore_load_included_files extends restore_structure_step {
- protected function define_structure() {
- $file = new restore_path_element('file', '/files/file');
- return array($file);
- }
- /**
- * Process one <file> element from files.xml
- *
- * @param array $data the element data
- */
- public function process_file($data) {
- $data = (object)$data; // handy
- // load it if needed:
- // - it it is one of the annotated inforef files (course/section/activity/block)
- // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
- // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
- // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
- $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
- $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
- $data->component == 'grouping' || $data->component == 'grade' ||
- $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
- if ($isfileref || $iscomponent) {
- restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
- }
- }
- }
- /**
- * Execution step that, *conditionally* (if there isn't preloaded information),
- * will load all the needed roles to backup_temp_ids. They will be stored with
- * "role" itemname. Also it will perform one automatic mapping to roles existing
- * in the target site, based in permissions of the user performing the restore,
- * archetypes and other bits. At the end, each original role will have its associated
- * target role or 0 if it's going to be skipped. Note we wrap everything over one
- * restore_dbops method, as far as the same stuff is going to be also executed
- * by restore prechecks
- */
- class restore_load_and_map_roles extends restore_execution_step {
- protected function define_execution() {
- if ($this->task->get_preloaded_information()) { // if info is already preloaded
- return;
- }
- $file = $this->get_basepath() . '/roles.xml';
- // Load needed toles to temp_ids
- restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
- // Process roles, mapping/skipping. Any error throws exception
- // Note we pass controller's info because it can contain role mapping information
- // about manual mappings performed by UI
- 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);
- }
- }
- /**
- * Execution step that, *conditionally* (if there isn't preloaded information
- * and users have been selected in settings, will load all the needed users
- * to backup_temp_ids. They will be stored with "user" itemname and with
- * their original contextid as paremitemid
- */
- class restore_load_included_users extends restore_execution_step {
- protected function define_execution() {
- if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
- return;
- }
- if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
- return;
- }
- $file = $this->get_basepath() . '/users.xml';
- // Load needed users to temp_ids.
- restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
- }
- }
- /**
- * Execution step that, *conditionally* (if there isn't preloaded information
- * and users have been selected in settings, will process all the needed users
- * in order to decide and perform any action with them (create / map / error)
- * Note: Any error will cause exception, as far as this is the same processing
- * than the one into restore prechecks (that should have stopped process earlier)
- */
- class restore_process_included_users extends restore_execution_step {
- protected function define_execution() {
- if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
- return;
- }
- if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
- return;
- }
- restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
- $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
- }
- }
- /**
- * Execution step that will create all the needed users as calculated
- * by @restore_process_included_users (those having newiteind = 0)
- */
- class restore_create_included_users extends restore_execution_step {
- protected function define_execution() {
- restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
- $this->task->get_userid(), $this->task->get_progress());
- }
- }
- /**
- * Structure step that will create all the needed groups and groupings
- * by loading them from the groups.xml file performing the required matches.
- * Note group members only will be added if restoring user info
- */
- class restore_groups_structure_step extends restore_structure_step {
- protected function define_structure() {
- $paths = array(); // Add paths here
- // Do not include group/groupings information if not requested.
- $groupinfo = $this->get_setting_value('groups');
- if ($groupinfo) {
- $paths[] = new restore_path_element('group', '/groups/group');
- $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
- $pat…
Large files files are truncated, but you can click here to view the full file