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);
50 // Create the old-course-id to new-course-id mapping, we need that available since the beginning
51 $itemid = $this->task->get_old_courseid();
52 $newitemid = $this->get_courseid();
53 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
59 * delete the temp dir used by backup/restore (conditionally),
60 * delete old directories and drop temp ids table
62 class restore_drop_and_clean_temp_stuff extends restore_execution_step {
64 protected function define_execution() {
66 restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
67 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
68 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
69 backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
75 * Restore calculated grade items, grade categories etc
77 class restore_gradebook_structure_step extends restore_structure_step {
80 * To conditionally decide if this step must be executed
81 * Note the "settings" conditions are evaluated in the
82 * corresponding task. Here we check for other conditions
83 * not being restore settings (files, site settings...)
85 protected function execute_condition() {
88 // No gradebook info found, don't execute
89 $fullpath = $this->task->get_taskbasepath();
90 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
91 if (!file_exists($fullpath)) {
95 // Some module present in backup file isn't available to restore
96 // in this site, don't execute
97 if ($this->task->is_missing_modules()) {
101 // Some activity has been excluded to be restored, don't execute
102 if ($this->task->is_excluding_activities()) {
106 // There should only be one grade category (the 1 associated with the course itself)
107 // If other categories already exist we're restoring into an existing course.
108 // Restoring categories into a course with an existing category structure is unlikely to go well
109 $category = new stdclass();
110 $category->courseid = $this->get_courseid();
111 $catcount = $DB->count_records('grade_categories', (array)$category);
116 // Arrived here, execute the step
120 protected function define_structure() {
122 $userinfo = $this->task->get_setting_value('users');
124 $paths[] = new restore_path_element('gradebook', '/gradebook');
125 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
126 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
128 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
130 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
131 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
136 protected function process_gradebook($data) {
139 protected function process_grade_item($data) {
142 $data = (object)$data;
145 $data->course = $this->get_courseid();
147 $data->courseid = $this->get_courseid();
149 //manual grade items store category id in categoryid
150 if ($data->itemtype=='manual') {
151 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid);
152 } //course and category grade items store their category id in iteminstance
153 else if ($data->itemtype=='course' || $data->itemtype=='category') {
154 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance);
157 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
158 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
160 $data->locktime = $this->apply_date_offset($data->locktime);
161 $data->timecreated = $this->apply_date_offset($data->timecreated);
162 $data->timemodified = $this->apply_date_offset($data->timemodified);
164 $coursecategory = $newitemid = null;
165 //course grade item should already exist so updating instead of inserting
166 if($data->itemtype=='course') {
168 //get the ID of the already created grade item
169 $gi = new stdclass();
170 $gi->courseid = $this->get_courseid();
172 $gi->itemtype = $data->itemtype;
173 if ($data->itemtype=='course') {
174 //need to get the id of the grade_category that was automatically created for the course
175 $category = new stdclass();
176 $category->courseid = $this->get_courseid();
177 $category->parent = null;
178 //course category fullname starts out as ? but may be edited
179 //$category->fullname = '?';
181 $coursecategory = $DB->get_record('grade_categories', (array)$category);
182 $gi->iteminstance = $coursecategory->id;
185 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
186 if (!empty($existinggradeitem)) {
187 $data->id = $newitemid = $existinggradeitem->id;
188 $DB->update_record('grade_items', $data);
192 if (empty($newitemid)) {
193 //in case we found the course category but still need to insert the course grade item
194 if ($data->itemtype=='course' && !empty($coursecategory)) {
195 $data->iteminstance = $coursecategory->id;
198 $newitemid = $DB->insert_record('grade_items', $data);
200 $this->set_mapping('grade_item', $oldid, $newitemid);
203 protected function process_grade_grade($data) {
206 $data = (object)$data;
209 $data->itemid = $this->get_new_parentid('grade_item');
211 $data->userid = $this->get_mappingid('user', $data->userid);
212 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
213 $data->locktime = $this->apply_date_offset($data->locktime);
214 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
215 $data->overridden = $this->apply_date_offset($data->overridden);
216 $data->timecreated = $this->apply_date_offset($data->timecreated);
217 $data->timemodified = $this->apply_date_offset($data->timemodified);
219 $newitemid = $DB->insert_record('grade_grades', $data);
220 //$this->set_mapping('grade_grade', $oldid, $newitemid);
222 protected function process_grade_category($data) {
225 $data = (object)$data;
228 $data->course = $this->get_courseid();
229 $data->courseid = $data->course;
231 $data->timecreated = $this->apply_date_offset($data->timecreated);
232 $data->timemodified = $this->apply_date_offset($data->timemodified);
235 //no parent means a course level grade category. That may have been created when the course was created
236 if(empty($data->parent)) {
237 //parent was being saved as 0 when it should be null
238 $data->parent = null;
240 //get the already created course level grade category
241 $category = new stdclass();
242 $category->courseid = $this->get_courseid();
244 $coursecategory = $DB->get_record('grade_categories', (array)$category);
245 if (!empty($coursecategory)) {
246 $data->id = $newitemid = $coursecategory->id;
247 $DB->update_record('grade_categories', $data);
251 //need to insert a course category
252 if (empty($newitemid)) {
253 $newitemid = $DB->insert_record('grade_categories', $data);
255 $this->set_mapping('grade_category', $oldid, $newitemid);
257 protected function process_grade_letter($data) {
260 $data = (object)$data;
263 $data->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
265 $newitemid = $DB->insert_record('grade_letters', $data);
266 $this->set_mapping('grade_letter', $oldid, $newitemid);
268 protected function process_grade_setting($data) {
271 $data = (object)$data;
274 $data->courseid = $this->get_courseid();
276 $newitemid = $DB->insert_record('grade_settings', $data);
277 //$this->set_mapping('grade_setting', $oldid, $newitemid);
280 //put all activity grade items in the correct grade category and mark all for recalculation
281 protected function after_execute() {
285 'backupid' => $this->get_restoreid(),
286 'itemname' => 'grade_item'//,
287 //'itemid' => $itemid
289 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
292 foreach($rs as $grade_item_backup) {
293 $updateobj = new stdclass();
294 $updateobj->id = $grade_item_backup->newitemid;
296 //if this is an activity grade item that needs to be put back in its correct category
297 if (!empty($grade_item_backup->parentitemid)) {
298 $updateobj->categoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid);
300 //mark course and category items as needing to be recalculated
301 $updateobj->needsupdate=1;
303 $DB->update_record('grade_items', $updateobj);
308 //need to correct the grade category path and parent
310 'courseid' => $this->get_courseid()
312 $grade_category = new stdclass();
314 $rs = $DB->get_recordset('grade_categories', $conditions);
316 //get all the parents correct first as grade_category::build_path() loads category parents from the DB
317 foreach($rs as $gc) {
318 if (!empty($gc->parent)) {
319 $grade_category->id = $gc->id;
320 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
321 $DB->update_record('grade_categories', $grade_category);
325 if (isset($grade_category->parent)) {
326 unset($grade_category->parent);
330 $rs = $DB->get_recordset('grade_categories', $conditions);
332 //now we can rebuild all the paths
333 foreach($rs as $gc) {
334 $grade_category->id = $gc->id;
335 $grade_category->path = grade_category::build_path($gc);
336 $DB->update_record('grade_categories', $grade_category);
344 * decode all the interlinks present in restored content
345 * relying 100% in the restore_decode_processor that handles
346 * both the contents to modify and the rules to be applied
348 class restore_decode_interlinks extends restore_execution_step {
350 protected function define_execution() {
351 // Get the decoder (from the plan)
352 $decoder = $this->task->get_decoder();
353 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
354 // And launch it, everything will be processed
360 * first, ensure that we have no gaps in section numbers
361 * and then, rebuid the course cache
363 class restore_rebuild_course_cache extends restore_execution_step {
365 protected function define_execution() {
368 // Although there is some sort of auto-recovery of missing sections
369 // present in course/formats... here we check that all the sections
370 // from 0 to MAX(section->section) exist, creating them if necessary
371 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
372 // Iterate over all sections
373 for ($i = 0; $i <= $maxsection; $i++) {
374 // If the section $i doesn't exist, create it
375 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
377 'course' => $this->get_courseid(),
379 $DB->insert_record('course_sections', $sectionrec); // missing section created
383 // Rebuild cache now that all sections are in place
384 rebuild_course_cache($this->get_courseid());
389 * Review all the tasks having one after_restore method
390 * executing it to perform some final adjustments of information
391 * not available when the task was executed.
393 class restore_execute_after_restore extends restore_execution_step {
395 protected function define_execution() {
397 // Simply call to the execute_after_restore() method of the task
398 // that always is the restore_final_task
399 $this->task->launch_execute_after_restore();
405 * Review all the (pending) block positions in backup_ids, matching by
406 * contextid, creating positions as needed. This is executed by the
407 * final task, once all the contexts have been created
409 class restore_review_pending_block_positions extends restore_execution_step {
411 protected function define_execution() {
414 // Get all the block_position objects pending to match
415 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
416 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
417 // Process block positions, creating them or accumulating for final step
418 foreach($rs as $posrec) {
419 // Get the complete position object (stored as info)
420 $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
421 // If position is for one already mapped (known) contextid
422 // process it now, creating the position, else nothing to
423 // do, position finally discarded
424 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
425 $position->contextid = $newctx->newitemid;
426 // Create the block position
427 $DB->insert_record('block_positions', $position);
435 * Process all the saved module availability records in backup_ids, matching
436 * course modules and grade item id once all them have been already restored.
437 * only if all matchings are satisfied the availability condition will be created.
438 * At the same time, it is required for the site to have that functionality enabled.
440 class restore_process_course_modules_availability extends restore_execution_step {
442 protected function define_execution() {
445 // Site hasn't availability enabled
446 if (empty($CFG->enableavailability)) {
450 // Get all the module_availability objects to process
451 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
452 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
453 // Process availabilities, creating them if everything matches ok
454 foreach($rs as $availrec) {
455 $allmatchesok = true;
456 // Get the complete availabilityobject
457 $availability = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_availability', $availrec->itemid)->info;
458 // Map the sourcecmid if needed and possible
459 if (!empty($availability->sourcecmid)) {
460 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
462 $availability->sourcecmid = $newcm->newitemid;
464 $allmatchesok = false; // Failed matching, we won't create this availability rule
467 // Map the gradeitemid if needed and possible
468 if (!empty($availability->gradeitemid)) {
469 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
471 $availability->gradeitemid = $newgi->newitemid;
473 $allmatchesok = false; // Failed matching, we won't create this availability rule
476 if ($allmatchesok) { // Everything ok, create the availability rule
477 $DB->insert_record('course_modules_availability', $availability);
486 * Execution step that, *conditionally* (if there isn't preloaded information)
487 * will load the inforef files for all the included course/section/activity tasks
488 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
490 class restore_load_included_inforef_records extends restore_execution_step {
492 protected function define_execution() {
494 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
498 // Get all the included tasks
499 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
500 foreach ($tasks as $task) {
501 // Load the inforef.xml file if exists
502 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
503 if (file_exists($inforefpath)) {
504 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath); // Load each inforef file to temp_ids
511 * Execution step that will load all the needed files into backup_files_temp
512 * - info: contains the whole original object (times, names...)
513 * (all them being original ids as loaded from xml)
515 class restore_load_included_files extends restore_structure_step {
517 protected function define_structure() {
519 $file = new restore_path_element('file', '/files/file');
524 // Processing functions go here
525 public function process_file($data) {
527 $data = (object)$data; // handy
529 // load it if needed:
530 // - it it is one of the annotated inforef files (course/section/activity/block)
531 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
532 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
533 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
534 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
535 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
536 $data->component == 'grouping' || $data->component == 'grade' ||
537 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
538 if ($isfileref || $iscomponent) {
539 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
545 * Execution step that, *conditionally* (if there isn't preloaded information),
546 * will load all the needed roles to backup_temp_ids. They will be stored with
547 * "role" itemname. Also it will perform one automatic mapping to roles existing
548 * in the target site, based in permissions of the user performing the restore,
549 * archetypes and other bits. At the end, each original role will have its associated
550 * target role or 0 if it's going to be skipped. Note we wrap everything over one
551 * restore_dbops method, as far as the same stuff is going to be also executed
552 * by restore prechecks
554 class restore_load_and_map_roles extends restore_execution_step {
556 protected function define_execution() {
557 if ($this->task->get_preloaded_information()) { // if info is already preloaded
561 $file = $this->get_basepath() . '/roles.xml';
562 // Load needed toles to temp_ids
563 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
565 // Process roles, mapping/skipping. Any error throws exception
566 // Note we pass controller's info because it can contain role mapping information
567 // about manual mappings performed by UI
568 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);
573 * Execution step that, *conditionally* (if there isn't preloaded information
574 * and users have been selected in settings, will load all the needed users
575 * to backup_temp_ids. They will be stored with "user" itemname and with
576 * their original contextid as paremitemid
578 class restore_load_included_users extends restore_execution_step {
580 protected function define_execution() {
582 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
585 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
588 $file = $this->get_basepath() . '/users.xml';
589 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
594 * Execution step that, *conditionally* (if there isn't preloaded information
595 * and users have been selected in settings, will process all the needed users
596 * in order to decide and perform any action with them (create / map / error)
597 * Note: Any error will cause exception, as far as this is the same processing
598 * than the one into restore prechecks (that should have stopped process earlier)
600 class restore_process_included_users extends restore_execution_step {
602 protected function define_execution() {
604 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
607 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
610 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
615 * Execution step that will create all the needed users as calculated
616 * by @restore_process_included_users (those having newiteind = 0)
618 class restore_create_included_users extends restore_execution_step {
620 protected function define_execution() {
622 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->get_setting_value('user_files'), $this->task->get_userid());
627 * Structure step that will create all the needed groups and groupings
628 * by loading them from the groups.xml file performing the required matches.
629 * Note group members only will be added if restoring user info
631 class restore_groups_structure_step extends restore_structure_step {
633 protected function define_structure() {
635 $paths = array(); // Add paths here
637 $paths[] = new restore_path_element('group', '/groups/group');
638 if ($this->get_setting_value('users')) {
639 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
641 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
642 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
647 // Processing functions go here
648 public function process_group($data) {
651 $data = (object)$data; // handy
652 $data->courseid = $this->get_courseid();
654 $oldid = $data->id; // need this saved for later
656 $restorefiles = false; // Only if we end creating the group
658 // Search if the group already exists (by name & description) in the target course
659 $description_clause = '';
660 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
661 if (!empty($data->description)) {
662 $description_clause = ' AND ' .
663 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
664 $params['description'] = $data->description;
666 if (!$groupdb = $DB->get_record_sql("SELECT *
668 WHERE courseid = :courseid
669 AND name = :grname $description_clause", $params)) {
670 // group doesn't exist, create
671 $newitemid = $DB->insert_record('groups', $data);
672 $restorefiles = true; // We'll restore the files
674 // group exists, use it
675 $newitemid = $groupdb->id;
677 // Save the id mapping
678 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
681 public function process_member($data) {
684 $data = (object)$data; // handy
686 // get parent group->id
687 $data->groupid = $this->get_new_parentid('group');
689 // map user newitemid and insert if not member already
690 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
691 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
692 $DB->insert_record('groups_members', $data);
697 public function process_grouping($data) {
700 $data = (object)$data; // handy
701 $data->courseid = $this->get_courseid();
703 $oldid = $data->id; // need this saved for later
704 $restorefiles = false; // Only if we end creating the grouping
706 // Search if the grouping already exists (by name & description) in the target course
707 $description_clause = '';
708 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
709 if (!empty($data->description)) {
710 $description_clause = ' AND ' .
711 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
712 $params['description'] = $data->description;
714 if (!$groupingdb = $DB->get_record_sql("SELECT *
716 WHERE courseid = :courseid
717 AND name = :grname $description_clause", $params)) {
718 // grouping doesn't exist, create
719 $newitemid = $DB->insert_record('groupings', $data);
720 $restorefiles = true; // We'll restore the files
722 // grouping exists, use it
723 $newitemid = $groupingdb->id;
725 // Save the id mapping
726 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
729 public function process_grouping_group($data) {
732 $data = (object)$data;
734 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
735 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
736 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
739 protected function after_execute() {
740 // Add group related files, matching with "group" mappings
741 $this->add_related_files('group', 'icon', 'group');
742 $this->add_related_files('group', 'description', 'group');
743 // Add grouping related files, matching with "grouping" mappings
744 $this->add_related_files('grouping', 'description', 'grouping');
750 * Structure step that will create all the needed scales
751 * by loading them from the scales.xml
753 class restore_scales_structure_step extends restore_structure_step {
755 protected function define_structure() {
757 $paths = array(); // Add paths here
758 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
762 protected function process_scale($data) {
765 $data = (object)$data;
767 $restorefiles = false; // Only if we end creating the group
769 $oldid = $data->id; // need this saved for later
771 // Look for scale (by 'scale' both in standard (course=0) and current course
772 // with priority to standard scales (ORDER clause)
773 // scale is not course unique, use get_record_sql to suppress warning
774 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
775 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
776 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
777 if (!$scadb = $DB->get_record_sql("SELECT *
779 WHERE courseid IN (0, :courseid)
780 AND $compare_scale_clause
781 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
782 // Remap the user if possible, defaut to user performing the restore if not
783 $userid = $this->get_mappingid('user', $data->userid);
784 $data->userid = $userid ? $userid : $this->task->get_userid();
785 // Remap the course if course scale
786 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
787 // If global scale (course=0), check the user has perms to create it
788 // falling to course scale if not
789 $systemctx = get_context_instance(CONTEXT_SYSTEM);
790 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
791 $data->courseid = $this->get_courseid();
793 // scale doesn't exist, create
794 $newitemid = $DB->insert_record('scale', $data);
795 $restorefiles = true; // We'll restore the files
797 // scale exists, use it
798 $newitemid = $scadb->id;
800 // Save the id mapping (with files support at system context)
801 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
804 protected function after_execute() {
805 // Add scales related files, matching with "scale" mappings
806 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
812 * Structure step that will create all the needed outocomes
813 * by loading them from the outcomes.xml
815 class restore_outcomes_structure_step extends restore_structure_step {
817 protected function define_structure() {
819 $paths = array(); // Add paths here
820 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
824 protected function process_outcome($data) {
827 $data = (object)$data;
829 $restorefiles = false; // Only if we end creating the group
831 $oldid = $data->id; // need this saved for later
833 // Look for outcome (by shortname both in standard (courseid=null) and current course
834 // with priority to standard outcomes (ORDER clause)
835 // outcome is not course unique, use get_record_sql to suppress warning
836 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
837 if (!$outdb = $DB->get_record_sql('SELECT *
838 FROM {grade_outcomes}
839 WHERE shortname = :shortname
840 AND (courseid = :courseid OR courseid IS NULL)
841 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
843 $userid = $this->get_mappingid('user', $data->usermodified);
844 $data->usermodified = $userid ? $userid : $this->task->get_userid();
846 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
847 // Remap the course if course outcome
848 $data->courseid = $data->courseid ? $this->get_courseid() : null;
849 // If global outcome (course=null), check the user has perms to create it
850 // falling to course outcome if not
851 $systemctx = get_context_instance(CONTEXT_SYSTEM);
852 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
853 $data->courseid = $this->get_courseid();
855 // outcome doesn't exist, create
856 $newitemid = $DB->insert_record('grade_outcomes', $data);
857 $restorefiles = true; // We'll restore the files
859 // scale exists, use it
860 $newitemid = $outdb->id;
862 // Set the corresponding grade_outcomes_courses record
863 $outcourserec = new stdclass();
864 $outcourserec->courseid = $this->get_courseid();
865 $outcourserec->outcomeid = $newitemid;
866 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
867 $DB->insert_record('grade_outcomes_courses', $outcourserec);
869 // Save the id mapping (with files support at system context)
870 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
873 protected function after_execute() {
874 // Add outcomes related files, matching with "outcome" mappings
875 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
880 * Execution step that, *conditionally* (if there isn't preloaded information
881 * will load all the question categories and questions (header info only)
882 * to backup_temp_ids. They will be stored with "question_category" and
883 * "question" itemnames and with their original contextid and question category
886 class restore_load_categories_and_questions extends restore_execution_step {
888 protected function define_execution() {
890 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
893 $file = $this->get_basepath() . '/questions.xml';
894 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
899 * Execution step that, *conditionally* (if there isn't preloaded information)
900 * will process all the needed categories and questions
901 * in order to decide and perform any action with them (create / map / error)
902 * Note: Any error will cause exception, as far as this is the same processing
903 * than the one into restore prechecks (that should have stopped process earlier)
905 class restore_process_categories_and_questions extends restore_execution_step {
907 protected function define_execution() {
909 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
912 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
917 * Structure step that will read the section.xml creating/updating sections
918 * as needed, rebuilding course cache and other friends
920 class restore_section_structure_step extends restore_structure_step {
922 protected function define_structure() {
923 $section = new restore_path_element('section', '/section');
925 // Apply for 'format' plugins optional paths at section level
926 $this->add_plugin_structure('format', $section);
928 return array($section);
931 public function process_section($data) {
933 $data = (object)$data;
934 $oldid = $data->id; // We'll need this later
936 $restorefiles = false;
938 // Look for the section
939 $section = new stdclass();
940 $section->course = $this->get_courseid();
941 $section->section = $data->number;
942 // Section doesn't exist, create it with all the info from backup
943 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
944 $section->name = $data->name;
945 $section->summary = $data->summary;
946 $section->summaryformat = $data->summaryformat;
947 $section->sequence = '';
948 $section->visible = $data->visible;
949 $newitemid = $DB->insert_record('course_sections', $section);
950 $restorefiles = true;
952 // Section exists, update non-empty information
954 $section->id = $secrec->id;
955 if (empty($secrec->name)) {
956 $section->name = $data->name;
958 if (empty($secrec->summary)) {
959 $section->summary = $data->summary;
960 $section->summaryformat = $data->summaryformat;
961 $restorefiles = true;
963 $DB->update_record('course_sections', $section);
964 $newitemid = $secrec->id;
967 // Annotate the section mapping, with restorefiles option if needed
968 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
970 // set the new course_section id in the task
971 $this->task->set_sectionid($newitemid);
974 // Commented out. We never modify course->numsections as far as that is used
975 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
976 // Note: We keep the code here, to know about and because of the possibility of making this
977 // optional based on some setting/attribute in the future
978 // If needed, adjust course->numsections
979 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
980 // if ($numsections < $section->section) {
981 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
986 protected function after_execute() {
987 // Add section related files, with 'course_section' itemid to match
988 $this->add_related_files('course', 'section', 'course_section');
994 * Structure step that will read the course.xml file, loading it and performing
995 * various actions depending of the site/restore settings. Note that target
996 * course always exist before arriving here so this step will be updating
997 * the course record (never inserting)
999 class restore_course_structure_step extends restore_structure_step {
1001 protected function define_structure() {
1003 $course = new restore_path_element('course', '/course');
1004 $category = new restore_path_element('category', '/course/category');
1005 $tag = new restore_path_element('tag', '/course/tags/tag');
1006 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1008 // Apply for 'format' plugins optional paths at course level
1009 $this->add_plugin_structure('format', $course);
1011 return array($course, $category, $tag, $allowed_module);
1015 * Processing functions go here
1017 * @global moodledatabase $DB
1018 * @param stdClass $data
1020 public function process_course($data) {
1023 $data = (object)$data;
1024 $oldid = $data->id; // We'll need this later
1026 $fullname = $this->get_setting_value('course_fullname');
1027 $shortname = $this->get_setting_value('course_shortname');
1028 $startdate = $this->get_setting_value('course_startdate');
1030 // Calculate final course names, to avoid dupes
1031 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1033 // Need to change some fields before updating the course record
1034 $data->id = $this->get_courseid();
1035 $data->fullname = $fullname;
1036 $data->shortname= $shortname;
1037 $data->idnumber = '';
1039 // Only restrict modules if original course was and target site too for new courses
1040 $data->restrictmodules = $data->restrictmodules && !empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all';
1042 $data->startdate= $this->apply_date_offset($data->startdate);
1043 if ($data->defaultgroupingid) {
1044 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1046 if (empty($CFG->enablecompletion)) {
1047 $data->enablecompletion = 0;
1048 $data->completionstartonenrol = 0;
1049 $data->completionnotify = 0;
1051 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1052 if (!array_key_exists($data->lang, $languages)) {
1055 $themes = get_list_of_themes(); // Get themes for quick search later
1056 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1060 // Course record ready, update it
1061 $DB->update_record('course', $data);
1063 // Role name aliases
1064 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1067 public function process_category($data) {
1068 // Nothing to do with the category. UI sets it before restore starts
1071 public function process_tag($data) {
1074 $data = (object)$data;
1076 if (!empty($CFG->usetags)) { // if enabled in server
1077 // TODO: This is highly inneficient. Each time we add one tag
1078 // we fetch all the existing because tag_set() deletes them
1079 // so everything must be reinserted on each call
1081 $existingtags = tag_get_tags('course', $this->get_courseid());
1082 // Re-add all the existitng tags
1083 foreach ($existingtags as $existingtag) {
1084 $tags[] = $existingtag->rawname;
1086 // Add the one being restored
1087 $tags[] = $data->rawname;
1088 // Send all the tags back to the course
1089 tag_set('course', $this->get_courseid(), $tags);
1093 public function process_allowed_module($data) {
1096 $data = (object)$data;
1098 // only if enabled by admin setting
1099 if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all') {
1100 $available = get_plugin_list('mod');
1101 $mname = $data->modulename;
1102 if (array_key_exists($mname, $available)) {
1103 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
1104 $rec = new stdclass();
1105 $rec->course = $this->get_courseid();
1106 $rec->module = $module->id;
1107 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
1108 $DB->insert_record('course_allowed_modules', $rec);
1115 protected function after_execute() {
1116 // Add course related files, without itemid to match
1117 $this->add_related_files('course', 'summary', null);
1118 $this->add_related_files('course', 'legacy', null);
1124 * Structure step that will read the roles.xml file (at course/activity/block levels)
1125 * containig all the role_assignments and overrides for that context. If corresponding to
1126 * one mapped role, they will be applied to target context. Will observe the role_assignments
1127 * setting to decide if ras are restored.
1128 * Note: only ras with component == null are restored as far as the any ra with component
1129 * is handled by one enrolment plugin, hence it will createt the ras later
1131 class restore_ras_and_caps_structure_step extends restore_structure_step {
1133 protected function define_structure() {
1137 // Observe the role_assignments setting
1138 if ($this->get_setting_value('role_assignments')) {
1139 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1141 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1149 * This has to be called after enrolments processing.
1151 * @param mixed $data
1154 public function process_assignment($data) {
1157 $data = (object)$data;
1159 // Check roleid, userid are one of the mapped ones
1160 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1163 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1166 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1167 // Only assign roles to not deleted users
1170 if (!$contextid = $this->task->get_contextid()) {
1174 if (empty($data->component)) {
1175 // assign standard manual roles
1176 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1177 role_assign($newroleid, $newuserid, $contextid);
1179 } else if ((strpos($data->component, 'enrol_') === 0)) {
1180 // Deal with enrolment roles
1181 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1182 if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
1183 //note: we have to verify component because it might have changed
1184 if ($component === 'enrol_manual') {
1185 // manual is a special case, we do not use components - this owudl happen when converting from other plugin
1186 role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
1188 role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
1195 public function process_override($data) {
1196 $data = (object)$data;
1198 // Check roleid is one of the mapped ones
1199 $newroleid = $this->get_mappingid('role', $data->roleid);
1200 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1201 if ($newroleid && $this->task->get_contextid()) {
1202 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1203 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1204 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1210 * This structure steps restores the enrol plugins and their underlying
1211 * enrolments, performing all the mappings and/or movements required
1213 class restore_enrolments_structure_step extends restore_structure_step {
1215 protected function define_structure() {
1219 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1220 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1226 * Create enrolment instances.
1228 * This has to be called after creation of roles
1229 * and before adding of role assignments.
1231 * @param mixed $data
1234 public function process_enrol($data) {
1237 $data = (object)$data;
1238 $oldid = $data->id; // We'll need this later
1240 $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);
1242 if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
1243 // TODO: add complex restore support via custom class
1244 debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
1245 $this->set_mapping('enrol', $oldid, 0);
1249 // Perform various checks to decide what to do with the enrol plugin
1250 if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
1251 // TODO: decide if we want to switch to manual enrol - we need UI for this
1252 debugging("Enrol plugin data can not be restored because it is not installed");
1253 $this->set_mapping('enrol', $oldid, 0);
1257 if (!enrol_is_enabled($data->enrol)) {
1258 // TODO: decide if we want to switch to manual enrol - we need UI for this
1259 debugging("Enrol plugin data can not be restored because it is not enabled");
1260 $this->set_mapping('enrol', $oldid, 0);
1264 // map standard fields - plugin has to process custom fields from own restore class
1265 $data->roleid = $this->get_mappingid('role', $data->roleid);
1266 //TODO: should we move the enrol start and end date here?
1268 // always add instance, if the course does not support multiple instances it just returns NULL
1269 $enrol = enrol_get_plugin($data->enrol);
1270 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1271 if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
1274 if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
1275 // most probably plugin that supports only one instance
1276 $newitemid = key($instances);
1278 debugging('Can not create new enrol instance or reuse existing');
1283 if ($restoretype === ENROL_RESTORE_NOUSERS) {
1284 // plugin requests to prevent restore of any users
1288 $this->set_mapping('enrol', $oldid, $newitemid);
1292 * Create user enrolments
1294 * This has to be called after creation of enrolment instances
1295 * and before adding of role assignments.
1297 * @param mixed $data
1300 public function process_enrolment($data) {
1303 $data = (object)$data;
1305 // Process only if parent instance have been mapped
1306 if ($enrolid = $this->get_new_parentid('enrol')) {
1307 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1308 // And only if user is a mapped one
1309 if ($userid = $this->get_mappingid('user', $data->userid)) {
1310 $enrol = enrol_get_plugin($instance->enrol);
1311 //TODO: do we need specify modifierid?
1312 $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
1313 //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
1322 * This structure steps restores the filters and their configs
1324 class restore_filters_structure_step extends restore_structure_step {
1326 protected function define_structure() {
1330 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1331 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1336 public function process_active($data) {
1338 $data = (object)$data;
1340 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1343 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1346 public function process_config($data) {
1348 $data = (object)$data;
1350 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1353 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1359 * This structure steps restores the comments
1360 * Note: Cannot use the comments API because defaults to USER->id.
1361 * That should change allowing to pass $userid
1363 class restore_comments_structure_step extends restore_structure_step {
1365 protected function define_structure() {
1369 $paths[] = new restore_path_element('comment', '/comments/comment');
1374 public function process_comment($data) {
1377 $data = (object)$data;
1379 // First of all, if the comment has some itemid, ask to the task what to map
1381 if ($data->itemid) {
1382 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1383 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
1385 // Only restore the comment if has no mapping OR we have found the matching mapping
1386 if (!$mapping || $data->itemid) {
1387 // Only if user mapping and context
1388 $data->userid = $this->get_mappingid('user', $data->userid);
1389 if ($data->userid && $this->task->get_contextid()) {
1390 $data->contextid = $this->task->get_contextid();
1391 // Only if there is another comment with same context/user/timecreated
1392 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1393 if (!$DB->record_exists('comments', $params)) {
1394 $DB->insert_record('comments', $data);
1401 class restore_course_completion_structure_step extends restore_structure_step {
1404 * Conditionally decide if this step should be executed.
1406 * This function checks parameters that are not immediate settings to ensure
1407 * that the enviroment is suitable for the restore of course completion info.
1409 * This function checks the following four parameters:
1411 * 1. Course completion is enabled on the site
1412 * 2. The backup includes course completion information
1413 * 3. All modules are restorable
1414 * 4. All modules are marked for restore.
1416 * @return bool True is safe to execute, false otherwise
1418 protected function execute_condition() {
1421 // First check course completion is enabled on this site
1422 if (empty($CFG->enablecompletion)) {
1423 // Disabled, don't restore course completion
1427 // Check it is included in the backup
1428 $fullpath = $this->task->get_taskbasepath();
1429 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1430 if (!file_exists($fullpath)) {
1431 // Not found, can't restore course completion
1435 // Check we are able to restore all backed up modules
1436 if ($this->task->is_missing_modules()) {
1440 // Finally check all modules within the backup are being restored.
1441 if ($this->task->is_excluding_activities()) {
1449 * Define the course completion structure
1451 * @return array Array of restore_path_element
1453 protected function define_structure() {
1455 // To know if we are including user completion info
1456 $userinfo = $this->get_setting_value('userscompletion');
1459 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1460 $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1461 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1464 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1465 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1473 * Process course completion criteria
1475 * @global moodle_database $DB
1476 * @param stdClass $data
1478 public function process_course_completion_criteria($data) {
1481 $data = (object)$data;
1482 $data->course = $this->get_courseid();
1484 // Apply the date offset to the time end field
1485 $data->timeend = $this->apply_date_offset($data->timeend);
1487 // Map the role from the criteria
1488 if (!empty($data->role)) {
1489 $data->role = $this->get_mappingid('role', $data->role);
1492 $skipcriteria = false;
1494 // If the completion criteria is for a module we need to map the module instance
1495 // to the new module id.
1496 if (!empty($data->moduleinstance) && !empty($data->module)) {
1497 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
1498 if (empty($data->moduleinstance)) {
1499 $skipcriteria = true;
1502 $data->module = null;
1503 $data->moduleinstance = null;
1506 // We backup the course shortname rather than the ID so that we can match back to the course
1507 if (!empty($data->courseinstanceshortname)) {
1508 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1509 if (!$courseinstanceid) {
1510 $skipcriteria = true;
1513 $courseinstanceid = null;
1515 $data->courseinstance = $courseinstanceid;
1517 if (!$skipcriteria) {
1519 'course' => $data->course,
1520 'criteriatype' => $data->criteriatype,
1521 'enrolperiod' => $data->enrolperiod,
1522 'courseinstance' => $data->courseinstance,
1523 'module' => $data->module,
1524 'moduleinstance' => $data->moduleinstance,
1525 'timeend' => $data->timeend,
1526 'gradepass' => $data->gradepass,
1527 'role' => $data->role
1529 $newid = $DB->insert_record('course_completion_criteria', $params);
1530 $this->set_mapping('course_completion_criteria', $data->id, $newid);
1535 * Processes course compltion criteria complete records
1537 * @global moodle_database $DB
1538 * @param stdClass $data
1540 public function process_course_completion_crit_compl($data) {
1543 $data = (object)$data;
1545 // This may be empty if criteria could not be restored
1546 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
1548 $data->course = $this->get_courseid();
1549 $data->userid = $this->get_mappingid('user', $data->userid);
1551 if (!empty($data->criteriaid) && !empty($data->userid)) {
1553 'userid' => $data->userid,
1554 'course' => $data->course,
1555 'criteriaid' => $data->criteriaid,
1556 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1558 if (isset($data->gradefinal)) {
1559 $params['gradefinal'] = $data->gradefinal;
1561 if (isset($data->unenroled)) {
1562 $params['unenroled'] = $data->unenroled;
1564 if (isset($data->deleted)) {
1565 $params['deleted'] = $data->deleted;
1567 $DB->insert_record('course_completion_crit_compl', $params);
1572 * Process course completions
1574 * @global moodle_database $DB
1575 * @param stdClass $data
1577 public function process_course_completions($data) {
1580 $data = (object)$data;
1582 $data->course = $this->get_courseid();
1583 $data->userid = $this->get_mappingid('user', $data->userid);
1585 if (!empty($data->userid)) {
1587 'userid' => $data->userid,
1588 'course' => $data->course,
1589 'deleted' => $data->deleted,
1590 'timenotified' => $this->apply_date_offset($data->timenotified),
1591 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1592 'timestarted' => $this->apply_date_offset($data->timestarted),
1593 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1594 'reaggregate' => $data->reaggregate
1596 $DB->insert_record('course_completions', $params);
1601 * Process course completion notification records.
1603 * Note: As of Moodle 2.0 this table is not being used however it has been
1604 * left in in the hopes that one day the functionality there will be completed
1606 * @global moodle_database $DB
1607 * @param stdClass $data
1609 public function process_course_completion_notify($data) {
1612 $data = (object)$data;
1614 $data->course = $this->get_courseid();
1615 if (!empty($data->role)) {
1616 $data->role = $this->get_mappingid('role', $data->role);
1620 'course' => $data->course,
1621 'role' => $data->role,
1622 'message' => $data->message,
1623 'timesent' => $this->apply_date_offset($data->timesent),
1625 $DB->insert_record('course_completion_notify', $params);
1629 * Process course completion aggregate methods
1631 * @global moodle_database $DB
1632 * @param stdClass $data
1634 public function process_course_completion_aggr_methd($data) {
1637 $data = (object)$data;
1639 $data->course = $this->get_courseid();
1642 'course' => $data->course,
1643 'criteriatype' => $data->criteriatype,
1644 'method' => $data->method,
1645 'value' => $data->value,
1647 $DB->insert_record('course_completion_aggr_methd', $params);
1654 * This structure step restores course logs (cmid = 0), delegating
1655 * the hard work to the corresponding {@link restore_logs_processor} passing the
1656 * collection of {@link restore_log_rule} rules to be observed as they are defined
1657 * by the task. Note this is only executed based in the 'logs' setting.
1659 * NOTE: This is executed by final task, to have all the activities already restored
1661 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
1662 * records are. There are others like 'calendar' and 'upload' that will be handled
1665 * NOTE: All the missing actions (not able to be restored) are sent to logs for
1666 * debugging purposes
1668 class restore_course_logs_structure_step extends restore_structure_step {
1671 * Conditionally decide if this step should be executed.
1673 * This function checks the following four parameters:
1675 * 1. the course/logs.xml file exists
1677 * @return bool true is safe to execute, false otherwise
1679 protected function execute_condition() {
1681 // Check it is included in the backup
1682 $fullpath = $this->task->get_taskbasepath();
1683 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1684 if (!file_exists($fullpath)) {
1685 // Not found, can't restore course logs
1692 protected function define_structure() {
1696 // Simple, one plain level of information contains them
1697 $paths[] = new restore_path_element('log', '/logs/log');
1702 protected function process_log($data) {
1705 $data = (object)($data);
1707 $data->time = $this->apply_date_offset($data->time);
1708 $data->userid = $this->get_mappingid('user', $data->userid);
1709 $data->course = $this->get_courseid();
1712 // For any reason user wasn't remapped ok, stop processing this
1713 if (empty($data->userid)) {
1717 // Everything ready, let's delegate to the restore_logs_processor
1719 // Set some fixed values that will save tons of DB requests
1721 'course' => $this->get_courseid());
1722 // Get instance and process log record
1723 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
1725 // If we have data, insert it, else something went wrong in the restore_logs_processor
1727 $DB->insert_record('log', $data);
1733 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
1734 * sharing its same structure but modifying the way records are handled
1736 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
1738 protected function process_log($data) {
1741 $data = (object)($data);
1743 $data->time = $this->apply_date_offset($data->time);
1744 $data->userid = $this->get_mappingid('user', $data->userid);
1745 $data->course = $this->get_courseid();
1746 $data->cmid = $this->task->get_moduleid();
1748 // For any reason user wasn't remapped ok, stop processing this
1749 if (empty($data->userid)) {
1753 // Everything ready, let's delegate to the restore_logs_processor
1755 // Set some fixed values that will save tons of DB requests
1757 'course' => $this->get_courseid(),
1758 'course_module' => $this->task->get_moduleid(),
1759 $this->task->get_modulename() => $this->task->get_activityid());
1760 // Get instance and process log record
1761 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
1763 // If we have data, insert it, else something went wrong in the restore_logs_processor
1765 $DB->insert_record('log', $data);
1771 * This structure step restores the grade items associated with one activity
1772 * All the grade items are made child of the "course" grade item but the original
1773 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
1774 * the complete gradebook (categories and calculations), that information is
1777 class restore_activity_grades_structure_step extends restore_structure_step {
1779 protected function define_structure() {
1782 $userinfo = $this->get_setting_value('userinfo');
1784 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
1785 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
1787 $paths[] = new restore_path_element('grade_grade',
1788 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
1793 protected function process_grade_item($data) {
1795 $data = (object)($data);
1796 $oldid = $data->id; // We'll need these later
1797 $oldparentid = $data->categoryid;
1799 // make sure top course category exists, all grade items will be associated
1800 // to it. Later, if restoring the whole gradebook, categories will be introduced
1801 $coursecat = grade_category::fetch_course_category($this->get_courseid());
1802 $coursecatid = $coursecat->id; // Get the categoryid to be used
1805 $data->categoryid = $coursecatid;
1806 $data->courseid = $this->get_courseid();
1807 $data->iteminstance = $this->task->get_activityid();
1808 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
1809 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
1810 // so the best is to keep the ones already in the gradebook
1811 // Potential problem: duplicates if same items are restored more than once. :-(
1812 // This needs to be fixed in some way (outcomes & activities with multiple items)
1813 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
1814 // In any case, verify always for uniqueness
1815 $data->idnumber = grade_verify_idnumber($data->idnumber, $this->get_courseid()) ? $data->idnumber : null;
1816 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1817 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
1818 $data->timecreated = $this->apply_date_offset($data->timecreated);
1819 $data->timemodified = $this->apply_date_offset($data->timemodified);
1821 $gradeitem = new grade_item($data, false);
1822 $gradeitem->insert('restore');
1824 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
1825 $gradeitem->sortorder = $data->sortorder;
1826 $gradeitem->update('restore');
1828 // Set mapping, saving the original category id into parentitemid
1829 // gradebook restore (final task) will need it to reorganise items
1830 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
1833 protected function process_grade_grade($data) {
1834 $data = (object)($data);
1837 $data->itemid = $this->get_new_parentid('grade_item');
1838 $data->userid = $this->get_mappingid('user', $data->userid);
1839 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
1840 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
1841 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
1842 $data->overridden = $this->apply_date_offset($data->overridden);
1844 $grade = new grade_grade($data, false);
1845 $grade->insert('restore');
1846 // no need to save any grade_grade mapping
1850 * process activity grade_letters. Note that, while these are possible,
1851 * because grade_letters are contextid based, in proctice, only course
1852 * context letters can be defined. So we keep here this method knowing
1853 * it won't be executed ever. gradebook restore will restore course letters.
1855 protected function process_grade_letter($data) {
1858 $data = (object)$data;
1860 $data->contextid = $this->task->get_contextid();
1861 $newitemid = $DB->insert_record('grade_letters', $data);
1862 // no need to save any grade_letter mapping
1868 * This structure steps restores one instance + positions of one block
1869 * Note: Positions corresponding to one existing context are restored
1870 * here, but all the ones having unknown contexts are sent to backup_ids
1871 * for a later chance to be restored at the end (final task)
1873 class restore_block_instance_structure_step extends restore_structure_step {
1875 protected function define_structure() {
1879 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
1880 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
1885 public function process_block($data) {
1888 $data = (object)$data; // Handy
1889 $oldcontextid = $data->contextid;
1891 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1893 // Look for the parent contextid
1894 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1895 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1898 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
1899 // If there is already one block of that type in the parent context
1900 // and the block is not multiple, stop processing
1901 // Use blockslib loader / method executor
1902 if (!block_method_result($data->blockname, 'instance_allow_multiple')) {
1903 if ($DB->record_exists_sql("SELECT bi.id
1904 FROM {block_instances} bi
1905 JOIN {block} b ON b.name = bi.blockname
1906 WHERE bi.parentcontextid = ?
1907 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
1912 // If there is already one block of that type in the parent context
1913 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
1916 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
1917 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
1918 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
1919 if ($birecs = $DB->get_records('block_instances', $params)) {
1920 foreach($birecs as $birec) {
1921 if ($birec->configdata == $data->configdata) {
1927 // Set task old contextid, blockid and blockname once we know them
1928 $this->task->set_old_contextid($oldcontextid);
1929 $this->task->set_old_blockid($oldid);
1930 $this->task->set_blockname($data->blockname);
1932 // Let's look for anything within configdata neededing processing
1933 // (nulls and uses of legacy file.php)
1934 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1935 $configdata = (array)unserialize(base64_decode($data->configdata));
1936 foreach ($configdata as $attribute => $value) {
1937 if (in_array($attribute, $attrstotransform)) {
1938 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
1941 $data->configdata = base64_encode(serialize((object)$configdata));
1944 // Create the block instance
1945 $newitemid = $DB->insert_record('block_instances', $data);
1946 // Save the mapping (with restorefiles support)
1947 $this->set_mapping('block_instance', $oldid, $newitemid, true);
1948 // Create the block context
1949 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
1950 // Save the block contexts mapping and sent it to task
1951 $this->set_mapping('context', $oldcontextid, $newcontextid);
1952 $this->task->set_contextid($newcontextid);
1953 $this->task->set_blockid($newitemid);
1955 // Restore block fileareas if declared
1956 $component = 'block_' . $this->task->get_blockname();
1957 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
1958 $this->add_related_files($component, $filearea, null);
1961 // Process block positions, creating them or accumulating for final step
1962 foreach($positions as $position) {
1963 $position = (object)$position;
1964 $position->blockinstanceid = $newitemid; // The instance is always the restored one
1965 // If position is for one already mapped (known) contextid
1966 // process it now, creating the position
1967 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
1968 $position->contextid = $newpositionctxid;
1969 // Create the block position
1970 $DB->insert_record('block_positions', $position);
1972 // The position belongs to an unknown context, send it to backup_ids
1973 // to process them as part of the final steps of restore. We send the
1974 // whole $position object there, hence use the low level method.
1976 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
1983 * Structure step to restore common course_module information
1985 * This step will process the module.xml file for one activity, in order to restore
1986 * the corresponding information to the course_modules table, skipping various bits
1987 * of information based on CFG settings (groupings, completion...) in order to fullfill
1988 * all the reqs to be able to create the context to be used by all the rest of steps
1989 * in the activity restore task
1991 class restore_module_structure_step extends restore_structure_step {
1993 protected function define_structure() {
1998 $module = new restore_path_element('module', '/module');
2000 if ($CFG->enableavailability) {
2001 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
2004 // Apply for 'format' plugins optional paths at module level
2005 $this->add_plugin_structure('format', $module);
2010 protected function process_module($data) {
2013 $data = (object)$data;
2016 $data->course = $this->task->get_courseid();
2017 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
2018 // Map section (first try by course_section mapping match. Useful in course and section restores)
2019 $data->section = $this->get_mappingid('course_section', $data->sectionid);
2020 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
2022 'course' => $this->get_courseid(),
2023 'section' => $data->sectionnumber);
2024 $data->section = $DB->get_field('course_sections', 'id', $params);
2026 if (!$data->section) { // sectionnumber failed, try to get first section in course
2028 'course' => $this->get_courseid());
2029 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
2031 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
2032 $sectionrec = array(
2033 'course' => $this->get_courseid(),
2035 $DB->insert_record('course_sections', $sectionrec); // section 0
2036 $sectionrec = array(
2037 'course' => $this->get_courseid(),
2039 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
2041 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
2042 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
2043 $data->groupmembersonly = 0;
2045 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
2046 $data->idnumber = '';
2048 if (empty($CFG->enablecompletion)) { // completion
2049 $data->completion = 0;
2050 $data->completiongradeitemnumber = null;
2051 $data->completionview = 0;
2052 $data->completionexpected = 0;
2054 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
2056 if (empty($CFG->enableavailability)) {
2057 $data->availablefrom = 0;
2058 $data->availableuntil = 0;
2059 $data->showavailability = 0;
2061 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
2062 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
2064 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
2066 // course_module record ready, insert it
2067 $newitemid = $DB->insert_record('course_modules', $data);
2069 $this->set_mapping('course_module', $oldid, $newitemid);
2070 // set the new course_module id in the task
2071 $this->task->set_moduleid($newitemid);
2072 // we can now create the context safely
2073 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
2074 // set the new context id in the task
2075 $this->task->set_contextid($ctxid);
2076 // update sequence field in course_section
2077 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
2078 $sequence .= ',' . $newitemid;
2080 $sequence = $newitemid;
2082 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
2086 protected function process_availability($data) {
2087 $data = (object)$data;
2088 // Simply going to store the whole availability record now, we'll process
2089 // all them later in the final task (once all actvivities have been restored)
2090 // Let's call the low level one to be able to store the whole object
2091 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
2092 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
2097 * Structure step that will process the user activity completion
2098 * information if all these conditions are met:
2099 * - Target site has completion enabled ($CFG->enablecompletion)
2100 * - Activity includes completion info (file_exists)
2102 class restore_userscompletion_structure_step extends restore_structure_step {
2105 * To conditionally decide if this step must be executed
2106 * Note the "settings" conditions are evaluated in the
2107 * corresponding task. Here we check for other conditions
2108 * not being restore settings (files, site settings...)
2110 protected function execute_condition() {
2113 // Completion disabled in this site, don't execute
2114 if (empty($CFG->enablecompletion)) {
2118 // No user completion info found, don't execute
2119 $fullpath = $this->task->get_taskbasepath();
2120 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2121 if (!file_exists($fullpath)) {
2125 // Arrived here, execute the step
2129 protected function define_structure() {
2133 $paths[] = new restore_path_element('completion', '/completions/completion');
2138 protected function process_completion($data) {
2141 $data = (object)$data;
2143 $data->coursemoduleid = $this->task->get_moduleid();
2144 $data->userid = $this->get_mappingid('user', $data->userid);
2145 $data->timemodified = $this->apply_date_offset($data->timemodified);
2147 $DB->insert_record('course_modules_completion', $data);
2152 * Abstract structure step, parent of all the activity structure steps. Used to suuport
2153 * the main <activity ...> tag and process it. Also provides subplugin support for
2156 abstract class restore_activity_structure_step extends restore_structure_step {
2158 protected function add_subplugin_structure($subplugintype, $element) {
2162 // Check the requested subplugintype is a valid one
2163 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
2164 if (!file_exists($subpluginsfile)) {
2165 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
2167 include($subpluginsfile);
2168 if (!array_key_exists($subplugintype, $subplugins)) {
2169 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
2171 // Get all the restore path elements, looking across all the subplugin dirs
2172 $subpluginsdirs = get_plugin_list($subplugintype);
2173 foreach ($subpluginsdirs as $name => $subpluginsdir) {
2174 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
2175 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
2176 if (file_exists($restorefile)) {
2177 require_once($restorefile);
2178 $restoresubplugin = new $classname($subplugintype, $name, $this);
2179 // Add subplugin paths to the step
2180 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
2186 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
2187 * have the parent task available for wrapping purposes (get course/context....)
2189 public function get_task() {
2194 * Adds support for the 'activity' path that is common to all the activities
2195 * and will be processed globally here
2197 protected function prepare_activity_structure($paths) {
2199 $paths[] = new restore_path_element('activity', '/activity');
2205 * Process the activity path, informing the task about various ids, needed later
2207 protected function process_activity($data) {
2208 $data = (object)$data;
2209 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
2210 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
2211 $this->task->set_old_activityid($data->id); // Save old activityid in task
2215 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
2216 * and will adjust the new activity id (the instance) in various places
2218 protected function apply_activity_instance($newitemid) {
2221 $this->task->set_activityid($newitemid); // Save activity id in task
2222 // Apply the id to course_sections->instanceid
2223 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
2224 // Do the mapping for modulename, preparing it for files by oldcontext
2225 $modulename = $this->task->get_modulename();
2226 $oldid = $this->task->get_old_activityid();
2227 $this->set_mapping($modulename, $oldid, $newitemid, true);
2232 * Structure step in charge of creating/mapping all the qcats and qs
2233 * by parsing the questions.xml file and checking it against the
2234 * results calculated by {@link restore_process_categories_and_questions}
2235 * and stored in backup_ids_temp
2237 class restore_create_categories_and_questions extends restore_structure_step {
2239 protected function define_structure() {
2241 $category = new restore_path_element('question_category', '/question_categories/question_category');
2242 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
2244 // Apply for 'qtype' plugins optional paths at question level
2245 $this->add_plugin_structure('qtype', $question);
2247 return array($category, $question);
2250 protected function process_question_category($data) {
2253 $data = (object)$data;
2256 // Check we have one mapping for this category
2257 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
2258 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
2261 // Check we have to create the category (newitemid = 0)
2262 if ($mapping->newitemid) {
2263 return; // newitemid != 0, this category is going to be mapped. Nothing to do
2266 // Arrived here, newitemid = 0, we need to create the category
2267 // we'll do it at parentitemid context, but for CONTEXT_MODULE
2268 // categories, that will be created at CONTEXT_COURSE and moved
2269 // to module context later when the activity is created
2270 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
2271 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
2273 $data->contextid = $mapping->parentitemid;
2275 // Let's create the question_category and save mapping
2276 $newitemid = $DB->insert_record('question_categories', $data);
2277 $this->set_mapping('question_category', $oldid, $newitemid);
2278 // Also annotate them as question_category_created, we need
2279 // that later when remapping parents
2280 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
2283 protected function process_question($data) {
2286 $data = (object)$data;
2289 // Check we have one mapping for this question
2290 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
2291 return; // No mapping = this question doesn't need to be created/mapped
2294 // Get the mapped category (cannot use get_new_parentid() because not
2295 // all the categories have been created, so it is not always available
2296 // Instead we get the mapping for the question->parentitemid because
2297 // we have loaded qcatids there for all parsed questions
2298 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
2300 $data->timecreated = $this->apply_date_offset($data->timecreated);
2301 $data->timemodified = $this->apply_date_offset($data->timemodified);
2303 $userid = $this->get_mappingid('user', $data->createdby);
2304 $data->createdby = $userid ? $userid : $this->task->get_userid();
2306 $userid = $this->get_mappingid('user', $data->modifiedby);
2307 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
2309 // With newitemid = 0, let's create the question
2310 if (!$questionmapping->newitemid) {
2311 $newitemid = $DB->insert_record('question', $data);
2312 $this->set_mapping('question', $oldid, $newitemid);
2313 // Also annotate them as question_created, we need
2314 // that later when remapping parents (keeping the old categoryid as parentid)
2315 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
2317 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
2318 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
2319 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
2322 // Note, we don't restore any question files yet
2323 // as far as the CONTEXT_MODULE categories still
2324 // haven't their contexts to be restored to
2325 // The {@link restore_create_question_files}, executed in the final step
2326 // step will be in charge of restoring all the question files
2329 protected function after_execute() {
2332 // First of all, recode all the created question_categories->parent fields
2333 $qcats = $DB->get_records('backup_ids_temp', array(
2334 'backupid' => $this->get_restoreid(),
2335 'itemname' => 'question_category_created'));
2336 foreach ($qcats as $qcat) {
2338 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
2339 // Get new parent (mapped or created, so we look in quesiton_category mappings)
2340 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2341 'backupid' => $this->get_restoreid(),
2342 'itemname' => 'question_category',
2343 'itemid' => $dbcat->parent))) {
2344 // contextids must match always, as far as we always include complete qbanks, just check it
2345 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
2346 if ($dbcat->contextid == $newparentctxid) {
2347 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
2349 $newparent = 0; // No ctx match for both cats, no parent relationship
2352 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
2354 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
2358 // Now, recode all the created question->parent fields
2359 $qs = $DB->get_records('backup_ids_temp', array(
2360 'backupid' => $this->get_restoreid(),
2361 'itemname' => 'question_created'));
2362 foreach ($qs as $q) {
2364 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
2365 // Get new parent (mapped or created, so we look in question mappings)
2366 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2367 'backupid' => $this->get_restoreid(),
2368 'itemname' => 'question',
2369 'itemid' => $dbq->parent))) {
2370 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
2374 // Note, we don't restore any question files yet
2375 // as far as the CONTEXT_MODULE categories still
2376 // haven't their contexts to be restored to
2377 // The {@link restore_create_question_files}, executed in the final step
2378 // step will be in charge of restoring all the question files
2383 * Execution step that will move all the CONTEXT_MODULE question categories
2384 * created at early stages of restore in course context (because modules weren't
2385 * created yet) to their target module (matching by old-new-contextid mapping)
2387 class restore_move_module_questions_categories extends restore_execution_step {
2389 protected function define_execution() {
2392 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
2393 foreach ($contexts as $contextid => $contextlevel) {
2394 // Only if context mapping exists (i.e. the module has been restored)
2395 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
2396 // Update all the qcats having their parentitemid set to the original contextid
2397 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
2398 FROM {backup_ids_temp}
2400 AND itemname = 'question_category'
2401 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
2402 foreach ($modulecats as $modulecat) {
2403 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
2404 // And set new contextid also in question_category mapping (will be
2405 // used by {@link restore_create_question_files} later
2406 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
2414 * Execution step that will create all the question/answers/qtype-specific files for the restored
2415 * questions. It must be executed after {@link restore_move_module_questions_categories}
2416 * because only then each question is in its final category and only then the
2417 * context can be determined
2419 * TODO: Improve this. Instead of looping over each question, it can be reduced to
2420 * be done by contexts (this will save a huge ammount of queries)
2422 class restore_create_question_files extends restore_execution_step {
2424 protected function define_execution() {
2427 // Let's process only created questions
2428 $questionsrs = $DB->get_recordset_sql("SELECT bi.itemid, bi.newitemid, bi.parentitemid, q.qtype
2429 FROM {backup_ids_temp} bi
2430 JOIN {question} q ON q.id = bi.newitemid
2431 WHERE bi.backupid = ?
2432 AND bi.itemname = 'question_created'", array($this->get_restoreid()));
2433 foreach ($questionsrs as $question) {
2434 // Get question_category mapping, it contains the target context for the question
2435 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $question->parentitemid)) {
2436 // Something went really wrong, cannot find the question_category for the question
2437 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
2440 // Calculate source and target contexts
2441 $oldctxid = $qcatmapping->info->contextid;
2442 $newctxid = $qcatmapping->parentitemid;
2444 // Add common question files (question and question_answer ones)
2445 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
2446 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2447 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
2448 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2449 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
2450 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
2451 // Add qtype dependent files
2452 $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
2453 foreach ($components as $component => $fileareas) {
2454 foreach ($fileareas as $filearea => $mapping) {
2455 // Use itemid only if mapping is question_created
2456 $itemid = ($mapping == 'question_created') ? $question->itemid : null;
2457 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
2458 $oldctxid, $this->task->get_userid(), $mapping, $itemid, $newctxid, true);
2462 $questionsrs->close();
2467 * Abstract structure step, to be used by all the activities using core questions stuff
2468 * (like the quiz module), to support qtype plugins, states and sessions
2470 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
2473 * Attach below $element (usually attempts) the needed restore_path_elements
2474 * to restore question_states
2476 protected function add_question_attempts_states($element, &$paths) {
2477 // Check $element is restore_path_element
2478 if (! $element instanceof restore_path_element) {
2479 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2481 // Check $paths is one array
2482 if (!is_array($paths)) {
2483 throw new restore_step_exception('paths_must_be_array', $paths);
2485 $paths[] = new restore_path_element('question_state', $element->get_path() . '/states/state');
2489 * Attach below $element (usually attempts) the needed restore_path_elements
2490 * to restore question_sessions
2492 protected function add_question_attempts_sessions($element, &$paths) {
2493 // Check $element is restore_path_element
2494 if (! $element instanceof restore_path_element) {
2495 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2497 // Check $paths is one array
2498 if (!is_array($paths)) {
2499 throw new restore_step_exception('paths_must_be_array', $paths);
2501 $paths[] = new restore_path_element('question_session', $element->get_path() . '/sessions/session');
2505 * Process question_states
2507 protected function process_question_state($data) {
2510 $data = (object)$data;
2513 // Get complete question mapping, we'll need info
2514 $question = $this->get_mapping('question', $data->question);
2516 // In the quiz_attempt mapping we are storing uniqueid
2517 // and not id, so this gets the correct question_attempt to point to
2518 $data->attempt = $this->get_new_parentid('quiz_attempt');
2519 $data->question = $question->newitemid;
2520 $data->answer = $this->restore_recode_answer($data, $question->info->qtype); // Delegate recoding of answer
2521 $data->timestamp= $this->apply_date_offset($data->timestamp);
2523 // Everything ready, insert and create mapping (needed by question_sessions)
2524 $newitemid = $DB->insert_record('question_states', $data);
2525 $this->set_mapping('question_state', $oldid, $newitemid);
2529 * Process question_sessions
2531 protected function process_question_session($data) {
2534 $data = (object)$data;
2537 // In the quiz_attempt mapping we are storing uniqueid
2538 // and not id, so this gets the correct question_attempt to point to
2539 $data->attemptid = $this->get_new_parentid('quiz_attempt');
2540 $data->questionid = $this->get_mappingid('question', $data->questionid);
2541 $data->newest = $this->get_mappingid('question_state', $data->newest);
2542 $data->newgraded = $this->get_mappingid('question_state', $data->newgraded);
2544 // Everything ready, insert (no mapping needed)
2545 $newitemid = $DB->insert_record('question_sessions', $data);
2547 // Note: question_sessions haven't files associated. On purpose manualcomment is lacking
2548 // support for them, so we don't need to handle them here.
2552 * Given a list of question->ids, separated by commas, returns the
2553 * recoded list, with all the restore question mappings applied.
2554 * Note: Used by quiz->questions and quiz_attempts->layout
2555 * Note: 0 = page break (unconverted)
2557 protected function questions_recode_layout($layout) {
2558 // Extracts question id from sequence
2559 if ($questionids = explode(',', $layout)) {
2560 foreach ($questionids as $id => $questionid) {
2561 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
2562 $newquestionid = $this->get_mappingid('question', $questionid);
2563 $questionids[$id] = $newquestionid;
2567 return implode(',', $questionids);
2571 * Given one question_states record, return the answer
2572 * recoded pointing to all the restored stuff
2574 public function restore_recode_answer($state, $qtype) {
2575 // Build one static cache to store {@link restore_qtype_plugin}
2576 // while we are needing them, just to save zillions of instantiations
2577 // or using static stuff that will break our nice API
2578 static $qtypeplugins = array();
2580 // If we haven't the corresponding restore_qtype_plugin for current qtype
2581 // instantiate it and add to cache
2582 if (!isset($qtypeplugins[$qtype])) {
2583 $classname = 'restore_qtype_' . $qtype . '_plugin';
2584 if (class_exists($classname)) {
2585 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
2587 $qtypeplugins[$qtype] = false;
2590 return !empty($qtypeplugins[$qtype]) ? $qtypeplugins[$qtype]->recode_state_answer($state) : $state->answer;