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/>.
20 * @subpackage backup-moodle2
21 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 * Define all the restore steps that will be used by common tasks in restore
30 * delete old directories and conditionally create backup_temp_ids table
32 class restore_create_and_clean_temp_stuff extends restore_execution_step {
34 protected function define_execution() {
35 $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
36 // If the table already exists, it's because restore_prechecks have been executed in the same
37 // request (without problems) and it already contains a bunch of preloaded information (users...)
38 // that we aren't going to execute again
39 if ($exists) { // Inform plan about preloaded information
40 $this->task->set_preloaded_information();
42 // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
43 $itemid = $this->task->get_old_contextid();
44 $newitemid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
45 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
46 // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
47 $itemid = $this->task->get_old_system_contextid();
48 $newitemid = get_context_instance(CONTEXT_SYSTEM)->id;
49 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
54 * delete the temp dir used by backup/restore (conditionally),
55 * delete old directories and drop temp ids table
57 class restore_drop_and_clean_temp_stuff extends restore_execution_step {
59 protected function define_execution() {
61 restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
62 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
63 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
64 backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
70 * Restore calculated grade items, grade categories etc
72 class restore_gradebook_step extends restore_structure_step {
75 * To conditionally decide if this step must be executed
76 * Note the "settings" conditions are evaluated in the
77 * corresponding task. Here we check for other conditions
78 * not being restore settings (files, site settings...)
80 protected function execute_condition() {
83 // No gradebook info found, don't execute
84 $fullpath = $this->task->get_taskbasepath();
85 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
86 if (!file_exists($fullpath)) {
90 // Arrived here, execute the step
94 protected function define_structure() {
96 $userinfo = $this->task->get_setting_value('users');
98 $paths[] = new restore_path_element('gradebook', '/gradebook');
99 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
100 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
102 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
104 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
109 protected function process_gradebook($data) {
112 protected function process_grade_item($data) {
115 $data = (object)$data;
118 $data->course = $this->get_courseid();
120 $data->courseid = $this->get_courseid();
122 //manual grade items store category id in categoryid
123 if ($data->itemtype=='manual') {
124 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid);
125 } //course and category grade items store their category id in iteminstance
126 else if ($data->itemtype=='course' || $data->itemtype=='category') {
127 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance);
130 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
131 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
133 $data->locktime = $this->apply_date_offset($data->locktime);
134 $data->timecreated = $this->apply_date_offset($data->timecreated);
135 $data->timemodified = $this->apply_date_offset($data->timemodified);
137 $coursecategory = $newitemid = null;
138 //course grade item should already exist so updating instead of inserting
139 if($data->itemtype=='course') {
141 //get the ID of the already created grade item
142 $gi = new stdclass();
143 $gi->courseid = $this->get_courseid();
145 $gi->itemtype = $data->itemtype;
146 if ($data->itemtype=='course') {
147 //need to get the id of the grade_category that was automatically created for the course
148 $category = new stdclass();
149 $category->courseid = $this->get_courseid();
150 $category->parent = null;
151 $category->fullname = '?';
153 $coursecategory = $DB->get_record('grade_categories', (array)$category);
154 $gi->iteminstance = $coursecategory->id;
157 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
158 if (!empty($existinggradeitem)) {
159 $data->id = $newitemid = $existinggradeitem->id;
160 $DB->update_record('grade_items', $data);
164 if (empty($newitemid)) {
165 //in case we found the course category but still need to insert the course grade item
166 if ($data->itemtype=='course' && !empty($coursecategory)) {
167 $data->iteminstance = $coursecategory->id;
170 $newitemid = $DB->insert_record('grade_items', $data);
172 $this->set_mapping('grade_item', $oldid, $newitemid);
175 protected function process_grade_grade($data) {
178 $data = (object)$data;
181 $data->itemid = $this->get_new_parentid('grade_item');
183 $data->userid = $this->get_mappingid('user', $data->userid);
184 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
185 $data->locktime = $this->apply_date_offset($data->locktime);
186 $data->timecreated = $this->apply_date_offset($data->timecreated);
187 $data->timemodified = $this->apply_date_offset($data->timemodified);
189 $newitemid = $DB->insert_record('grade_grades', $data);
190 $this->set_mapping('grade_grade', $oldid, $newitemid);
192 protected function process_grade_category($data) {
195 $data = (object)$data;
198 $data->course = $this->get_courseid();
199 $data->courseid = $data->course;
201 $data->timecreated = $this->apply_date_offset($data->timecreated);
202 $data->timemodified = $this->apply_date_offset($data->timemodified);
205 //no parent means a course level grade category. That may have been created when the course was created
206 if(empty($data->parent)) {
207 //parent was being saved as 0 when it should be null
208 $data->parent = null;
210 //get the already created course level grade category
211 $category = new stdclass();
212 $category->courseid = $this->get_courseid();
214 $coursecategory = $DB->get_record('grade_categories', (array)$category);
215 if (!empty($coursecategory)) {
216 $data->id = $newitemid = $coursecategory->id;
217 $DB->update_record('grade_categories', $data);
221 //need to insert a course category
222 if (empty($newitemid)) {
223 if (!empty($data->parent)) {
224 $data->parent = $this->get_mappingid('grade_category', $data->parent);
226 $newitemid = $DB->insert_record('grade_categories', $data);
228 $this->set_mapping('grade_category', $oldid, $newitemid);
230 //need to correct the path as its a string that contains grade category IDs
231 $grade_category = new stdclass();
232 $grade_category->parent = $data->parent;
233 $grade_category->id = $newitemid;
234 $grade_category->path = grade_category::build_path($grade_category);
235 $DB->update_record('grade_categories', $grade_category);
237 protected function process_grade_letter($data) {
240 $data = (object)$data;
243 $data->contextid = $this->get_mappingid('context', $data->contextid);
245 $newitemid = $DB->insert_record('grade_letters', $data);
246 $this->set_mapping('grade_letter', $oldid, $newitemid);
249 //put all activity grade items in the correct grade category and mark all for recalculation
250 protected function after_execute() {
254 'backupid' => $this->get_restoreid(),
255 'itemname' => 'grade_item'//,
256 //'itemid' => $itemid
258 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
261 foreach($rs as $grade_item_backup) {
262 $updateobj = new stdclass();
263 $updateobj->id = $grade_item_backup->newitemid;
265 //if this is an activity grade item that needs to be put back in its correct category
266 if (!empty($grade_item_backup->parentitemid)) {
267 $updateobj->categoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid);
269 //mark course and category items as needing to be recalculated
270 $updateobj->needsupdate=1;
272 $DB->update_record('grade_items', $updateobj);
274 //todo need to get hold of the grade_items previous sortorder to restore it
282 * decode all the interlinks present in restored content
283 * relying 100% in the restore_decode_processor that handles
284 * both the contents to modify and the rules to be applied
286 class restore_decode_interlinks extends restore_execution_step {
288 protected function define_execution() {
290 $this->task->get_decoder()->execute();
295 * rebuid the course cache
297 class restore_rebuild_course_cache extends restore_execution_step {
299 protected function define_execution() {
301 rebuild_course_cache($this->get_courseid());
307 * Review all the (pending) block positions in backup_ids, matching by
308 * contextid, creating positions as needed. This is executed by the
309 * final task, once all the contexts have been created
311 class restore_review_pending_block_positions extends restore_execution_step {
313 protected function define_execution() {
316 // Get all the block_position objects pending to match
317 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
318 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
319 // Process block positions, creating them or accumulating for final step
320 foreach($rs as $posrec) {
321 // Get the complete position object (stored as info)
322 $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
323 // If position is for one already mapped (known) contextid
324 // process it now, creating the position, else nothing to
325 // do, position finally discarded
326 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
327 $position->contextid = $newctx->newitemid;
328 // Create the block position
329 $DB->insert_record('block_positions', $position);
337 * Process all the saved module availability records in backup_ids, matching
338 * course modules and grade item id once all them have been already restored.
339 * only if all matchings are satisfied the availability condition will be created.
340 * At the same time, it is required for the site to have that functionality enabled.
342 class restore_process_course_modules_availability extends restore_execution_step {
344 protected function define_execution() {
347 // Site hasn't availability enabled
348 if (empty($CFG->enableavailability)) {
352 // Get all the module_availability objects to process
353 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
354 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
355 // Process availabilities, creating them if everything matches ok
356 foreach($rs as $availrec) {
357 $allmatchesok = true;
358 // Get the complete availabilityobject
359 $availability = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_availability', $availrec->itemid)->info;
360 // Map the sourcecmid if needed and possible
361 if (!empty($availability->sourcecmid)) {
362 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
364 $availability->sourcecmid = $newcm->newitemid;
366 $allmatchesok = false; // Failed matching, we won't create this availability rule
369 // Map the gradeitemid if needed and possible
370 if (!empty($availability->gradeitemid)) {
371 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
373 $availability->gradeitemid = $newgi->newitemid;
375 $allmatchesok = false; // Failed matching, we won't create this availability rule
378 if ($allmatchesok) { // Everything ok, create the availability rule
379 $DB->insert_record('course_modules_availability', $availability);
388 * Execution step that, *conditionally* (if there isn't preloaded information)
389 * will load the inforef files for all the included course/section/activity tasks
390 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
392 class restore_load_included_inforef_records extends restore_execution_step {
394 protected function define_execution() {
396 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
400 // Get all the included inforef files
401 $files = restore_dbops::get_needed_inforef_files($this->get_restoreid());
402 foreach ($files as $file) {
403 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $file); // Load each inforef file to temp_ids
409 * Execution step that will load all the needed files into backup_files_temp
410 * - info: contains the whole original object (times, names...)
411 * (all them being original ids as loaded from xml)
413 class restore_load_included_files extends restore_structure_step {
415 protected function define_structure() {
417 $file = new restore_path_element('file', '/files/file');
422 // Processing functions go here
423 public function process_file($data) {
425 $data = (object)$data; // handy
427 // load it if needed:
428 // - it it is one of the annotated inforef files (course/section/activity/block)
429 // - it is one "user", "group", "grouping" or "grade" component file (that aren't sent to inforef ever)
430 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
431 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
432 $data->component == 'grouping' || $data->component == 'grade');
433 if ($isfileref || $iscomponent) {
434 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
440 * Execution step that, *conditionally* (if there isn't preloaded information),
441 * will load all the needed roles to backup_temp_ids. They will be stored with
442 * "role" itemname. Also it will perform one automatic mapping to roles existing
443 * in the target site, based in permissions of the user performing the restore,
444 * archetypes and other bits. At the end, each original role will have its associated
445 * target role or 0 if it's going to be skipped. Note we wrap everything over one
446 * restore_dbops method, as far as the same stuff is going to be also executed
447 * by restore prechecks
449 class restore_load_and_map_roles extends restore_execution_step {
451 protected function define_execution() {
452 if ($this->task->get_preloaded_information()) { // if info is already preloaded
456 $file = $this->get_basepath() . '/roles.xml';
457 // Load needed toles to temp_ids
458 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
460 // Process roles, mapping/skipping. Any error throws exception
461 // Note we pass controller's info because it can contain role mapping information
462 // about manual mappings performed by UI
463 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);
468 * Execution step that, *conditionally* (if there isn't preloaded information
469 * and users have been selected in settings, will load all the needed users
470 * to backup_temp_ids. They will be stored with "user" itemname and with
471 * their original contextid as paremitemid
473 class restore_load_included_users extends restore_execution_step {
475 protected function define_execution() {
477 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
480 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
483 $file = $this->get_basepath() . '/users.xml';
484 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
489 * Execution step that, *conditionally* (if there isn't preloaded information
490 * and users have been selected in settings, will process all the needed users
491 * in order to decide and perform any action with them (create / map / error)
492 * Note: Any error will cause exception, as far as this is the same processing
493 * than the one into restore prechecks (that should have stopped process earlier)
495 class restore_process_included_users extends restore_execution_step {
497 protected function define_execution() {
499 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
502 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
505 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
510 * Execution step that will create all the needed users as calculated
511 * by @restore_process_included_users (those having newiteind = 0)
513 class restore_create_included_users extends restore_execution_step {
515 protected function define_execution() {
517 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->get_setting_value('user_files'), $this->task->get_userid());
522 * Structure step that will create all the needed groups and groupings
523 * by loading them from the groups.xml file performing the required matches.
524 * Note group members only will be added if restoring user info
526 class restore_groups_structure_step extends restore_structure_step {
528 protected function define_structure() {
530 $paths = array(); // Add paths here
532 $paths[] = new restore_path_element('group', '/groups/group');
533 if ($this->get_setting_value('users')) {
534 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
536 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
537 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
542 // Processing functions go here
543 public function process_group($data) {
546 $data = (object)$data; // handy
547 $data->courseid = $this->get_courseid();
549 $oldid = $data->id; // need this saved for later
551 $restorefiles = false; // Only if we end creating the group
553 // Search if the group already exists (by name & description) in the target course
554 $description_clause = '';
555 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
556 if (!empty($data->description)) {
557 $description_clause = ' AND ' .
558 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
559 $params['desc'] = $data->description;
561 if (!$groupdb = $DB->get_record_sql("SELECT *
563 WHERE courseid = :courseid
564 AND name = :grname $description_clause", $params)) {
565 // group doesn't exist, create
566 $newitemid = $DB->insert_record('groups', $data);
567 $restorefiles = true; // We'll restore the files
569 // group exists, use it
570 $newitemid = $groupdb->id;
572 // Save the id mapping
573 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
576 public function process_member($data) {
579 $data = (object)$data; // handy
581 // get parent group->id
582 $data->groupid = $this->get_new_parentid('group');
584 // map user newitemid and insert if not member already
585 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
586 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
587 $DB->insert_record('groups_members', $data);
592 public function process_grouping($data) {
595 $data = (object)$data; // handy
596 $data->courseid = $this->get_courseid();
598 $oldid = $data->id; // need this saved for later
599 $restorefiles = false; // Only if we end creating the grouping
601 // Search if the grouping already exists (by name & description) in the target course
602 $description_clause = '';
603 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
604 if (!empty($data->description)) {
605 $description_clause = ' AND ' .
606 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
607 $params['desc'] = $data->description;
609 if (!$groupingdb = $DB->get_record_sql("SELECT *
611 WHERE courseid = :courseid
612 AND name = :grname $description_clause", $params)) {
613 // grouping doesn't exist, create
614 $newitemid = $DB->insert_record('groupings', $data);
615 $restorefiles = true; // We'll restore the files
617 // grouping exists, use it
618 $newitemid = $groupingdb->id;
620 // Save the id mapping
621 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
624 public function process_grouping_group($data) {
627 $data = (object)$data;
629 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
630 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
631 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
634 protected function after_execute() {
635 // Add group related files, matching with "group" mappings
636 $this->add_related_files('group', 'icon', 'group');
637 $this->add_related_files('group', 'description', 'group');
638 // Add grouping related files, matching with "grouping" mappings
639 $this->add_related_files('grouping', 'description', 'grouping');
645 * Structure step that will create all the needed scales
646 * by loading them from the scales.xml
648 class restore_scales_structure_step extends restore_structure_step {
650 protected function define_structure() {
652 $paths = array(); // Add paths here
653 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
657 protected function process_scale($data) {
660 $data = (object)$data;
662 $restorefiles = false; // Only if we end creating the group
664 $oldid = $data->id; // need this saved for later
666 // Look for scale (by 'scale' both in standard (course=0) and current course
667 // with priority to standard scales (ORDER clause)
668 // scale is not course unique, use get_record_sql to suppress warning
669 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
670 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
671 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
672 if (!$scadb = $DB->get_record_sql("SELECT *
674 WHERE courseid IN (0, :courseid)
675 AND $compare_scale_clause
676 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
677 // Remap the user if possible, defaut to user performing the restore if not
678 $userid = $this->get_mappingid('user', $data->userid);
679 $data->userid = $userid ? $userid : $this->task->get_userid();
680 // Remap the course if course scale
681 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
682 // If global scale (course=0), check the user has perms to create it
683 // falling to course scale if not
684 $systemctx = get_context_instance(CONTEXT_SYSTEM);
685 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
686 $data->courseid = $this->get_courseid();
688 // scale doesn't exist, create
689 $newitemid = $DB->insert_record('scale', $data);
690 $restorefiles = true; // We'll restore the files
692 // scale exists, use it
693 $newitemid = $scadb->id;
695 // Save the id mapping (with files support at system context)
696 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
699 protected function after_execute() {
700 // Add scales related files, matching with "scale" mappings
701 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
707 * Structure step that will create all the needed outocomes
708 * by loading them from the outcomes.xml
710 class restore_outcomes_structure_step extends restore_structure_step {
712 protected function define_structure() {
714 $paths = array(); // Add paths here
715 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
719 protected function process_outcome($data) {
722 $data = (object)$data;
724 $restorefiles = false; // Only if we end creating the group
726 $oldid = $data->id; // need this saved for later
728 // Look for outcome (by shortname both in standard (courseid=null) and current course
729 // with priority to standard outcomes (ORDER clause)
730 // outcome is not course unique, use get_record_sql to suppress warning
731 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
732 if (!$outdb = $DB->get_record_sql('SELECT *
733 FROM {grade_outcomes}
734 WHERE shortname = :shortname
735 AND (courseid = :courseid OR courseid IS NULL)
736 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
738 $userid = $this->get_mappingid('user', $data->usermodified);
739 $data->usermodified = $userid ? $userid : $this->task->get_userid();
741 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
742 // Remap the course if course outcome
743 $data->courseid = $data->courseid ? $this->get_courseid() : null;
744 // If global outcome (course=null), check the user has perms to create it
745 // falling to course outcome if not
746 $systemctx = get_context_instance(CONTEXT_SYSTEM);
747 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
748 $data->courseid = $this->get_courseid();
750 // outcome doesn't exist, create
751 $newitemid = $DB->insert_record('grade_outcomes', $data);
752 $restorefiles = true; // We'll restore the files
754 // scale exists, use it
755 $newitemid = $outdb->id;
757 // Set the corresponding grade_outcomes_courses record
758 $outcourserec = new stdclass();
759 $outcourserec->courseid = $this->get_courseid();
760 $outcourserec->outcomeid = $newitemid;
761 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
762 $DB->insert_record('grade_outcomes_courses', $outcourserec);
764 // Save the id mapping (with files support at system context)
765 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
768 protected function after_execute() {
769 // Add outcomes related files, matching with "outcome" mappings
770 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
775 * Structure step that will read the section.xml creating/updating sections
776 * as needed, rebuilding course cache and other friends
778 class restore_section_structure_step extends restore_structure_step {
780 protected function define_structure() {
781 return array(new restore_path_element('section', '/section'));
784 public function process_section($data) {
786 $data = (object)$data;
787 $oldid = $data->id; // We'll need this later
789 $restorefiles = false;
791 // Look for the section
792 $section = new stdclass();
793 $section->course = $this->get_courseid();
794 $section->section = $data->number;
795 // Section doesn't exist, create it with all the info from backup
796 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
797 $section->name = $data->name;
798 $section->summary = $data->summary;
799 $section->summaryformat = $data->summaryformat;
800 $section->sequence = '';
801 $section->visible = $data->visible;
802 $newitemid = $DB->insert_record('course_sections', $section);
803 $restorefiles = true;
805 // Section exists, update non-empty information
807 $section->id = $secrec->id;
808 if (empty($secrec->name)) {
809 $section->name = $data->name;
811 if (empty($secrec->summary)) {
812 $section->summary = $data->summary;
813 $section->summaryformat = $data->summaryformat;
814 $restorefiles = true;
816 $DB->update_record('course_sections', $section);
817 $newitemid = $secrec->id;
820 // Annotate the section mapping, with restorefiles option if needed
821 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
823 // If needed, adjust course->numsections
824 if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
825 if ($numsections < $section->section) {
826 $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
831 protected function after_execute() {
832 // Add section related files, with 'course_section' itemid to match
833 $this->add_related_files('course', 'section', 'course_section');
839 * Structure step that will read the course.xml file, loading it and performing
840 * various actions depending of the site/restore settings. Note that target
841 * course always exist before arriving here so this step will be updating
842 * the course record (never inserting)
844 class restore_course_structure_step extends restore_structure_step {
846 protected function define_structure() {
848 $course = new restore_path_element('course', '/course', true); // Grouped
849 $category = new restore_path_element('category', '/course/category');
850 $tag = new restore_path_element('tag', '/course/tags/tag');
851 $allowed = new restore_path_element('allowed', '/course/allowed_modules/module');
853 return array($course, $category, $tag, $allowed);
857 * Processing functions go here
859 * @global moodledatabase $DB
860 * @param stdClass $data
862 public function process_course($data) {
865 $data = (object)$data;
866 $coursetags = isset($data->tags['tag']) ? $data->tags['tag'] : array();
867 $coursemodules = isset($data->allowed_modules['module']) ? $data->allowed_modules['module'] : array();
868 $oldid = $data->id; // We'll need this later
870 $fullname = $this->get_setting_value('course_fullname');
871 $shortname = $this->get_setting_value('course_shortname');
872 $startdate = $this->get_setting_value('course_startdate');
874 // Calculate final course names, to avoid dupes
875 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
877 // Need to change some fields before updating the course record
878 $data->id = $this->get_courseid();
879 $data->fullname = $fullname;
880 $data->shortname= $shortname;
881 $data->idnumber = '';
883 // Category is set by UI when choosing the destination
884 unset($data->category);
886 $data->startdate= $this->apply_date_offset($data->startdate);
887 if ($data->defaultgroupingid) {
888 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
890 if (empty($CFG->enablecompletion)) {
891 $data->enablecompletion = 0;
892 $data->completionstartonenrol = 0;
893 $data->completionnotify = 0;
895 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
896 if (!array_key_exists($data->lang, $languages)) {
899 $themes = get_list_of_themes(); // Get themes for quick search later
900 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
904 // Course record ready, update it
905 $DB->update_record('course', $data);
907 // Set course mapping
908 $this->set_mapping('course', $oldid, $data->id);
911 if (!empty($CFG->usetags) && isset($coursetags)) { // if enabled in server and present in backup
913 foreach ($coursetags as $coursetag) {
914 $coursetag = (object)$coursetag;
915 $tags[] = $coursetag->rawname;
917 tag_set('course', $this->get_courseid(), $tags);
919 // Course allowed modules
920 if (!empty($data->restrictmodules) && !empty($coursemodules)) {
921 $available = get_plugin_list('mod');
922 foreach ($coursemodules as $coursemodule) {
923 $mname = $coursemodule['modulename'];
924 if (array_key_exists($mname, $available)) {
925 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
926 $rec = new stdclass();
927 $rec->course = $this->get_courseid();
928 $rec->module = $module->id;
929 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
930 $DB->insert_record('course_allowed_modules', $rec);
937 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
940 protected function after_execute() {
941 // Add course related files, without itemid to match
942 $this->add_related_files('course', 'summary', null);
943 $this->add_related_files('course', 'legacy', null);
949 * Structure step that will read the roles.xml file (at course/activity/block levels)
950 * containig all the role_assignments and overrides for that context. If corresponding to
951 * one mapped role, they will be applied to target context. Will observe the role_assignments
952 * setting to decide if ras are restored.
953 * Note: only ras with component == null are restored as far as the any ra with component
954 * is handled by one enrolment plugin, hence it will createt the ras later
956 class restore_ras_and_caps_structure_step extends restore_structure_step {
958 protected function define_structure() {
962 // Observe the role_assignments setting
963 if ($this->get_setting_value('role_assignments')) {
964 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
966 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
971 public function process_assignment($data) {
974 $data = (object)$data;
976 // Check roleid, userid are one of the mapped ones
977 $newroleid = $this->get_mappingid('role', $data->roleid);
978 $newuserid = $this->get_mappingid('user', $data->userid);
979 // If newroleid and newuserid and component is empty and context valid assign via API (handles dupes and friends)
980 if ($newroleid && $newuserid && empty($data->component) && $this->task->get_contextid()) {
981 // Only assign roles to not deleted users
982 if ($DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
983 // TODO: role_assign() needs one userid param to be able to specify our restore userid
984 role_assign($newroleid, $newuserid, $this->task->get_contextid());
989 public function process_override($data) {
990 $data = (object)$data;
992 // Check roleid is one of the mapped ones
993 $newroleid = $this->get_mappingid('role', $data->roleid);
994 // If newroleid and context are valid assign it via API (it handles dupes and so on)
995 if ($newroleid && $this->task->get_contextid()) {
996 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
997 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
998 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1004 * This structure steps restores the enrol plugins and their underlying
1005 * enrolments, performing all the mappings and/or movements required
1007 class restore_enrolments_structure_step extends restore_structure_step {
1009 protected function define_structure() {
1013 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1014 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1019 public function process_enrol($data) {
1022 $data = (object)$data;
1023 $oldid = $data->id; // We'll need this later
1025 // TODO: Just one quick process of manual enrol_plugin. Add the rest (complex ones) and fix this
1026 if ($data->enrol !== 'manual') {
1027 debugging("Skipping '{$data->enrol}' enrolment plugin. Must be implemented", DEBUG_DEVELOPER);
1031 // Perform various checks to decide what to do with the enrol plugin
1032 $installed = array_key_exists($data->enrol, enrol_get_plugins(false));
1033 $enabled = enrol_is_enabled($data->enrol);
1035 $roleid = $this->get_mappingid('role', $data->roleid);
1036 if ($rec = $DB->get_record('enrol', array('courseid' => $this->get_courseid(), 'enrol' => $data->enrol))) {
1039 // If installed and enabled, continue processing
1040 if ($installed && $enabled) {
1041 // If not exists in course and we have a target role mapping
1042 if (!$exists && $roleid) {
1043 $data->roleid = $roleid;
1044 $enrol = enrol_get_plugin($data->enrol);
1045 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1046 $newitemid = $enrol->add_instance($courserec, array($data));
1048 // Already exists, user it for enrolments
1050 $newitemid = $exists;
1053 // Not installed and enabled, map to 0
1057 // Perform the simple mapping and done
1058 $this->set_mapping('enrol', $oldid, $newitemid);
1061 public function process_enrolment($data) {
1064 $data = (object)$data;
1066 // Process only if parent instance have been mapped
1067 if ($enrolid = $this->get_new_parentid('enrol')) {
1068 // And only if user is a mapped one
1069 if ($userid = $this->get_mappingid('user', $data->userid)) {
1070 // TODO: Surely need to use API (enrol_user) here, instead of the current low-level impl
1071 // TODO: Note enrol_user() sticks to $USER->id (need to add userid param)
1072 $enrolment = new stdclass();
1073 $enrolment->enrolid = $enrolid;
1074 $enrolment->userid = $userid;
1075 if (!$DB->record_exists('user_enrolments', (array)$enrolment)) {
1076 $enrolment->status = $data->status;
1077 $enrolment->timestart = $data->timestart;
1078 $enrolment->timeend = $data->timeend;
1079 $enrolment->modifierid = $this->task->get_userid();
1080 $enrolment->timecreated = time();
1081 $enrolment->timemodified = 0;
1082 $DB->insert_record('user_enrolments', $enrolment);
1091 * This structure steps restores the filters and their configs
1093 class restore_filters_structure_step extends restore_structure_step {
1095 protected function define_structure() {
1099 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1100 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1105 public function process_active($data) {
1107 $data = (object)$data;
1109 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1112 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1115 public function process_config($data) {
1117 $data = (object)$data;
1119 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1122 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1128 * This structure steps restores the comments
1129 * Note: Cannot use the comments API because defaults to USER->id.
1130 * That should change allowing to pass $userid
1132 class restore_comments_structure_step extends restore_structure_step {
1134 protected function define_structure() {
1138 $paths[] = new restore_path_element('comment', '/comments/comment');
1143 public function process_comment($data) {
1146 $data = (object)$data;
1148 // First of all, if the comment has some itemid, ask to the task what to map
1150 if ($data->itemid) {
1151 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1152 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
1154 // Only restore the comment if has no mapping OR we have found the matching mapping
1155 if (!$mapping || $data->itemid) {
1156 // Only if user mapping and context
1157 $data->userid = $this->get_mappingid('user', $data->userid);
1158 if ($data->userid && $this->task->get_contextid()) {
1159 $data->contextid = $this->task->get_contextid();
1160 // Only if there is another comment with same context/user/timecreated
1161 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1162 if (!$DB->record_exists('comments', $params)) {
1163 $DB->insert_record('comments', $data);
1171 * This structure step restores the grade items associated with one activity
1172 * All the grade items are made child of the "course" grade item but the original
1173 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
1174 * the complete gradebook (categories and calculations), that information is
1177 class restore_activity_grades_structure_step extends restore_structure_step {
1179 protected function define_structure() {
1182 $userinfo = $this->get_setting_value('userinfo');
1184 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
1185 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
1187 $paths[] = new restore_path_element('grade_grade',
1188 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
1193 protected function process_grade_item($data) {
1195 $data = (object)($data);
1196 $oldid = $data->id; // We'll need these later
1197 $oldparentid = $data->categoryid;
1199 // make sure top course category exists, all grade items will be associated
1200 // to it. Later, if restoring the whole gradebook, categories will be introduced
1201 $coursecat = grade_category::fetch_course_category($this->get_courseid());
1202 $coursecatid = $coursecat->id; // Get the categoryid to be used
1205 $data->categoryid = $coursecatid;
1206 $data->courseid = $this->get_courseid();
1207 $data->iteminstance = $this->task->get_activityid();
1208 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
1209 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
1210 // so the best is to keep the ones already in the gradebook
1211 // Potential problem: duplicates if same items are restored more than once. :-(
1212 // This needs to be fixed in some way (outcomes & activities with multiple items)
1213 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
1214 // In any case, verify always for uniqueness
1215 $data->idnumber = grade_verify_idnumber($data->idnumber, $this->get_courseid()) ? $data->idnumber : null;
1216 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1217 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
1218 $data->timecreated = $this->apply_date_offset($data->timecreated);
1219 $data->timemodified = $this->apply_date_offset($data->timemodified);
1221 $gradeitem = new grade_item($data);
1222 $gradeitem->insert('restore');
1224 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
1225 $gradeitem->sortorder = $data->sortorder;
1226 $gradeitem->update('restore');
1228 // Set mapping, saving the original category id into parentitemid
1229 // gradebook restore (final task) will need it to reorganise items
1230 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
1233 protected function process_grade_grade($data) {
1234 $data = (object)($data);
1237 $data->itemid = $this->get_new_parentid('grade_item');
1238 $data->userid = $this->get_mappingid('user', $data->userid);
1239 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
1240 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
1241 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
1242 $data->overridden = $this->apply_date_offset($data->overridden);
1244 $grade = new grade_grade($data);
1245 $grade->insert('restore');
1246 // no need to save any grade_grade mapping
1250 * process activity grade_letters. Note that, while these are possible,
1251 * because grade_letters are contextid based, in proctice, only course
1252 * context letters can be defined. So we keep here this method knowing
1253 * it won't be executed ever. gradebook restore will restore course letters.
1255 protected function process_grade_letter($data) {
1258 $data = (object)$data;
1260 $data->contextid = $this->task->get_contextid();
1261 $newitemid = $DB->insert_record('grade_letters', $data);
1262 // no need to save any grade_letter mapping
1268 * This structure steps restores one instance + positions of one block
1269 * Note: Positions corresponding to one existing context are restored
1270 * here, but all the ones having unknown contexts are sent to backup_ids
1271 * for a later chance to be restored at the end (final task)
1273 class restore_block_instance_structure_step extends restore_structure_step {
1275 protected function define_structure() {
1279 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
1280 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
1285 public function process_block($data) {
1288 $data = (object)$data; // Handy
1289 $oldcontextid = $data->contextid;
1291 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1293 // Look for the parent contextid
1294 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1295 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1298 // If there is already one block of that type in the parent context
1299 // and the block is not multiple, stop processing
1300 if ($DB->record_exists_sql("SELECT bi.id
1301 FROM {block_instances} bi
1302 JOIN {block} b ON b.name = bi.blockname
1303 WHERE bi.parentcontextid = ?
1304 AND bi.blockname = ?
1305 AND b.multiple = 0", array($data->parentcontextid, $data->blockname))) {
1309 // If there is already one block of that type in the parent context
1310 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
1313 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
1314 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
1315 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
1316 if ($birecs = $DB->get_records('block_instances', $params)) {
1317 foreach($birecs as $birec) {
1318 if ($birec->configdata == $data->configdata) {
1324 // Set task old contextid, blockid and blockname once we know them
1325 $this->task->set_old_contextid($oldcontextid);
1326 $this->task->set_old_blockid($oldid);
1327 $this->task->set_blockname($data->blockname);
1329 // Let's look for anything within configdata neededing processing
1330 // (nulls and uses of legacy file.php)
1331 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1332 $configdata = (array)unserialize(base64_decode($data->configdata));
1333 foreach ($configdata as $attribute => $value) {
1334 if (in_array($attribute, $attrstotransform)) {
1335 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
1338 $data->configdata = base64_encode(serialize((object)$configdata));
1341 // Create the block instance
1342 $newitemid = $DB->insert_record('block_instances', $data);
1343 // Save the mapping (with restorefiles support)
1344 $this->set_mapping('block_instance', $oldid, $newitemid, true);
1345 // Create the block context
1346 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
1347 // Save the block contexts mapping and sent it to task
1348 $this->set_mapping('context', $oldcontextid, $newcontextid);
1349 $this->task->set_contextid($newcontextid);
1350 $this->task->set_blockid($newitemid);
1352 // Restore block fileareas if declared
1353 $component = 'block_' . $this->task->get_blockname();
1354 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
1355 $this->add_related_files($component, $filearea, null);
1358 // Process block positions, creating them or accumulating for final step
1359 foreach($positions as $position) {
1360 $position = (object)$position;
1361 $position->blockinstanceid = $newitemid; // The instance is always the restored one
1362 // If position is for one already mapped (known) contextid
1363 // process it now, creating the position
1364 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
1365 $position->contextid = $newpositionctxid;
1366 // Create the block position
1367 $DB->insert_record('block_positions', $position);
1369 // The position belongs to an unknown context, send it to backup_ids
1370 // to process them as part of the final steps of restore. We send the
1371 // whole $position object there, hence use the low level method.
1373 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
1380 * Structure step to restore common course_module information
1382 * This step will process the module.xml file for one activity, in order to restore
1383 * the corresponding information to the course_modules table, skipping various bits
1384 * of information based on CFG settings (groupings, completion...) in order to fullfill
1385 * all the reqs to be able to create the context to be used by all the rest of steps
1386 * in the activity restore task
1388 class restore_module_structure_step extends restore_structure_step {
1390 protected function define_structure() {
1395 $paths[] = new restore_path_element('module', '/module');
1396 if ($CFG->enableavailability) {
1397 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
1403 protected function process_module($data) {
1406 $data = (object)$data;
1409 $data->course = $this->task->get_courseid();
1410 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
1411 // Map section (first try by course_section mapping match. Useful in course and section restores)
1412 $data->section = $this->get_mappingid('course_section', $data->sectionid);
1413 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
1415 'course' => $this->get_courseid(),
1416 'section' => $data->sectionnumber);
1417 $data->section = $DB->get_field('course_sections', 'id', $params);
1419 if (!$data->section) { // sectionnumber failed, try to get first section in course
1421 'course' => $this->get_courseid());
1422 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
1424 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
1425 $sectionrec = array(
1426 'course' => $this->get_courseid(),
1428 $DB->insert_record('course_sections', $sectionrec); // section 0
1429 $sectionrec = array(
1430 'course' => $this->get_courseid(),
1432 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
1434 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
1435 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
1436 $data->groupmembersonly = 0;
1438 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
1439 $data->idnumber = '';
1441 if (empty($CFG->enablecompletion)) { // completion
1442 $data->completion = 0;
1443 $data->completiongradeitemnumber = null;
1444 $data->completionview = 0;
1445 $data->completionexpected = 0;
1447 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
1449 if (empty($CFG->enableavailability)) {
1450 $data->availablefrom = 0;
1451 $data->availableuntil = 0;
1452 $data->showavailability = 0;
1454 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
1455 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
1457 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
1459 // course_module record ready, insert it
1460 $newitemid = $DB->insert_record('course_modules', $data);
1462 $this->set_mapping('course_module', $oldid, $newitemid);
1463 // set the new course_module id in the task
1464 $this->task->set_moduleid($newitemid);
1465 // we can now create the context safely
1466 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
1467 // set the new context id in the task
1468 $this->task->set_contextid($ctxid);
1469 // update sequence field in course_section
1470 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
1471 $sequence .= ',' . $newitemid;
1473 $sequence = $newitemid;
1475 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
1479 protected function process_availability($data) {
1480 $data = (object)$data;
1481 // Simply going to store the whole availability record now, we'll process
1482 // all them later in the final task (once all actvivities have been restored)
1483 // Let's call the low level one to be able to store the whole object
1484 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
1485 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
1490 * Structure step that will process the user activity completion
1491 * information if all these conditions are met:
1492 * - Target site has completion enabled ($CFG->enablecompletion)
1493 * - Activity includes completion info (file_exists)
1495 class restore_userscompletion_structure_step extends restore_structure_step {
1498 * To conditionally decide if this step must be executed
1499 * Note the "settings" conditions are evaluated in the
1500 * corresponding task. Here we check for other conditions
1501 * not being restore settings (files, site settings...)
1503 protected function execute_condition() {
1506 // Completion disabled in this site, don't execute
1507 if (empty($CFG->enablecompletion)) {
1511 // No user completion info found, don't execute
1512 $fullpath = $this->task->get_taskbasepath();
1513 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1514 if (!file_exists($fullpath)) {
1518 // Arrived here, execute the step
1522 protected function define_structure() {
1526 $paths[] = new restore_path_element('completion', '/completions/completion');
1531 protected function process_completion($data) {
1534 $data = (object)$data;
1536 $data->coursemoduleid = $this->task->get_moduleid();
1537 $data->userid = $this->get_mappingid('user', $data->userid);
1538 $data->timemodified = $this->apply_date_offset($data->timemodified);
1540 $DB->insert_record('course_modules_completion', $data);
1545 * Abstract structure step, parent of all the activity structure steps. Used to suuport
1546 * the main <activity ...> tag and process it. Also provides subplugin support for
1549 abstract class restore_activity_structure_step extends restore_structure_step {
1551 protected function add_subplugin_structure($subplugintype, $element) {
1555 // Check the requested subplugintype is a valid one
1556 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
1557 if (!file_exists($subpluginsfile)) {
1558 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
1560 include($subpluginsfile);
1561 if (!array_key_exists($subplugintype, $subplugins)) {
1562 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
1564 // Get all the restore path elements, looking across all the subplugin dirs
1565 $subpluginsdirs = get_plugin_list($subplugintype);
1566 foreach ($subpluginsdirs as $name => $subpluginsdir) {
1567 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
1568 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
1569 if (file_exists($restorefile)) {
1570 require_once($restorefile);
1571 $restoresubplugin = new $classname($subplugintype, $name, $this);
1572 // Add subplugin paths to the step
1573 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
1579 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
1580 * have the parent task available for wrapping purposes (get course/context....)
1582 public function get_task() {
1587 * Adds support for the 'activity' path that is common to all the activities
1588 * and will be processed globally here
1590 protected function prepare_activity_structure($paths) {
1592 $paths[] = new restore_path_element('activity', '/activity');
1598 * Process the activity path, informing the task about various ids, needed later
1600 protected function process_activity($data) {
1601 $data = (object)$data;
1602 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
1603 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
1604 $this->task->set_old_activityid($data->id); // Save old activityid in task
1608 * This must be invoked inmediately after creating the "module" activity record (forum, choice...)
1609 * and will adjust the new activity id (the instance) in various places
1611 protected function apply_activity_instance($newitemid) {
1614 $this->task->set_activityid($newitemid); // Save activity id in task
1615 // Apply the id to course_sections->instanceid
1616 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
1617 // Do the mapping for modulename, preparing it for files by oldcontext
1618 $modulename = $this->task->get_modulename();
1619 $oldid = $this->task->get_old_activityid();
1620 $this->set_mapping($modulename, $oldid, $newitemid, true);