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(time() - (4 * 60 * 60), $progress); // Delete > 4 hours 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 // No gradebook info found, don't execute
93 $fullpath = $this->task->get_taskbasepath();
94 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
95 if (!file_exists($fullpath)) {
99 // Some module present in backup file isn't available to restore
100 // in this site, don't execute
101 if ($this->task->is_missing_modules()) {
105 // Some activity has been excluded to be restored, don't execute
106 if ($this->task->is_excluding_activities()) {
110 // There should only be one grade category (the 1 associated with the course itself)
111 // If other categories already exist we're restoring into an existing course.
112 // Restoring categories into a course with an existing category structure is unlikely to go well
113 $category = new stdclass();
114 $category->courseid = $this->get_courseid();
115 $catcount = $DB->count_records('grade_categories', (array)$category);
120 // Arrived here, execute the step
124 protected function define_structure() {
126 $userinfo = $this->task->get_setting_value('users');
128 $paths[] = new restore_path_element('gradebook', '/gradebook');
129 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
130 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
132 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
134 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
135 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
140 protected function process_gradebook($data) {
143 protected function process_grade_item($data) {
146 $data = (object)$data;
149 $data->course = $this->get_courseid();
151 $data->courseid = $this->get_courseid();
153 if ($data->itemtype=='manual') {
154 // manual grade items store category id in categoryid
155 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
156 // if mapping failed put in course's grade category
157 if (NULL == $data->categoryid) {
158 $coursecat = grade_category::fetch_course_category($this->get_courseid());
159 $data->categoryid = $coursecat->id;
161 } else if ($data->itemtype=='course') {
162 // course grade item stores their category id in iteminstance
163 $coursecat = grade_category::fetch_course_category($this->get_courseid());
164 $data->iteminstance = $coursecat->id;
165 } else if ($data->itemtype=='category') {
166 // category grade items store their category id in iteminstance
167 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
169 throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
172 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
173 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
175 $data->locktime = $this->apply_date_offset($data->locktime);
176 $data->timecreated = $this->apply_date_offset($data->timecreated);
177 $data->timemodified = $this->apply_date_offset($data->timemodified);
179 $coursecategory = $newitemid = null;
180 //course grade item should already exist so updating instead of inserting
181 if($data->itemtype=='course') {
182 //get the ID of the already created grade item
183 $gi = new stdclass();
184 $gi->courseid = $this->get_courseid();
185 $gi->itemtype = $data->itemtype;
187 //need to get the id of the grade_category that was automatically created for the course
188 $category = new stdclass();
189 $category->courseid = $this->get_courseid();
190 $category->parent = null;
191 //course category fullname starts out as ? but may be edited
192 //$category->fullname = '?';
193 $coursecategory = $DB->get_record('grade_categories', (array)$category);
194 $gi->iteminstance = $coursecategory->id;
196 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
197 if (!empty($existinggradeitem)) {
198 $data->id = $newitemid = $existinggradeitem->id;
199 $DB->update_record('grade_items', $data);
201 } else if ($data->itemtype == 'manual') {
202 // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
204 'itemtype' => $data->itemtype,
205 'courseid' => $data->courseid,
206 'itemname' => $data->itemname,
207 'categoryid' => $data->categoryid,
209 $newitemid = $DB->get_field('grade_items', 'id', $gi);
212 if (empty($newitemid)) {
213 //in case we found the course category but still need to insert the course grade item
214 if ($data->itemtype=='course' && !empty($coursecategory)) {
215 $data->iteminstance = $coursecategory->id;
218 $newitemid = $DB->insert_record('grade_items', $data);
220 $this->set_mapping('grade_item', $oldid, $newitemid);
223 protected function process_grade_grade($data) {
226 $data = (object)$data;
227 $olduserid = $data->userid;
229 $data->itemid = $this->get_new_parentid('grade_item');
231 $data->userid = $this->get_mappingid('user', $data->userid, null);
232 if (!empty($data->userid)) {
233 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
234 $data->locktime = $this->apply_date_offset($data->locktime);
235 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
236 $data->overridden = $this->apply_date_offset($data->overridden);
237 $data->timecreated = $this->apply_date_offset($data->timecreated);
238 $data->timemodified = $this->apply_date_offset($data->timemodified);
240 $newitemid = $DB->insert_record('grade_grades', $data);
242 $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
243 $this->log($message, backup::LOG_DEBUG);
247 protected function process_grade_category($data) {
250 $data = (object)$data;
253 $data->course = $this->get_courseid();
254 $data->courseid = $data->course;
256 $data->timecreated = $this->apply_date_offset($data->timecreated);
257 $data->timemodified = $this->apply_date_offset($data->timemodified);
260 //no parent means a course level grade category. That may have been created when the course was created
261 if(empty($data->parent)) {
262 //parent was being saved as 0 when it should be null
263 $data->parent = null;
265 //get the already created course level grade category
266 $category = new stdclass();
267 $category->courseid = $this->get_courseid();
268 $category->parent = null;
270 $coursecategory = $DB->get_record('grade_categories', (array)$category);
271 if (!empty($coursecategory)) {
272 $data->id = $newitemid = $coursecategory->id;
273 $DB->update_record('grade_categories', $data);
277 //need to insert a course category
278 if (empty($newitemid)) {
279 $newitemid = $DB->insert_record('grade_categories', $data);
281 $this->set_mapping('grade_category', $oldid, $newitemid);
283 protected function process_grade_letter($data) {
286 $data = (object)$data;
289 $data->contextid = context_course::instance($this->get_courseid())->id;
291 $gradeletter = (array)$data;
292 unset($gradeletter['id']);
293 if (!$DB->record_exists('grade_letters', $gradeletter)) {
294 $newitemid = $DB->insert_record('grade_letters', $data);
296 $newitemid = $data->id;
299 $this->set_mapping('grade_letter', $oldid, $newitemid);
301 protected function process_grade_setting($data) {
304 $data = (object)$data;
307 $data->courseid = $this->get_courseid();
309 if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
310 $newitemid = $DB->insert_record('grade_settings', $data);
312 $newitemid = $data->id;
315 $this->set_mapping('grade_setting', $oldid, $newitemid);
319 * put all activity grade items in the correct grade category and mark all for recalculation
321 protected function after_execute() {
325 'backupid' => $this->get_restoreid(),
326 'itemname' => 'grade_item'//,
327 //'itemid' => $itemid
329 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
331 // We need this for calculation magic later on.
335 foreach($rs as $grade_item_backup) {
337 // Store the oldid with the new id.
338 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
340 $updateobj = new stdclass();
341 $updateobj->id = $grade_item_backup->newitemid;
343 //if this is an activity grade item that needs to be put back in its correct category
344 if (!empty($grade_item_backup->parentitemid)) {
345 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
346 if (!is_null($oldcategoryid)) {
347 $updateobj->categoryid = $oldcategoryid;
348 $DB->update_record('grade_items', $updateobj);
351 //mark course and category items as needing to be recalculated
352 $updateobj->needsupdate=1;
353 $DB->update_record('grade_items', $updateobj);
359 // We need to update the calculations for calculated grade items that may reference old
360 // grade item ids using ##gi\d+##.
361 // $mappings can be empty, use 0 if so (won't match ever)
362 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
363 $sql = "SELECT gi.id, gi.calculation
364 FROM {grade_items} gi
365 WHERE gi.id {$sql} AND
366 calculation IS NOT NULL";
367 $rs = $DB->get_recordset_sql($sql, $params);
368 foreach ($rs as $gradeitem) {
369 // Collect all of the used grade item id references
370 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
371 // This calculation doesn't reference any other grade items... EASY!
374 // For this next bit we are going to do the replacement of id's in two steps:
375 // 1. We will replace all old id references with a special mapping reference.
376 // 2. We will replace all mapping references with id's
377 // Why do we do this?
378 // Because there potentially there will be an overlap of ids within the query and we
379 // we substitute the wrong id.. safest way around this is the two step system
380 $calculationmap = array();
382 foreach ($matches[1] as $match) {
383 // Check that the old id is known to us, if not it was broken to begin with and will
384 // continue to be broken.
385 if (!array_key_exists($match, $mappings)) {
388 // Our special mapping key
389 $mapping = '##MAPPING'.$mapcount.'##';
390 // The old id that exists within the calculation now
391 $oldid = '##gi'.$match.'##';
392 // The new id that we want to replace the old one with.
393 $newid = '##gi'.$mappings[$match].'##';
394 // Replace in the special mapping key
395 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
396 // And record the mapping
397 $calculationmap[$mapping] = $newid;
400 // Iterate all special mappings for this calculation and replace in the new id's
401 foreach ($calculationmap as $mapping => $newid) {
402 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
404 // Update the calculation now that its being remapped
405 $DB->update_record('grade_items', $gradeitem);
409 // Need to correct the grade category path and parent
411 'courseid' => $this->get_courseid()
414 $rs = $DB->get_recordset('grade_categories', $conditions);
415 // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
416 foreach ($rs as $gc) {
417 if (!empty($gc->parent)) {
418 $grade_category = new stdClass();
419 $grade_category->id = $gc->id;
420 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
421 $DB->update_record('grade_categories', $grade_category);
426 // Now we can rebuild all the paths
427 $rs = $DB->get_recordset('grade_categories', $conditions);
428 foreach ($rs as $gc) {
429 $grade_category = new stdClass();
430 $grade_category->id = $gc->id;
431 $grade_category->path = grade_category::build_path($gc);
432 $grade_category->depth = substr_count($grade_category->path, '/') - 1;
433 $DB->update_record('grade_categories', $grade_category);
437 // Restore marks items as needing update. Update everything now.
438 grade_regrade_final_grades($this->get_courseid());
443 * decode all the interlinks present in restored content
444 * relying 100% in the restore_decode_processor that handles
445 * both the contents to modify and the rules to be applied
447 class restore_decode_interlinks extends restore_execution_step {
449 protected function define_execution() {
450 // Get the decoder (from the plan)
451 $decoder = $this->task->get_decoder();
452 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
453 // And launch it, everything will be processed
459 * first, ensure that we have no gaps in section numbers
460 * and then, rebuid the course cache
462 class restore_rebuild_course_cache extends restore_execution_step {
464 protected function define_execution() {
467 // Although there is some sort of auto-recovery of missing sections
468 // present in course/formats... here we check that all the sections
469 // from 0 to MAX(section->section) exist, creating them if necessary
470 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
471 // Iterate over all sections
472 for ($i = 0; $i <= $maxsection; $i++) {
473 // If the section $i doesn't exist, create it
474 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
476 'course' => $this->get_courseid(),
478 $DB->insert_record('course_sections', $sectionrec); // missing section created
482 // Rebuild cache now that all sections are in place
483 rebuild_course_cache($this->get_courseid());
484 cache_helper::purge_by_event('changesincourse');
485 cache_helper::purge_by_event('changesincoursecat');
490 * Review all the tasks having one after_restore method
491 * executing it to perform some final adjustments of information
492 * not available when the task was executed.
494 class restore_execute_after_restore extends restore_execution_step {
496 protected function define_execution() {
498 // Simply call to the execute_after_restore() method of the task
499 // that always is the restore_final_task
500 $this->task->launch_execute_after_restore();
506 * Review all the (pending) block positions in backup_ids, matching by
507 * contextid, creating positions as needed. This is executed by the
508 * final task, once all the contexts have been created
510 class restore_review_pending_block_positions extends restore_execution_step {
512 protected function define_execution() {
515 // Get all the block_position objects pending to match
516 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
517 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
518 // Process block positions, creating them or accumulating for final step
519 foreach($rs as $posrec) {
520 // Get the complete position object out of the info field.
521 $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
522 // If position is for one already mapped (known) contextid
523 // process it now, creating the position, else nothing to
524 // do, position finally discarded
525 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
526 $position->contextid = $newctx->newitemid;
527 // Create the block position
528 $DB->insert_record('block_positions', $position);
536 * Process all the saved module availability records in backup_ids, matching
537 * course modules and grade item id once all them have been already restored.
538 * only if all matchings are satisfied the availability condition will be created.
539 * At the same time, it is required for the site to have that functionality enabled.
541 class restore_process_course_modules_availability extends restore_execution_step {
543 protected function define_execution() {
546 // Site hasn't availability enabled
547 if (empty($CFG->enableavailability)) {
551 // Get all the module_availability objects to process
552 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
553 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
554 // Process availabilities, creating them if everything matches ok
555 foreach($rs as $availrec) {
556 $allmatchesok = true;
557 // Get the complete availabilityobject
558 $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
559 // Map the sourcecmid if needed and possible
560 if (!empty($availability->sourcecmid)) {
561 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
563 $availability->sourcecmid = $newcm->newitemid;
565 $allmatchesok = false; // Failed matching, we won't create this availability rule
568 // Map the gradeitemid if needed and possible
569 if (!empty($availability->gradeitemid)) {
570 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
572 $availability->gradeitemid = $newgi->newitemid;
574 $allmatchesok = false; // Failed matching, we won't create this availability rule
577 if ($allmatchesok) { // Everything ok, create the availability rule
578 $DB->insert_record('course_modules_availability', $availability);
587 * Execution step that, *conditionally* (if there isn't preloaded information)
588 * will load the inforef files for all the included course/section/activity tasks
589 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
591 class restore_load_included_inforef_records extends restore_execution_step {
593 protected function define_execution() {
595 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
599 // Get all the included tasks
600 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
601 $progress = $this->task->get_progress();
602 $progress->start_progress($this->get_name(), count($tasks));
603 foreach ($tasks as $task) {
604 // Load the inforef.xml file if exists
605 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
606 if (file_exists($inforefpath)) {
607 // Load each inforef file to temp_ids.
608 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
611 $progress->end_progress();
616 * Execution step that will load all the needed files into backup_files_temp
617 * - info: contains the whole original object (times, names...)
618 * (all them being original ids as loaded from xml)
620 class restore_load_included_files extends restore_structure_step {
622 protected function define_structure() {
624 $file = new restore_path_element('file', '/files/file');
630 * Process one <file> element from files.xml
632 * @param array $data the element data
634 public function process_file($data) {
636 $data = (object)$data; // handy
638 // load it if needed:
639 // - it it is one of the annotated inforef files (course/section/activity/block)
640 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
641 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
642 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
643 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
644 $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
645 $data->component == 'grouping' || $data->component == 'grade' ||
646 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
647 if ($isfileref || $iscomponent) {
648 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
654 * Execution step that, *conditionally* (if there isn't preloaded information),
655 * will load all the needed roles to backup_temp_ids. They will be stored with
656 * "role" itemname. Also it will perform one automatic mapping to roles existing
657 * in the target site, based in permissions of the user performing the restore,
658 * archetypes and other bits. At the end, each original role will have its associated
659 * target role or 0 if it's going to be skipped. Note we wrap everything over one
660 * restore_dbops method, as far as the same stuff is going to be also executed
661 * by restore prechecks
663 class restore_load_and_map_roles extends restore_execution_step {
665 protected function define_execution() {
666 if ($this->task->get_preloaded_information()) { // if info is already preloaded
670 $file = $this->get_basepath() . '/roles.xml';
671 // Load needed toles to temp_ids
672 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
674 // Process roles, mapping/skipping. Any error throws exception
675 // Note we pass controller's info because it can contain role mapping information
676 // about manual mappings performed by UI
677 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);
682 * Execution step that, *conditionally* (if there isn't preloaded information
683 * and users have been selected in settings, will load all the needed users
684 * to backup_temp_ids. They will be stored with "user" itemname and with
685 * their original contextid as paremitemid
687 class restore_load_included_users extends restore_execution_step {
689 protected function define_execution() {
691 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
694 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
697 $file = $this->get_basepath() . '/users.xml';
698 // Load needed users to temp_ids.
699 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
704 * Execution step that, *conditionally* (if there isn't preloaded information
705 * and users have been selected in settings, will process all the needed users
706 * in order to decide and perform any action with them (create / map / error)
707 * Note: Any error will cause exception, as far as this is the same processing
708 * than the one into restore prechecks (that should have stopped process earlier)
710 class restore_process_included_users extends restore_execution_step {
712 protected function define_execution() {
714 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
717 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
720 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
721 $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
726 * Execution step that will create all the needed users as calculated
727 * by @restore_process_included_users (those having newiteind = 0)
729 class restore_create_included_users extends restore_execution_step {
731 protected function define_execution() {
733 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
734 $this->task->get_userid(), $this->task->get_progress());
739 * Structure step that will create all the needed groups and groupings
740 * by loading them from the groups.xml file performing the required matches.
741 * Note group members only will be added if restoring user info
743 class restore_groups_structure_step extends restore_structure_step {
745 protected function define_structure() {
747 $paths = array(); // Add paths here
749 $paths[] = new restore_path_element('group', '/groups/group');
750 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
751 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
756 // Processing functions go here
757 public function process_group($data) {
760 $data = (object)$data; // handy
761 $data->courseid = $this->get_courseid();
763 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
764 // another a group in the same course
765 $context = context_course::instance($data->courseid);
766 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
767 if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
768 unset($data->idnumber);
771 unset($data->idnumber);
774 $oldid = $data->id; // need this saved for later
776 $restorefiles = false; // Only if we end creating the group
778 // Search if the group already exists (by name & description) in the target course
779 $description_clause = '';
780 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
781 if (!empty($data->description)) {
782 $description_clause = ' AND ' .
783 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
784 $params['description'] = $data->description;
786 if (!$groupdb = $DB->get_record_sql("SELECT *
788 WHERE courseid = :courseid
789 AND name = :grname $description_clause", $params)) {
790 // group doesn't exist, create
791 $newitemid = $DB->insert_record('groups', $data);
792 $restorefiles = true; // We'll restore the files
794 // group exists, use it
795 $newitemid = $groupdb->id;
797 // Save the id mapping
798 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
799 // Invalidate the course group data cache just in case.
800 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
803 public function process_grouping($data) {
806 $data = (object)$data; // handy
807 $data->courseid = $this->get_courseid();
809 // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
810 // another a grouping in the same course
811 $context = context_course::instance($data->courseid);
812 if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
813 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
814 unset($data->idnumber);
817 unset($data->idnumber);
820 $oldid = $data->id; // need this saved for later
821 $restorefiles = false; // Only if we end creating the grouping
823 // Search if the grouping already exists (by name & description) in the target course
824 $description_clause = '';
825 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
826 if (!empty($data->description)) {
827 $description_clause = ' AND ' .
828 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
829 $params['description'] = $data->description;
831 if (!$groupingdb = $DB->get_record_sql("SELECT *
833 WHERE courseid = :courseid
834 AND name = :grname $description_clause", $params)) {
835 // grouping doesn't exist, create
836 $newitemid = $DB->insert_record('groupings', $data);
837 $restorefiles = true; // We'll restore the files
839 // grouping exists, use it
840 $newitemid = $groupingdb->id;
842 // Save the id mapping
843 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
844 // Invalidate the course group data cache just in case.
845 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
848 public function process_grouping_group($data) {
851 require_once($CFG->dirroot.'/group/lib.php');
853 $data = (object)$data;
854 groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
857 protected function after_execute() {
858 // Add group related files, matching with "group" mappings
859 $this->add_related_files('group', 'icon', 'group');
860 $this->add_related_files('group', 'description', 'group');
861 // Add grouping related files, matching with "grouping" mappings
862 $this->add_related_files('grouping', 'description', 'grouping');
863 // Invalidate the course group data.
864 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
870 * Structure step that will create all the needed group memberships
871 * by loading them from the groups.xml file performing the required matches.
873 class restore_groups_members_structure_step extends restore_structure_step {
875 protected $plugins = null;
877 protected function define_structure() {
879 $paths = array(); // Add paths here
881 if ($this->get_setting_value('users')) {
882 $paths[] = new restore_path_element('group', '/groups/group');
883 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
889 public function process_group($data) {
890 $data = (object)$data; // handy
893 // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
894 // Let's fake internal state to make $this->get_new_parentid('group') work.
896 $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
899 public function process_member($data) {
901 require_once("$CFG->dirroot/group/lib.php");
903 // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
905 $data = (object)$data; // handy
907 // get parent group->id
908 $data->groupid = $this->get_new_parentid('group');
910 // map user newitemid and insert if not member already
911 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
912 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
913 // Check the component, if any, exists.
914 if (empty($data->component)) {
915 groups_add_member($data->groupid, $data->userid);
917 } else if ((strpos($data->component, 'enrol_') === 0)) {
918 // Deal with enrolment groups - ignore the component and just find out the instance via new id,
919 // it is possible that enrolment was restored using different plugin type.
920 if (!isset($this->plugins)) {
921 $this->plugins = enrol_get_plugins(true);
923 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
924 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
925 if (isset($this->plugins[$instance->enrol])) {
926 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
932 $dir = core_component::get_component_directory($data->component);
933 if ($dir and is_dir($dir)) {
934 if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
938 // Bad luck, plugin could not restore the data, let's add normal membership.
939 groups_add_member($data->groupid, $data->userid);
940 $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
941 $this->log($message, backup::LOG_WARNING);
949 * Structure step that will create all the needed scales
950 * by loading them from the scales.xml
952 class restore_scales_structure_step extends restore_structure_step {
954 protected function define_structure() {
956 $paths = array(); // Add paths here
957 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
961 protected function process_scale($data) {
964 $data = (object)$data;
966 $restorefiles = false; // Only if we end creating the group
968 $oldid = $data->id; // need this saved for later
970 // Look for scale (by 'scale' both in standard (course=0) and current course
971 // with priority to standard scales (ORDER clause)
972 // scale is not course unique, use get_record_sql to suppress warning
973 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
974 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
975 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
976 if (!$scadb = $DB->get_record_sql("SELECT *
978 WHERE courseid IN (0, :courseid)
979 AND $compare_scale_clause
980 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
981 // Remap the user if possible, defaut to user performing the restore if not
982 $userid = $this->get_mappingid('user', $data->userid);
983 $data->userid = $userid ? $userid : $this->task->get_userid();
984 // Remap the course if course scale
985 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
986 // If global scale (course=0), check the user has perms to create it
987 // falling to course scale if not
988 $systemctx = context_system::instance();
989 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
990 $data->courseid = $this->get_courseid();
992 // scale doesn't exist, create
993 $newitemid = $DB->insert_record('scale', $data);
994 $restorefiles = true; // We'll restore the files
996 // scale exists, use it
997 $newitemid = $scadb->id;
999 // Save the id mapping (with files support at system context)
1000 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1003 protected function after_execute() {
1004 // Add scales related files, matching with "scale" mappings
1005 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1011 * Structure step that will create all the needed outocomes
1012 * by loading them from the outcomes.xml
1014 class restore_outcomes_structure_step extends restore_structure_step {
1016 protected function define_structure() {
1018 $paths = array(); // Add paths here
1019 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1023 protected function process_outcome($data) {
1026 $data = (object)$data;
1028 $restorefiles = false; // Only if we end creating the group
1030 $oldid = $data->id; // need this saved for later
1032 // Look for outcome (by shortname both in standard (courseid=null) and current course
1033 // with priority to standard outcomes (ORDER clause)
1034 // outcome is not course unique, use get_record_sql to suppress warning
1035 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1036 if (!$outdb = $DB->get_record_sql('SELECT *
1037 FROM {grade_outcomes}
1038 WHERE shortname = :shortname
1039 AND (courseid = :courseid OR courseid IS NULL)
1040 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1042 $userid = $this->get_mappingid('user', $data->usermodified);
1043 $data->usermodified = $userid ? $userid : $this->task->get_userid();
1045 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1046 // Remap the course if course outcome
1047 $data->courseid = $data->courseid ? $this->get_courseid() : null;
1048 // If global outcome (course=null), check the user has perms to create it
1049 // falling to course outcome if not
1050 $systemctx = context_system::instance();
1051 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1052 $data->courseid = $this->get_courseid();
1054 // outcome doesn't exist, create
1055 $newitemid = $DB->insert_record('grade_outcomes', $data);
1056 $restorefiles = true; // We'll restore the files
1058 // scale exists, use it
1059 $newitemid = $outdb->id;
1061 // Set the corresponding grade_outcomes_courses record
1062 $outcourserec = new stdclass();
1063 $outcourserec->courseid = $this->get_courseid();
1064 $outcourserec->outcomeid = $newitemid;
1065 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1066 $DB->insert_record('grade_outcomes_courses', $outcourserec);
1068 // Save the id mapping (with files support at system context)
1069 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1072 protected function after_execute() {
1073 // Add outcomes related files, matching with "outcome" mappings
1074 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1079 * Execution step that, *conditionally* (if there isn't preloaded information
1080 * will load all the question categories and questions (header info only)
1081 * to backup_temp_ids. They will be stored with "question_category" and
1082 * "question" itemnames and with their original contextid and question category
1083 * id as paremitemids
1085 class restore_load_categories_and_questions extends restore_execution_step {
1087 protected function define_execution() {
1089 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1092 $file = $this->get_basepath() . '/questions.xml';
1093 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1098 * Execution step that, *conditionally* (if there isn't preloaded information)
1099 * will process all the needed categories and questions
1100 * in order to decide and perform any action with them (create / map / error)
1101 * Note: Any error will cause exception, as far as this is the same processing
1102 * than the one into restore prechecks (that should have stopped process earlier)
1104 class restore_process_categories_and_questions extends restore_execution_step {
1106 protected function define_execution() {
1108 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1111 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1116 * Structure step that will read the section.xml creating/updating sections
1117 * as needed, rebuilding course cache and other friends
1119 class restore_section_structure_step extends restore_structure_step {
1121 protected function define_structure() {
1126 $section = new restore_path_element('section', '/section');
1127 $paths[] = $section;
1128 if ($CFG->enableavailability) {
1129 $paths[] = new restore_path_element('availability', '/section/availability');
1130 $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1132 $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1134 // Apply for 'format' plugins optional paths at section level
1135 $this->add_plugin_structure('format', $section);
1137 // Apply for 'local' plugins optional paths at section level
1138 $this->add_plugin_structure('local', $section);
1143 public function process_section($data) {
1145 $data = (object)$data;
1146 $oldid = $data->id; // We'll need this later
1148 $restorefiles = false;
1150 // Look for the section
1151 $section = new stdclass();
1152 $section->course = $this->get_courseid();
1153 $section->section = $data->number;
1154 // Section doesn't exist, create it with all the info from backup
1155 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1156 $section->name = $data->name;
1157 $section->summary = $data->summary;
1158 $section->summaryformat = $data->summaryformat;
1159 $section->sequence = '';
1160 $section->visible = $data->visible;
1161 if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1162 $section->availablefrom = 0;
1163 $section->availableuntil = 0;
1164 $section->showavailability = 0;
1166 $section->availablefrom = isset($data->availablefrom) ? $this->apply_date_offset($data->availablefrom) : 0;
1167 $section->availableuntil = isset($data->availableuntil) ? $this->apply_date_offset($data->availableuntil) : 0;
1168 $section->showavailability = isset($data->showavailability) ? $data->showavailability : 0;
1170 if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
1171 $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
1173 $newitemid = $DB->insert_record('course_sections', $section);
1174 $restorefiles = true;
1176 // Section exists, update non-empty information
1178 $section->id = $secrec->id;
1179 if ((string)$secrec->name === '') {
1180 $section->name = $data->name;
1182 if (empty($secrec->summary)) {
1183 $section->summary = $data->summary;
1184 $section->summaryformat = $data->summaryformat;
1185 $restorefiles = true;
1187 if (empty($secrec->groupingid)) {
1188 if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
1189 $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
1193 // Don't update available from, available until, or show availability
1194 // (I didn't see a useful way to define whether existing or new one should
1195 // take precedence).
1197 $DB->update_record('course_sections', $section);
1198 $newitemid = $secrec->id;
1201 // Annotate the section mapping, with restorefiles option if needed
1202 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1204 // set the new course_section id in the task
1205 $this->task->set_sectionid($newitemid);
1208 // Commented out. We never modify course->numsections as far as that is used
1209 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1210 // Note: We keep the code here, to know about and because of the possibility of making this
1211 // optional based on some setting/attribute in the future
1212 // If needed, adjust course->numsections
1213 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1214 // if ($numsections < $section->section) {
1215 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1220 public function process_availability($data) {
1222 $data = (object)$data;
1224 $data->coursesectionid = $this->task->get_sectionid();
1226 // NOTE: Other values in $data need updating, but these (cm,
1227 // grade items) have not yet been restored, so are done later.
1229 $newid = $DB->insert_record('course_sections_availability', $data);
1231 // We do not need to map between old and new id but storing a mapping
1232 // means it gets added to the backup_ids table to record which ones
1233 // need updating. The mapping is stored with $newid => $newid for
1235 $this->set_mapping('course_sections_availability', $newid, $newid);
1238 public function process_availability_field($data) {
1240 $data = (object)$data;
1241 // Mark it is as passed by default
1243 $customfieldid = null;
1245 // If a customfield has been used in order to pass we must be able to match an existing
1246 // customfield by name (data->customfield) and type (data->customfieldtype)
1247 if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1248 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1249 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1251 } else if (!is_null($data->customfield)) {
1252 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1253 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1254 $passed = ($customfieldid !== false);
1258 // Create the object to insert into the database
1259 $availfield = new stdClass();
1260 $availfield->coursesectionid = $this->task->get_sectionid();
1261 $availfield->userfield = $data->userfield;
1262 $availfield->customfieldid = $customfieldid;
1263 $availfield->operator = $data->operator;
1264 $availfield->value = $data->value;
1265 $DB->insert_record('course_sections_avail_fields', $availfield);
1269 public function process_course_format_options($data) {
1271 $data = (object)$data;
1274 $data->sectionid = $this->task->get_sectionid();
1275 $data->courseid = $this->get_courseid();
1276 $newid = $DB->insert_record('course_format_options', $data);
1277 $this->set_mapping('course_format_options', $oldid, $newid);
1280 protected function after_execute() {
1281 // Add section related files, with 'course_section' itemid to match
1282 $this->add_related_files('course', 'section', 'course_section');
1285 public function after_restore() {
1288 $sectionid = $this->get_task()->get_sectionid();
1290 // Get data object for current section availability (if any).
1291 $records = $DB->get_records('course_sections_availability',
1292 array('coursesectionid' => $sectionid), 'id, sourcecmid, gradeitemid');
1294 // If it exists, update mappings.
1295 foreach ($records as $data) {
1296 // Only update mappings for entries which are created by this restore.
1297 // Otherwise, when you restore to an existing course, it will mess up
1298 // existing section availability entries.
1299 if (!$this->get_mappingid('course_sections_availability', $data->id, false)) {
1303 // Update source cmid / grade id to new value.
1304 $data->sourcecmid = $this->get_mappingid('course_module', $data->sourcecmid);
1305 if (!$data->sourcecmid) {
1306 $data->sourcecmid = null;
1308 $data->gradeitemid = $this->get_mappingid('grade_item', $data->gradeitemid);
1309 if (!$data->gradeitemid) {
1310 $data->gradeitemid = null;
1313 // Delete the record if the condition wasn't found, otherwise update it.
1314 if ($data->sourcecmid === null && $data->gradeitemid === null) {
1315 $DB->delete_records('course_sections_availability', array('id' => $data->id));
1317 $DB->update_record('course_sections_availability', $data);
1325 * Structure step that will read the course.xml file, loading it and performing
1326 * various actions depending of the site/restore settings. Note that target
1327 * course always exist before arriving here so this step will be updating
1328 * the course record (never inserting)
1330 class restore_course_structure_step extends restore_structure_step {
1332 * @var bool this gets set to true by {@link process_course()} if we are
1333 * restoring an old coures that used the legacy 'module security' feature.
1334 * If so, we have to do more work in {@link after_execute()}.
1336 protected $legacyrestrictmodules = false;
1339 * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1340 * array with array keys the module names ('forum', 'quiz', etc.). These are
1341 * the modules that are allowed according to the data in the backup file.
1342 * In {@link after_execute()} we then have to prevent adding of all the other
1343 * types of activity.
1345 protected $legacyallowedmodules = array();
1347 protected function define_structure() {
1349 $course = new restore_path_element('course', '/course');
1350 $category = new restore_path_element('category', '/course/category');
1351 $tag = new restore_path_element('tag', '/course/tags/tag');
1352 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1354 // Apply for 'format' plugins optional paths at course level
1355 $this->add_plugin_structure('format', $course);
1357 // Apply for 'theme' plugins optional paths at course level
1358 $this->add_plugin_structure('theme', $course);
1360 // Apply for 'report' plugins optional paths at course level
1361 $this->add_plugin_structure('report', $course);
1363 // Apply for 'course report' plugins optional paths at course level
1364 $this->add_plugin_structure('coursereport', $course);
1366 // Apply for plagiarism plugins optional paths at course level
1367 $this->add_plugin_structure('plagiarism', $course);
1369 // Apply for local plugins optional paths at course level
1370 $this->add_plugin_structure('local', $course);
1372 return array($course, $category, $tag, $allowed_module);
1376 * Processing functions go here
1378 * @global moodledatabase $DB
1379 * @param stdClass $data
1381 public function process_course($data) {
1384 $data = (object)$data;
1386 $fullname = $this->get_setting_value('course_fullname');
1387 $shortname = $this->get_setting_value('course_shortname');
1388 $startdate = $this->get_setting_value('course_startdate');
1390 // Calculate final course names, to avoid dupes
1391 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1393 // Need to change some fields before updating the course record
1394 $data->id = $this->get_courseid();
1395 $data->fullname = $fullname;
1396 $data->shortname= $shortname;
1398 $context = context::instance_by_id($this->task->get_contextid());
1399 if (has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1400 $data->idnumber = '';
1402 unset($data->idnumber);
1405 // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1406 // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1407 if (empty($data->hiddensections)) {
1408 $data->hiddensections = 0;
1411 // Set legacyrestrictmodules to true if the course was resticting modules. If so
1412 // then we will need to process restricted modules after execution.
1413 $this->legacyrestrictmodules = !empty($data->restrictmodules);
1415 $data->startdate= $this->apply_date_offset($data->startdate);
1416 if ($data->defaultgroupingid) {
1417 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1419 if (empty($CFG->enablecompletion)) {
1420 $data->enablecompletion = 0;
1421 $data->completionstartonenrol = 0;
1422 $data->completionnotify = 0;
1424 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1425 if (!array_key_exists($data->lang, $languages)) {
1429 $themes = get_list_of_themes(); // Get themes for quick search later
1430 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1434 // Check if this is an old SCORM course format.
1435 if ($data->format == 'scorm') {
1436 $data->format = 'singleactivity';
1437 $data->activitytype = 'scorm';
1440 // Course record ready, update it
1441 $DB->update_record('course', $data);
1443 course_get_format($data)->update_course_format_options($data);
1445 // Role name aliases
1446 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1449 public function process_category($data) {
1450 // Nothing to do with the category. UI sets it before restore starts
1453 public function process_tag($data) {
1456 $data = (object)$data;
1458 if (!empty($CFG->usetags)) { // if enabled in server
1459 // TODO: This is highly inneficient. Each time we add one tag
1460 // we fetch all the existing because tag_set() deletes them
1461 // so everything must be reinserted on each call
1463 $existingtags = tag_get_tags('course', $this->get_courseid());
1464 // Re-add all the existitng tags
1465 foreach ($existingtags as $existingtag) {
1466 $tags[] = $existingtag->rawname;
1468 // Add the one being restored
1469 $tags[] = $data->rawname;
1470 // Send all the tags back to the course
1471 tag_set('course', $this->get_courseid(), $tags);
1475 public function process_allowed_module($data) {
1476 $data = (object)$data;
1478 // Backwards compatiblity support for the data that used to be in the
1479 // course_allowed_modules table.
1480 if ($this->legacyrestrictmodules) {
1481 $this->legacyallowedmodules[$data->modulename] = 1;
1485 protected function after_execute() {
1488 // Add course related files, without itemid to match
1489 $this->add_related_files('course', 'summary', null);
1490 $this->add_related_files('course', 'overviewfiles', null);
1492 // Deal with legacy allowed modules.
1493 if ($this->legacyrestrictmodules) {
1494 $context = context_course::instance($this->get_courseid());
1496 list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1497 list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1498 foreach ($managerroleids as $roleid) {
1499 unset($roleids[$roleid]);
1502 foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1503 if (isset($this->legacyallowedmodules[$modname])) {
1504 // Module is allowed, no worries.
1508 $capability = 'mod/' . $modname . ':addinstance';
1509 foreach ($roleids as $roleid) {
1510 assign_capability($capability, CAP_PREVENT, $roleid, $context);
1518 * Execution step that will migrate legacy files if present.
1520 class restore_course_legacy_files_step extends restore_execution_step {
1521 public function define_execution() {
1524 // Do a check for legacy files and skip if there are none.
1525 $sql = 'SELECT count(*)
1526 FROM {backup_files_temp}
1531 $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
1533 if ($DB->count_records_sql($sql, $params)) {
1534 $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
1535 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
1536 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
1542 * Structure step that will read the roles.xml file (at course/activity/block levels)
1543 * containing all the role_assignments and overrides for that context. If corresponding to
1544 * one mapped role, they will be applied to target context. Will observe the role_assignments
1545 * setting to decide if ras are restored.
1547 * Note: this needs to be executed after all users are enrolled.
1549 class restore_ras_and_caps_structure_step extends restore_structure_step {
1550 protected $plugins = null;
1552 protected function define_structure() {
1556 // Observe the role_assignments setting
1557 if ($this->get_setting_value('role_assignments')) {
1558 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1560 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1568 * This has to be called after enrolments processing.
1570 * @param mixed $data
1573 public function process_assignment($data) {
1576 $data = (object)$data;
1578 // Check roleid, userid are one of the mapped ones
1579 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1582 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1585 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1586 // Only assign roles to not deleted users
1589 if (!$contextid = $this->task->get_contextid()) {
1593 if (empty($data->component)) {
1594 // assign standard manual roles
1595 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1596 role_assign($newroleid, $newuserid, $contextid);
1598 } else if ((strpos($data->component, 'enrol_') === 0)) {
1599 // Deal with enrolment roles - ignore the component and just find out the instance via new id,
1600 // it is possible that enrolment was restored using different plugin type.
1601 if (!isset($this->plugins)) {
1602 $this->plugins = enrol_get_plugins(true);
1604 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1605 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1606 if (isset($this->plugins[$instance->enrol])) {
1607 $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
1613 $data->roleid = $newroleid;
1614 $data->userid = $newuserid;
1615 $data->contextid = $contextid;
1616 $dir = core_component::get_component_directory($data->component);
1617 if ($dir and is_dir($dir)) {
1618 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
1622 // Bad luck, plugin could not restore the data, let's add normal membership.
1623 role_assign($data->roleid, $data->userid, $data->contextid);
1624 $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
1625 $this->log($message, backup::LOG_WARNING);
1629 public function process_override($data) {
1630 $data = (object)$data;
1632 // Check roleid is one of the mapped ones
1633 $newroleid = $this->get_mappingid('role', $data->roleid);
1634 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1635 if ($newroleid && $this->task->get_contextid()) {
1636 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1637 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1638 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1644 * If no instances yet add default enrol methods the same way as when creating new course in UI.
1646 class restore_default_enrolments_step extends restore_execution_step {
1647 public function define_execution() {
1650 $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
1652 if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
1653 // Something already added instances, do not add default instances.
1654 $plugins = enrol_get_plugins(true);
1655 foreach ($plugins as $plugin) {
1656 $plugin->restore_sync_course($course);
1660 // Looks like a newly created course.
1661 enrol_course_updated(true, $course, null);
1667 * This structure steps restores the enrol plugins and their underlying
1668 * enrolments, performing all the mappings and/or movements required
1670 class restore_enrolments_structure_step extends restore_structure_step {
1671 protected $enrolsynced = false;
1672 protected $plugins = null;
1673 protected $originalstatus = array();
1676 * Conditionally decide if this step should be executed.
1678 * This function checks the following parameter:
1680 * 1. the course/enrolments.xml file exists
1682 * @return bool true is safe to execute, false otherwise
1684 protected function execute_condition() {
1686 // Check it is included in the backup
1687 $fullpath = $this->task->get_taskbasepath();
1688 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1689 if (!file_exists($fullpath)) {
1690 // Not found, can't restore enrolments info
1697 protected function define_structure() {
1701 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1702 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1708 * Create enrolment instances.
1710 * This has to be called after creation of roles
1711 * and before adding of role assignments.
1713 * @param mixed $data
1716 public function process_enrol($data) {
1719 $data = (object)$data;
1720 $oldid = $data->id; // We'll need this later.
1723 $this->originalstatus[$oldid] = $data->status;
1725 if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
1726 $this->set_mapping('enrol', $oldid, 0);
1730 if (!isset($this->plugins)) {
1731 $this->plugins = enrol_get_plugins(true);
1734 if (!$this->enrolsynced) {
1735 // Make sure that all plugin may create instances and enrolments automatically
1736 // before the first instance restore - this is suitable especially for plugins
1737 // that synchronise data automatically using course->idnumber or by course categories.
1738 foreach ($this->plugins as $plugin) {
1739 $plugin->restore_sync_course($courserec);
1741 $this->enrolsynced = true;
1744 // Map standard fields - plugin has to process custom fields manually.
1745 $data->roleid = $this->get_mappingid('role', $data->roleid);
1746 $data->courseid = $courserec->id;
1748 if ($this->get_setting_value('enrol_migratetomanual')) {
1749 unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
1750 if (!enrol_is_enabled('manual')) {
1751 $this->set_mapping('enrol', $oldid, 0);
1754 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
1755 $instance = reset($instances);
1756 $this->set_mapping('enrol', $oldid, $instance->id);
1758 if ($data->enrol === 'manual') {
1759 $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
1761 $instanceid = $this->plugins['manual']->add_default_instance($courserec);
1763 $this->set_mapping('enrol', $oldid, $instanceid);
1767 if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
1768 $this->set_mapping('enrol', $oldid, 0);
1769 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments";
1770 $this->log($message, backup::LOG_WARNING);
1773 if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
1774 // Let's keep the sortorder in old backups.
1776 // Prevent problems with colliding sortorders in old backups,
1777 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
1778 unset($data->sortorder);
1780 // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
1781 $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
1786 * Create user enrolments.
1788 * This has to be called after creation of enrolment instances
1789 * and before adding of role assignments.
1791 * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
1793 * @param mixed $data
1796 public function process_enrolment($data) {
1799 if (!isset($this->plugins)) {
1800 $this->plugins = enrol_get_plugins(true);
1803 $data = (object)$data;
1805 // Process only if parent instance have been mapped.
1806 if ($enrolid = $this->get_new_parentid('enrol')) {
1807 $oldinstancestatus = ENROL_INSTANCE_ENABLED;
1808 $oldenrolid = $this->get_old_parentid('enrol');
1809 if (isset($this->originalstatus[$oldenrolid])) {
1810 $oldinstancestatus = $this->originalstatus[$oldenrolid];
1812 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1813 // And only if user is a mapped one.
1814 if ($userid = $this->get_mappingid('user', $data->userid)) {
1815 if (isset($this->plugins[$instance->enrol])) {
1816 $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
1826 * Make sure the user restoring the course can actually access it.
1828 class restore_fix_restorer_access_step extends restore_execution_step {
1829 protected function define_execution() {
1832 if (!$userid = $this->task->get_userid()) {
1836 if (empty($CFG->restorernewroleid)) {
1837 // Bad luck, no fallback role for restorers specified
1841 $courseid = $this->get_courseid();
1842 $context = context_course::instance($courseid);
1844 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1845 // Current user may access the course (admin, category manager or restored teacher enrolment usually)
1849 // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
1850 role_assign($CFG->restorernewroleid, $userid, $context);
1852 if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1853 // Extra role is enough, yay!
1857 // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
1858 // hopefully admin selected suitable $CFG->restorernewroleid ...
1859 if (!enrol_is_enabled('manual')) {
1862 if (!$enrol = enrol_get_plugin('manual')) {
1865 if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
1866 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
1867 $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
1868 $enrol->add_instance($course, $fields);
1871 enrol_try_internal_enrol($courseid, $userid);
1877 * This structure steps restores the filters and their configs
1879 class restore_filters_structure_step extends restore_structure_step {
1881 protected function define_structure() {
1885 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1886 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1891 public function process_active($data) {
1893 $data = (object)$data;
1895 if (strpos($data->filter, 'filter/') === 0) {
1896 $data->filter = substr($data->filter, 7);
1898 } else if (strpos($data->filter, '/') !== false) {
1899 // Unsupported old filter.
1903 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1906 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1909 public function process_config($data) {
1911 $data = (object)$data;
1913 if (strpos($data->filter, 'filter/') === 0) {
1914 $data->filter = substr($data->filter, 7);
1916 } else if (strpos($data->filter, '/') !== false) {
1917 // Unsupported old filter.
1921 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1924 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1930 * This structure steps restores the comments
1931 * Note: Cannot use the comments API because defaults to USER->id.
1932 * That should change allowing to pass $userid
1934 class restore_comments_structure_step extends restore_structure_step {
1936 protected function define_structure() {
1940 $paths[] = new restore_path_element('comment', '/comments/comment');
1945 public function process_comment($data) {
1948 $data = (object)$data;
1950 // First of all, if the comment has some itemid, ask to the task what to map
1952 if ($data->itemid) {
1953 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1954 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
1956 // Only restore the comment if has no mapping OR we have found the matching mapping
1957 if (!$mapping || $data->itemid) {
1958 // Only if user mapping and context
1959 $data->userid = $this->get_mappingid('user', $data->userid);
1960 if ($data->userid && $this->task->get_contextid()) {
1961 $data->contextid = $this->task->get_contextid();
1962 // Only if there is another comment with same context/user/timecreated
1963 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1964 if (!$DB->record_exists('comments', $params)) {
1965 $DB->insert_record('comments', $data);
1973 * This structure steps restores the badges and their configs
1975 class restore_badges_structure_step extends restore_structure_step {
1978 * Conditionally decide if this step should be executed.
1980 * This function checks the following parameters:
1982 * 1. Badges and course badges are enabled on the site.
1983 * 2. The course/badges.xml file exists.
1984 * 3. All modules are restorable.
1985 * 4. All modules are marked for restore.
1987 * @return bool True is safe to execute, false otherwise
1989 protected function execute_condition() {
1992 // First check is badges and course level badges are enabled on this site.
1993 if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
1994 // Disabled, don't restore course badges.
1998 // Check if badges.xml is included in the backup.
1999 $fullpath = $this->task->get_taskbasepath();
2000 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2001 if (!file_exists($fullpath)) {
2002 // Not found, can't restore course badges.
2006 // Check we are able to restore all backed up modules.
2007 if ($this->task->is_missing_modules()) {
2011 // Finally check all modules within the backup are being restored.
2012 if ($this->task->is_excluding_activities()) {
2019 protected function define_structure() {
2021 $paths[] = new restore_path_element('badge', '/badges/badge');
2022 $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2023 $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2024 $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2029 public function process_badge($data) {
2032 require_once($CFG->libdir . '/badgeslib.php');
2034 $data = (object)$data;
2035 $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2036 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2038 // We'll restore the badge image.
2039 $restorefiles = true;
2041 $courseid = $this->get_courseid();
2044 'name' => $data->name,
2045 'description' => $data->description,
2046 'timecreated' => $this->apply_date_offset($data->timecreated),
2047 'timemodified' => $this->apply_date_offset($data->timemodified),
2048 'usercreated' => $data->usercreated,
2049 'usermodified' => $data->usermodified,
2050 'issuername' => $data->issuername,
2051 'issuerurl' => $data->issuerurl,
2052 'issuercontact' => $data->issuercontact,
2053 'expiredate' => $this->apply_date_offset($data->expiredate),
2054 'expireperiod' => $data->expireperiod,
2055 'type' => BADGE_TYPE_COURSE,
2056 'courseid' => $courseid,
2057 'message' => $data->message,
2058 'messagesubject' => $data->messagesubject,
2059 'attachment' => $data->attachment,
2060 'notification' => $data->notification,
2061 'status' => BADGE_STATUS_INACTIVE,
2062 'nextcron' => $this->apply_date_offset($data->nextcron)
2065 $newid = $DB->insert_record('badge', $params);
2066 $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2069 public function process_criterion($data) {
2072 $data = (object)$data;
2075 'badgeid' => $this->get_new_parentid('badge'),
2076 'criteriatype' => $data->criteriatype,
2077 'method' => $data->method
2079 $newid = $DB->insert_record('badge_criteria', $params);
2080 $this->set_mapping('criterion', $data->id, $newid);
2083 public function process_parameter($data) {
2086 require_once($CFG->libdir . '/badgeslib.php');
2088 $data = (object)$data;
2089 $criteriaid = $this->get_new_parentid('criterion');
2091 // Parameter array that will go to database.
2093 $params['critid'] = $criteriaid;
2095 $oldparam = explode('_', $data->name);
2097 if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2098 $module = $this->get_mappingid('course_module', $oldparam[1]);
2099 $params['name'] = $oldparam[0] . '_' . $module;
2100 $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2101 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2102 $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2103 $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2104 } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2105 $role = $this->get_mappingid('role', $data->value);
2106 if (!empty($role)) {
2107 $params['name'] = 'role_' . $role;
2108 $params['value'] = $role;
2114 if (!$DB->record_exists('badge_criteria_param', $params)) {
2115 $DB->insert_record('badge_criteria_param', $params);
2119 public function process_manual_award($data) {
2122 $data = (object)$data;
2123 $role = $this->get_mappingid('role', $data->issuerrole);
2125 if (!empty($role)) {
2127 'badgeid' => $this->get_new_parentid('badge'),
2128 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2129 'issuerid' => $this->get_mappingid('user', $data->issuerid),
2130 'issuerrole' => $role,
2131 'datemet' => $this->apply_date_offset($data->datemet)
2133 $DB->insert_record('badge_manual_award', $award);
2137 protected function after_execute() {
2138 // Add related files.
2139 $this->add_related_files('badges', 'badgeimage', 'badge');
2144 * This structure steps restores the calendar events
2146 class restore_calendarevents_structure_step extends restore_structure_step {
2148 protected function define_structure() {
2152 $paths[] = new restore_path_element('calendarevents', '/events/event');
2157 public function process_calendarevents($data) {
2160 $data = (object)$data;
2162 $restorefiles = true; // We'll restore the files
2163 // Find the userid and the groupid associated with the event. Return if not found.
2164 $data->userid = $this->get_mappingid('user', $data->userid);
2165 if ($data->userid === false) {
2168 if (!empty($data->groupid)) {
2169 $data->groupid = $this->get_mappingid('group', $data->groupid);
2170 if ($data->groupid === false) {
2174 // Handle events with empty eventtype //MDL-32827
2175 if(empty($data->eventtype)) {
2176 if ($data->courseid == $SITE->id) { // Site event
2177 $data->eventtype = "site";
2178 } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2179 // Course assingment event
2180 $data->eventtype = "due";
2181 } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event
2182 $data->eventtype = "course";
2183 } else if ($data->groupid) { // Group event
2184 $data->eventtype = "group";
2185 } else if ($data->userid) { // User event
2186 $data->eventtype = "user";
2193 'name' => $data->name,
2194 'description' => $data->description,
2195 'format' => $data->format,
2196 'courseid' => $this->get_courseid(),
2197 'groupid' => $data->groupid,
2198 'userid' => $data->userid,
2199 'repeatid' => $data->repeatid,
2200 'modulename' => $data->modulename,
2201 'eventtype' => $data->eventtype,
2202 'timestart' => $this->apply_date_offset($data->timestart),
2203 'timeduration' => $data->timeduration,
2204 'visible' => $data->visible,
2205 'uuid' => $data->uuid,
2206 'sequence' => $data->sequence,
2207 'timemodified' => $this->apply_date_offset($data->timemodified));
2208 if ($this->name == 'activity_calendar') {
2209 $params['instance'] = $this->task->get_activityid();
2211 $params['instance'] = 0;
2215 WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2220 AND timeduration = ?
2221 AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2222 $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
2223 $result = $DB->record_exists_sql($sql, $arg);
2224 if (empty($result)) {
2225 $newitemid = $DB->insert_record('event', $params);
2226 $this->set_mapping('event', $oldid, $newitemid);
2227 $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2231 protected function after_execute() {
2232 // Add related files
2233 $this->add_related_files('calendar', 'event_description', 'event_description');
2237 class restore_course_completion_structure_step extends restore_structure_step {
2240 * Conditionally decide if this step should be executed.
2242 * This function checks parameters that are not immediate settings to ensure
2243 * that the enviroment is suitable for the restore of course completion info.
2245 * This function checks the following four parameters:
2247 * 1. Course completion is enabled on the site
2248 * 2. The backup includes course completion information
2249 * 3. All modules are restorable
2250 * 4. All modules are marked for restore.
2252 * @return bool True is safe to execute, false otherwise
2254 protected function execute_condition() {
2257 // First check course completion is enabled on this site
2258 if (empty($CFG->enablecompletion)) {
2259 // Disabled, don't restore course completion
2263 // Check it is included in the backup
2264 $fullpath = $this->task->get_taskbasepath();
2265 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2266 if (!file_exists($fullpath)) {
2267 // Not found, can't restore course completion
2271 // Check we are able to restore all backed up modules
2272 if ($this->task->is_missing_modules()) {
2276 // Finally check all modules within the backup are being restored.
2277 if ($this->task->is_excluding_activities()) {
2285 * Define the course completion structure
2287 * @return array Array of restore_path_element
2289 protected function define_structure() {
2291 // To know if we are including user completion info
2292 $userinfo = $this->get_setting_value('userscompletion');
2295 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2296 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2299 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2300 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2308 * Process course completion criteria
2310 * @global moodle_database $DB
2311 * @param stdClass $data
2313 public function process_course_completion_criteria($data) {
2316 $data = (object)$data;
2317 $data->course = $this->get_courseid();
2319 // Apply the date offset to the time end field
2320 $data->timeend = $this->apply_date_offset($data->timeend);
2322 // Map the role from the criteria
2323 if (!empty($data->role)) {
2324 $data->role = $this->get_mappingid('role', $data->role);
2327 $skipcriteria = false;
2329 // If the completion criteria is for a module we need to map the module instance
2330 // to the new module id.
2331 if (!empty($data->moduleinstance) && !empty($data->module)) {
2332 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
2333 if (empty($data->moduleinstance)) {
2334 $skipcriteria = true;
2337 $data->module = null;
2338 $data->moduleinstance = null;
2341 // We backup the course shortname rather than the ID so that we can match back to the course
2342 if (!empty($data->courseinstanceshortname)) {
2343 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
2344 if (!$courseinstanceid) {
2345 $skipcriteria = true;
2348 $courseinstanceid = null;
2350 $data->courseinstance = $courseinstanceid;
2352 if (!$skipcriteria) {
2354 'course' => $data->course,
2355 'criteriatype' => $data->criteriatype,
2356 'enrolperiod' => $data->enrolperiod,
2357 'courseinstance' => $data->courseinstance,
2358 'module' => $data->module,
2359 'moduleinstance' => $data->moduleinstance,
2360 'timeend' => $data->timeend,
2361 'gradepass' => $data->gradepass,
2362 'role' => $data->role
2364 $newid = $DB->insert_record('course_completion_criteria', $params);
2365 $this->set_mapping('course_completion_criteria', $data->id, $newid);
2370 * Processes course compltion criteria complete records
2372 * @global moodle_database $DB
2373 * @param stdClass $data
2375 public function process_course_completion_crit_compl($data) {
2378 $data = (object)$data;
2380 // This may be empty if criteria could not be restored
2381 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
2383 $data->course = $this->get_courseid();
2384 $data->userid = $this->get_mappingid('user', $data->userid);
2386 if (!empty($data->criteriaid) && !empty($data->userid)) {
2388 'userid' => $data->userid,
2389 'course' => $data->course,
2390 'criteriaid' => $data->criteriaid,
2391 'timecompleted' => $this->apply_date_offset($data->timecompleted)
2393 if (isset($data->gradefinal)) {
2394 $params['gradefinal'] = $data->gradefinal;
2396 if (isset($data->unenroled)) {
2397 $params['unenroled'] = $data->unenroled;
2399 $DB->insert_record('course_completion_crit_compl', $params);
2404 * Process course completions
2406 * @global moodle_database $DB
2407 * @param stdClass $data
2409 public function process_course_completions($data) {
2412 $data = (object)$data;
2414 $data->course = $this->get_courseid();
2415 $data->userid = $this->get_mappingid('user', $data->userid);
2417 if (!empty($data->userid)) {
2419 'userid' => $data->userid,
2420 'course' => $data->course,
2421 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
2422 'timestarted' => $this->apply_date_offset($data->timestarted),
2423 'timecompleted' => $this->apply_date_offset($data->timecompleted),
2424 'reaggregate' => $data->reaggregate
2426 $DB->insert_record('course_completions', $params);
2431 * Process course completion aggregate methods
2433 * @global moodle_database $DB
2434 * @param stdClass $data
2436 public function process_course_completion_aggr_methd($data) {
2439 $data = (object)$data;
2441 $data->course = $this->get_courseid();
2443 // Only create the course_completion_aggr_methd records if
2444 // the target course has not them defined. MDL-28180
2445 if (!$DB->record_exists('course_completion_aggr_methd', array(
2446 'course' => $data->course,
2447 'criteriatype' => $data->criteriatype))) {
2449 'course' => $data->course,
2450 'criteriatype' => $data->criteriatype,
2451 'method' => $data->method,
2452 'value' => $data->value,
2454 $DB->insert_record('course_completion_aggr_methd', $params);
2461 * This structure step restores course logs (cmid = 0), delegating
2462 * the hard work to the corresponding {@link restore_logs_processor} passing the
2463 * collection of {@link restore_log_rule} rules to be observed as they are defined
2464 * by the task. Note this is only executed based in the 'logs' setting.
2466 * NOTE: This is executed by final task, to have all the activities already restored
2468 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2469 * records are. There are others like 'calendar' and 'upload' that will be handled
2472 * NOTE: All the missing actions (not able to be restored) are sent to logs for
2473 * debugging purposes
2475 class restore_course_logs_structure_step extends restore_structure_step {
2478 * Conditionally decide if this step should be executed.
2480 * This function checks the following parameter:
2482 * 1. the course/logs.xml file exists
2484 * @return bool true is safe to execute, false otherwise
2486 protected function execute_condition() {
2488 // Check it is included in the backup
2489 $fullpath = $this->task->get_taskbasepath();
2490 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2491 if (!file_exists($fullpath)) {
2492 // Not found, can't restore course logs
2499 protected function define_structure() {
2503 // Simple, one plain level of information contains them
2504 $paths[] = new restore_path_element('log', '/logs/log');
2509 protected function process_log($data) {
2512 $data = (object)($data);
2514 $data->time = $this->apply_date_offset($data->time);
2515 $data->userid = $this->get_mappingid('user', $data->userid);
2516 $data->course = $this->get_courseid();
2519 // For any reason user wasn't remapped ok, stop processing this
2520 if (empty($data->userid)) {
2524 // Everything ready, let's delegate to the restore_logs_processor
2526 // Set some fixed values that will save tons of DB requests
2528 'course' => $this->get_courseid());
2529 // Get instance and process log record
2530 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2532 // If we have data, insert it, else something went wrong in the restore_logs_processor
2534 $DB->insert_record('log', $data);
2540 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2541 * sharing its same structure but modifying the way records are handled
2543 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2545 protected function process_log($data) {
2548 $data = (object)($data);
2550 $data->time = $this->apply_date_offset($data->time);
2551 $data->userid = $this->get_mappingid('user', $data->userid);
2552 $data->course = $this->get_courseid();
2553 $data->cmid = $this->task->get_moduleid();
2555 // For any reason user wasn't remapped ok, stop processing this
2556 if (empty($data->userid)) {
2560 // Everything ready, let's delegate to the restore_logs_processor
2562 // Set some fixed values that will save tons of DB requests
2564 'course' => $this->get_courseid(),
2565 'course_module' => $this->task->get_moduleid(),
2566 $this->task->get_modulename() => $this->task->get_activityid());
2567 // Get instance and process log record
2568 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2570 // If we have data, insert it, else something went wrong in the restore_logs_processor
2572 $DB->insert_record('log', $data);
2579 * Defines the restore step for advanced grading methods attached to the activity module
2581 class restore_activity_grading_structure_step extends restore_structure_step {
2584 * This step is executed only if the grading file is present
2586 protected function execute_condition() {
2588 $fullpath = $this->task->get_taskbasepath();
2589 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2590 if (!file_exists($fullpath)) {
2599 * Declares paths in the grading.xml file we are interested in
2601 protected function define_structure() {
2604 $userinfo = $this->get_setting_value('userinfo');
2606 $area = new restore_path_element('grading_area', '/areas/area');
2608 // attach local plugin stucture to $area element
2609 $this->add_plugin_structure('local', $area);
2611 $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
2612 $paths[] = $definition;
2613 $this->add_plugin_structure('gradingform', $definition);
2614 // attach local plugin stucture to $definition element
2615 $this->add_plugin_structure('local', $definition);
2619 $instance = new restore_path_element('grading_instance',
2620 '/areas/area/definitions/definition/instances/instance');
2621 $paths[] = $instance;
2622 $this->add_plugin_structure('gradingform', $instance);
2623 // attach local plugin stucture to $intance element
2624 $this->add_plugin_structure('local', $instance);
2631 * Processes one grading area element
2633 * @param array $data element data
2635 protected function process_grading_area($data) {
2638 $task = $this->get_task();
2639 $data = (object)$data;
2641 $data->component = 'mod_'.$task->get_modulename();
2642 $data->contextid = $task->get_contextid();
2644 $newid = $DB->insert_record('grading_areas', $data);
2645 $this->set_mapping('grading_area', $oldid, $newid);
2649 * Processes one grading definition element
2651 * @param array $data element data
2653 protected function process_grading_definition($data) {
2656 $task = $this->get_task();
2657 $data = (object)$data;
2659 $data->areaid = $this->get_new_parentid('grading_area');
2660 $data->copiedfromid = null;
2661 $data->timecreated = time();
2662 $data->usercreated = $task->get_userid();
2663 $data->timemodified = $data->timecreated;
2664 $data->usermodified = $data->usercreated;
2666 $newid = $DB->insert_record('grading_definitions', $data);
2667 $this->set_mapping('grading_definition', $oldid, $newid, true);
2671 * Processes one grading form instance element
2673 * @param array $data element data
2675 protected function process_grading_instance($data) {
2678 $data = (object)$data;
2680 // new form definition id
2681 $newformid = $this->get_new_parentid('grading_definition');
2683 // get the name of the area we are restoring to
2684 $sql = "SELECT ga.areaname
2685 FROM {grading_definitions} gd
2686 JOIN {grading_areas} ga ON gd.areaid = ga.id
2688 $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
2690 // get the mapped itemid - the activity module is expected to define the mappings
2691 // for each gradable area
2692 $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
2695 $data->definitionid = $newformid;
2696 $data->raterid = $this->get_mappingid('user', $data->raterid);
2697 $data->itemid = $newitemid;
2699 $newid = $DB->insert_record('grading_instances', $data);
2700 $this->set_mapping('grading_instance', $oldid, $newid);
2704 * Final operations when the database records are inserted
2706 protected function after_execute() {
2707 // Add files embedded into the definition description
2708 $this->add_related_files('grading', 'description', 'grading_definition');
2714 * This structure step restores the grade items associated with one activity
2715 * All the grade items are made child of the "course" grade item but the original
2716 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
2717 * the complete gradebook (categories and calculations), that information is
2720 class restore_activity_grades_structure_step extends restore_structure_step {
2722 protected function define_structure() {
2725 $userinfo = $this->get_setting_value('userinfo');
2727 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
2728 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
2730 $paths[] = new restore_path_element('grade_grade',
2731 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
2736 protected function process_grade_item($data) {
2739 $data = (object)($data);
2740 $oldid = $data->id; // We'll need these later
2741 $oldparentid = $data->categoryid;
2742 $courseid = $this->get_courseid();
2744 // make sure top course category exists, all grade items will be associated
2745 // to it. Later, if restoring the whole gradebook, categories will be introduced
2746 $coursecat = grade_category::fetch_course_category($courseid);
2747 $coursecatid = $coursecat->id; // Get the categoryid to be used
2750 if (!empty($data->idnumber)) {
2751 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
2752 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
2753 // so the best is to keep the ones already in the gradebook
2754 // Potential problem: duplicates if same items are restored more than once. :-(
2755 // This needs to be fixed in some way (outcomes & activities with multiple items)
2756 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
2757 // In any case, verify always for uniqueness
2758 $sql = "SELECT cm.id
2759 FROM {course_modules} cm
2760 WHERE cm.course = :courseid AND
2761 cm.idnumber = :idnumber AND
2764 'courseid' => $courseid,
2765 'idnumber' => $data->idnumber,
2766 'cmid' => $this->task->get_moduleid()
2768 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
2769 $idnumber = $data->idnumber;
2774 $data->categoryid = $coursecatid;
2775 $data->courseid = $this->get_courseid();
2776 $data->iteminstance = $this->task->get_activityid();
2777 $data->idnumber = $idnumber;
2778 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
2779 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
2780 $data->timecreated = $this->apply_date_offset($data->timecreated);
2781 $data->timemodified = $this->apply_date_offset($data->timemodified);
2783 $gradeitem = new grade_item($data, false);
2784 $gradeitem->insert('restore');
2786 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
2787 $gradeitem->sortorder = $data->sortorder;
2788 $gradeitem->update('restore');
2790 // Set mapping, saving the original category id into parentitemid
2791 // gradebook restore (final task) will need it to reorganise items
2792 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
2795 protected function process_grade_grade($data) {
2796 $data = (object)($data);
2797 $olduserid = $data->userid;
2800 $data->itemid = $this->get_new_parentid('grade_item');
2802 $data->userid = $this->get_mappingid('user', $data->userid, null);
2803 if (!empty($data->userid)) {
2804 $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
2805 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
2806 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
2807 $data->overridden = $this->apply_date_offset($data->overridden);
2809 $grade = new grade_grade($data, false);
2810 $grade->insert('restore');
2811 // no need to save any grade_grade mapping
2813 debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
2818 * process activity grade_letters. Note that, while these are possible,
2819 * because grade_letters are contextid based, in practice, only course
2820 * context letters can be defined. So we keep here this method knowing
2821 * it won't be executed ever. gradebook restore will restore course letters.
2823 protected function process_grade_letter($data) {
2826 $data['contextid'] = $this->task->get_contextid();
2827 $gradeletter = (object)$data;
2829 // Check if it exists before adding it
2831 if (!$DB->record_exists('grade_letters', $data)) {
2832 $newitemid = $DB->insert_record('grade_letters', $gradeletter);
2834 // no need to save any grade_letter mapping
2837 public function after_restore() {
2838 // Fix grade item's sortorder after restore, as it might have duplicates.
2839 $courseid = $this->get_task()->get_courseid();
2840 grade_item::fix_duplicate_sortorder($courseid);
2846 * This structure steps restores one instance + positions of one block
2847 * Note: Positions corresponding to one existing context are restored
2848 * here, but all the ones having unknown contexts are sent to backup_ids
2849 * for a later chance to be restored at the end (final task)
2851 class restore_block_instance_structure_step extends restore_structure_step {
2853 protected function define_structure() {
2857 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
2858 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
2863 public function process_block($data) {
2866 $data = (object)$data; // Handy
2867 $oldcontextid = $data->contextid;
2869 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
2871 // Look for the parent contextid
2872 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
2873 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
2876 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
2877 // If there is already one block of that type in the parent context
2878 // and the block is not multiple, stop processing
2879 // Use blockslib loader / method executor
2880 if (!$bi = block_instance($data->blockname)) {
2884 if (!$bi->instance_allow_multiple()) {
2885 if ($DB->record_exists_sql("SELECT bi.id
2886 FROM {block_instances} bi
2887 JOIN {block} b ON b.name = bi.blockname
2888 WHERE bi.parentcontextid = ?
2889 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
2894 // If there is already one block of that type in the parent context
2895 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
2898 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
2899 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
2900 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
2901 if ($birecs = $DB->get_records('block_instances', $params)) {
2902 foreach($birecs as $birec) {
2903 if ($birec->configdata == $data->configdata) {
2909 // Set task old contextid, blockid and blockname once we know them
2910 $this->task->set_old_contextid($oldcontextid);
2911 $this->task->set_old_blockid($oldid);
2912 $this->task->set_blockname($data->blockname);
2914 // Let's look for anything within configdata neededing processing
2915 // (nulls and uses of legacy file.php)
2916 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
2917 $configdata = (array)unserialize(base64_decode($data->configdata));
2918 foreach ($configdata as $attribute => $value) {
2919 if (in_array($attribute, $attrstotransform)) {
2920 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
2923 $data->configdata = base64_encode(serialize((object)$configdata));
2926 // Create the block instance
2927 $newitemid = $DB->insert_record('block_instances', $data);
2928 // Save the mapping (with restorefiles support)
2929 $this->set_mapping('block_instance', $oldid, $newitemid, true);
2930 // Create the block context
2931 $newcontextid = context_block::instance($newitemid)->id;
2932 // Save the block contexts mapping and sent it to task
2933 $this->set_mapping('context', $oldcontextid, $newcontextid);
2934 $this->task->set_contextid($newcontextid);
2935 $this->task->set_blockid($newitemid);
2937 // Restore block fileareas if declared
2938 $component = 'block_' . $this->task->get_blockname();
2939 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
2940 $this->add_related_files($component, $filearea, null);
2943 // Process block positions, creating them or accumulating for final step
2944 foreach($positions as $position) {
2945 $position = (object)$position;
2946 $position->blockinstanceid = $newitemid; // The instance is always the restored one
2947 // If position is for one already mapped (known) contextid
2948 // process it now, creating the position
2949 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
2950 $position->contextid = $newpositionctxid;
2951 // Create the block position
2952 $DB->insert_record('block_positions', $position);
2954 // The position belongs to an unknown context, send it to backup_ids
2955 // to process them as part of the final steps of restore. We send the
2956 // whole $position object there, hence use the low level method.
2958 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
2965 * Structure step to restore common course_module information
2967 * This step will process the module.xml file for one activity, in order to restore
2968 * the corresponding information to the course_modules table, skipping various bits
2969 * of information based on CFG settings (groupings, completion...) in order to fullfill
2970 * all the reqs to be able to create the context to be used by all the rest of steps
2971 * in the activity restore task
2973 class restore_module_structure_step extends restore_structure_step {
2975 protected function define_structure() {
2980 $module = new restore_path_element('module', '/module');
2982 if ($CFG->enableavailability) {
2983 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
2984 $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
2987 // Apply for 'format' plugins optional paths at module level
2988 $this->add_plugin_structure('format', $module);
2990 // Apply for 'plagiarism' plugins optional paths at module level
2991 $this->add_plugin_structure('plagiarism', $module);
2993 // Apply for 'local' plugins optional paths at module level
2994 $this->add_plugin_structure('local', $module);
2999 protected function process_module($data) {
3002 $data = (object)$data;
3004 $this->task->set_old_moduleversion($data->version);
3006 $data->course = $this->task->get_courseid();
3007 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
3008 // Map section (first try by course_section mapping match. Useful in course and section restores)
3009 $data->section = $this->get_mappingid('course_section', $data->sectionid);
3010 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
3012 'course' => $this->get_courseid(),
3013 'section' => $data->sectionnumber);
3014 $data->section = $DB->get_field('course_sections', 'id', $params);
3016 if (!$data->section) { // sectionnumber failed, try to get first section in course
3018 'course' => $this->get_courseid());
3019 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
3021 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
3022 $sectionrec = array(
3023 'course' => $this->get_courseid(),
3025 $DB->insert_record('course_sections', $sectionrec); // section 0
3026 $sectionrec = array(
3027 'course' => $this->get_courseid(),
3029 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
3031 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
3032 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
3033 $data->groupmembersonly = 0;
3035 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
3036 $data->idnumber = '';
3038 if (empty($CFG->enablecompletion)) { // completion
3039 $data->completion = 0;
3040 $data->completiongradeitemnumber = null;
3041 $data->completionview = 0;
3042 $data->completionexpected = 0;
3044 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
3046 if (empty($CFG->enableavailability)) {
3047 $data->availablefrom = 0;
3048 $data->availableuntil = 0;
3049 $data->showavailability = 0;
3051 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
3052 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
3054 // Backups that did not include showdescription, set it to default 0
3055 // (this is not totally necessary as it has a db default, but just to
3057 if (!isset($data->showdescription)) {
3058 $data->showdescription = 0;
3060 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
3062 // course_module record ready, insert it
3063 $newitemid = $DB->insert_record('course_modules', $data);
3065 $this->set_mapping('course_module', $oldid, $newitemid);
3066 // set the new course_module id in the task
3067 $this->task->set_moduleid($newitemid);
3068 // we can now create the context safely
3069 $ctxid = context_module::instance($newitemid)->id;
3070 // set the new context id in the task
3071 $this->task->set_contextid($ctxid);
3072 // update sequence field in course_section
3073 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
3074 $sequence .= ',' . $newitemid;
3076 $sequence = $newitemid;
3078 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
3081 protected function process_availability($data) {
3082 $data = (object)$data;
3083 // Simply going to store the whole availability record now, we'll process
3084 // all them later in the final task (once all activities have been restored)
3085 // Let's call the low level one to be able to store the whole object
3086 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
3087 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
3090 protected function process_availability_field($data) {
3092 $data = (object)$data;
3093 // Mark it is as passed by default
3095 $customfieldid = null;
3097 // If a customfield has been used in order to pass we must be able to match an existing
3098 // customfield by name (data->customfield) and type (data->customfieldtype)
3099 if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
3100 // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
3101 // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
3103 } else if (!empty($data->customfield)) {
3104 $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
3105 $customfieldid = $DB->get_field('user_info_field', 'id', $params);
3106 $passed = ($customfieldid !== false);
3110 // Create the object to insert into the database
3111 $availfield = new stdClass();
3112 $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
3113 $availfield->userfield = $data->userfield;
3114 $availfield->customfieldid = $customfieldid;
3115 $availfield->operator = $data->operator;
3116 $availfield->value = $data->value;
3117 // Insert into the database
3118 $DB->insert_record('course_modules_avail_fields', $availfield);
3124 * Structure step that will process the user activity completion
3125 * information if all these conditions are met:
3126 * - Target site has completion enabled ($CFG->enablecompletion)
3127 * - Activity includes completion info (file_exists)
3129 class restore_userscompletion_structure_step extends restore_structure_step {
3131 * To conditionally decide if this step must be executed
3132 * Note the "settings" conditions are evaluated in the
3133 * corresponding task. Here we check for other conditions
3134 * not being restore settings (files, site settings...)
3136 protected function execute_condition() {
3139 // Completion disabled in this site, don't execute
3140 if (empty($CFG->enablecompletion)) {
3144 // No user completion info found, don't execute
3145 $fullpath = $this->task->get_taskbasepath();
3146 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3147 if (!file_exists($fullpath)) {
3151 // Arrived here, execute the step
3155 protected function define_structure() {
3159 $paths[] = new restore_path_element('completion', '/completions/completion');
3164 protected function process_completion($data) {
3167 $data = (object)$data;
3169 $data->coursemoduleid = $this->task->get_moduleid();
3170 $data->userid = $this->get_mappingid('user', $data->userid);
3171 $data->timemodified = $this->apply_date_offset($data->timemodified);
3173 // Find the existing record
3174 $existing = $DB->get_record('course_modules_completion', array(
3175 'coursemoduleid' => $data->coursemoduleid,
3176 'userid' => $data->userid), 'id, timemodified');
3177 // Check we didn't already insert one for this cmid and userid
3178 // (there aren't supposed to be duplicates in that field, but
3179 // it was possible until MDL-28021 was fixed).
3181 // Update it to these new values, but only if the time is newer
3182 if ($existing->timemodified < $data->timemodified) {
3183 $data->id = $existing->id;
3184 $DB->update_record('course_modules_completion', $data);
3187 // Normal entry where it doesn't exist already
3188 $DB->insert_record('course_modules_completion', $data);
3194 * Abstract structure step, parent of all the activity structure steps. Used to suuport
3195 * the main <activity ...> tag and process it. Also provides subplugin support for
3198 abstract class restore_activity_structure_step extends restore_structure_step {
3200 protected function add_subplugin_structure($subplugintype, $element) {
3204 // Check the requested subplugintype is a valid one
3205 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
3206 if (!file_exists($subpluginsfile)) {
3207 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
3209 include($subpluginsfile);
3210 if (!array_key_exists($subplugintype, $subplugins)) {
3211 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
3213 // Get all the restore path elements, looking across all the subplugin dirs
3214 $subpluginsdirs = core_component::get_plugin_list($subplugintype);
3215 foreach ($subpluginsdirs as $name => $subpluginsdir) {
3216 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
3217 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
3218 if (file_exists($restorefile)) {
3219 require_once($restorefile);
3220 $restoresubplugin = new $classname($subplugintype, $name, $this);
3221 // Add subplugin paths to the step
3222 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
3228 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
3229 * have the parent task available for wrapping purposes (get course/context....)
3230 * @return restore_task
3232 public function get_task() {
3237 * Adds support for the 'activity' path that is common to all the activities
3238 * and will be processed globally here
3240 protected function prepare_activity_structure($paths) {
3242 $paths[] = new restore_path_element('activity', '/activity');
3248 * Process the activity path, informing the task about various ids, needed later
3250 protected function process_activity($data) {
3251 $data = (object)$data;
3252 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
3253 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
3254 $this->task->set_old_activityid($data->id); // Save old activityid in task