Merge branch 'MDL-27635_m21' of git://github.com/rwijaya/moodle into MOODLE_21_STABLE
[moodle.git] / backup / moodle2 / restore_stepslib.php
blob0b02c0105d9dbfb7e37eebb3cac0c7b21896f3e0
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * @package moodlecore
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
25 /**
26 * Define all the restore steps that will be used by common tasks in restore
29 /**
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);
58 /**
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() {
65 global $CFG;
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
74 /**
75 * Restore calculated grade items, grade categories etc
77 class restore_gradebook_structure_step extends restore_structure_step {
79 /**
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() {
86 global $CFG, $DB;
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)) {
92 return false;
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()) {
98 return false;
101 // Some activity has been excluded to be restored, don't execute
102 if ($this->task->is_excluding_activities()) {
103 return false;
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);
112 if ($catcount>1) {
113 return false;
116 // Arrived here, execute the step
117 return true;
120 protected function define_structure() {
121 $paths = array();
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');
127 if ($userinfo) {
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');
133 return $paths;
136 protected function process_gradebook($data) {
139 protected function process_grade_item($data) {
140 global $DB;
142 $data = (object)$data;
144 $oldid = $data->id;
145 $data->course = $this->get_courseid();
147 $data->courseid = $this->get_courseid();
149 if ($data->itemtype=='manual') {
150 // manual grade items store category id in categoryid
151 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
152 } else if ($data->itemtype=='course') {
153 // course grade item stores their category id in iteminstance
154 $coursecat = grade_category::fetch_course_category($this->get_courseid());
155 $data->iteminstance = $coursecat->id;
156 } else if ($data->itemtype=='category') {
157 // category grade items store their category id in iteminstance
158 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
159 } else {
160 throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
163 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
164 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
166 $data->locktime = $this->apply_date_offset($data->locktime);
167 $data->timecreated = $this->apply_date_offset($data->timecreated);
168 $data->timemodified = $this->apply_date_offset($data->timemodified);
170 $coursecategory = $newitemid = null;
171 //course grade item should already exist so updating instead of inserting
172 if($data->itemtype=='course') {
173 //get the ID of the already created grade item
174 $gi = new stdclass();
175 $gi->courseid = $this->get_courseid();
176 $gi->itemtype = $data->itemtype;
178 //need to get the id of the grade_category that was automatically created for the course
179 $category = new stdclass();
180 $category->courseid = $this->get_courseid();
181 $category->parent = null;
182 //course category fullname starts out as ? but may be edited
183 //$category->fullname = '?';
184 $coursecategory = $DB->get_record('grade_categories', (array)$category);
185 $gi->iteminstance = $coursecategory->id;
187 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
188 if (!empty($existinggradeitem)) {
189 $data->id = $newitemid = $existinggradeitem->id;
190 $DB->update_record('grade_items', $data);
194 if (empty($newitemid)) {
195 //in case we found the course category but still need to insert the course grade item
196 if ($data->itemtype=='course' && !empty($coursecategory)) {
197 $data->iteminstance = $coursecategory->id;
200 $newitemid = $DB->insert_record('grade_items', $data);
202 $this->set_mapping('grade_item', $oldid, $newitemid);
205 protected function process_grade_grade($data) {
206 global $DB;
208 $data = (object)$data;
209 $oldid = $data->id;
211 $data->itemid = $this->get_new_parentid('grade_item');
213 $data->userid = $this->get_mappingid('user', $data->userid, NULL);
214 $data->usermodified = $this->get_mappingid('user', $data->usermodified, NULL);
215 $data->locktime = $this->apply_date_offset($data->locktime);
216 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
217 $data->overridden = $this->apply_date_offset($data->overridden);
218 $data->timecreated = $this->apply_date_offset($data->timecreated);
219 $data->timemodified = $this->apply_date_offset($data->timemodified);
221 $newitemid = $DB->insert_record('grade_grades', $data);
222 //$this->set_mapping('grade_grade', $oldid, $newitemid);
224 protected function process_grade_category($data) {
225 global $DB;
227 $data = (object)$data;
228 $oldid = $data->id;
230 $data->course = $this->get_courseid();
231 $data->courseid = $data->course;
233 $data->timecreated = $this->apply_date_offset($data->timecreated);
234 $data->timemodified = $this->apply_date_offset($data->timemodified);
236 $newitemid = null;
237 //no parent means a course level grade category. That may have been created when the course was created
238 if(empty($data->parent)) {
239 //parent was being saved as 0 when it should be null
240 $data->parent = null;
242 //get the already created course level grade category
243 $category = new stdclass();
244 $category->courseid = $this->get_courseid();
245 $category->parent = null;
247 $coursecategory = $DB->get_record('grade_categories', (array)$category);
248 if (!empty($coursecategory)) {
249 $data->id = $newitemid = $coursecategory->id;
250 $DB->update_record('grade_categories', $data);
254 //need to insert a course category
255 if (empty($newitemid)) {
256 $newitemid = $DB->insert_record('grade_categories', $data);
258 $this->set_mapping('grade_category', $oldid, $newitemid);
260 protected function process_grade_letter($data) {
261 global $DB;
263 $data = (object)$data;
264 $oldid = $data->id;
266 $data->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
268 $newitemid = $DB->insert_record('grade_letters', $data);
269 $this->set_mapping('grade_letter', $oldid, $newitemid);
271 protected function process_grade_setting($data) {
272 global $DB;
274 $data = (object)$data;
275 $oldid = $data->id;
277 $data->courseid = $this->get_courseid();
279 $newitemid = $DB->insert_record('grade_settings', $data);
280 //$this->set_mapping('grade_setting', $oldid, $newitemid);
284 * put all activity grade items in the correct grade category and mark all for recalculation
286 protected function after_execute() {
287 global $DB;
289 $conditions = array(
290 'backupid' => $this->get_restoreid(),
291 'itemname' => 'grade_item'//,
292 //'itemid' => $itemid
294 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
296 // We need this for calculation magic later on.
297 $mappings = array();
299 if (!empty($rs)) {
300 foreach($rs as $grade_item_backup) {
302 // Store the oldid with the new id.
303 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
305 $updateobj = new stdclass();
306 $updateobj->id = $grade_item_backup->newitemid;
308 //if this is an activity grade item that needs to be put back in its correct category
309 if (!empty($grade_item_backup->parentitemid)) {
310 $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
311 if (!is_null($oldcategoryid)) {
312 $updateobj->categoryid = $oldcategoryid;
313 $DB->update_record('grade_items', $updateobj);
315 } else {
316 //mark course and category items as needing to be recalculated
317 $updateobj->needsupdate=1;
318 $DB->update_record('grade_items', $updateobj);
322 $rs->close();
324 // We need to update the calculations for calculated grade items that may reference old
325 // grade item ids using ##gi\d+##.
326 // $mappings can be empty, use 0 if so (won't match ever)
327 list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
328 $sql = "SELECT gi.id, gi.calculation
329 FROM {grade_items} gi
330 WHERE gi.id {$sql} AND
331 calculation IS NOT NULL";
332 $rs = $DB->get_recordset_sql($sql, $params);
333 foreach ($rs as $gradeitem) {
334 // Collect all of the used grade item id references
335 if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
336 // This calculation doesn't reference any other grade items... EASY!
337 continue;
339 // For this next bit we are going to do the replacement of id's in two steps:
340 // 1. We will replace all old id references with a special mapping reference.
341 // 2. We will replace all mapping references with id's
342 // Why do we do this?
343 // Because there potentially there will be an overlap of ids within the query and we
344 // we substitute the wrong id.. safest way around this is the two step system
345 $calculationmap = array();
346 $mapcount = 0;
347 foreach ($matches[1] as $match) {
348 // Check that the old id is known to us, if not it was broken to begin with and will
349 // continue to be broken.
350 if (!array_key_exists($match, $mappings)) {
351 continue;
353 // Our special mapping key
354 $mapping = '##MAPPING'.$mapcount.'##';
355 // The old id that exists within the calculation now
356 $oldid = '##gi'.$match.'##';
357 // The new id that we want to replace the old one with.
358 $newid = '##gi'.$mappings[$match].'##';
359 // Replace in the special mapping key
360 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
361 // And record the mapping
362 $calculationmap[$mapping] = $newid;
363 $mapcount++;
365 // Iterate all special mappings for this calculation and replace in the new id's
366 foreach ($calculationmap as $mapping => $newid) {
367 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
369 // Update the calculation now that its being remapped
370 $DB->update_record('grade_items', $gradeitem);
372 $rs->close();
374 //need to correct the grade category path and parent
375 $conditions = array(
376 'courseid' => $this->get_courseid()
378 $grade_category = new stdclass();
380 $rs = $DB->get_recordset('grade_categories', $conditions);
381 if (!empty($rs)) {
382 //get all the parents correct first as grade_category::build_path() loads category parents from the DB
383 foreach($rs as $gc) {
384 if (!empty($gc->parent)) {
385 $grade_category->id = $gc->id;
386 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
387 $DB->update_record('grade_categories', $grade_category);
391 if (isset($grade_category->parent)) {
392 unset($grade_category->parent);
394 $rs->close();
396 $rs = $DB->get_recordset('grade_categories', $conditions);
397 if (!empty($rs)) {
398 //now we can rebuild all the paths
399 foreach($rs as $gc) {
400 $grade_category->id = $gc->id;
401 $grade_category->path = grade_category::build_path($gc);
402 $DB->update_record('grade_categories', $grade_category);
405 $rs->close();
407 //Restore marks items as needing update. Update everything now.
408 grade_regrade_final_grades($this->get_courseid());
413 * decode all the interlinks present in restored content
414 * relying 100% in the restore_decode_processor that handles
415 * both the contents to modify and the rules to be applied
417 class restore_decode_interlinks extends restore_execution_step {
419 protected function define_execution() {
420 // Get the decoder (from the plan)
421 $decoder = $this->task->get_decoder();
422 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
423 // And launch it, everything will be processed
424 $decoder->execute();
429 * first, ensure that we have no gaps in section numbers
430 * and then, rebuid the course cache
432 class restore_rebuild_course_cache extends restore_execution_step {
434 protected function define_execution() {
435 global $DB;
437 // Although there is some sort of auto-recovery of missing sections
438 // present in course/formats... here we check that all the sections
439 // from 0 to MAX(section->section) exist, creating them if necessary
440 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
441 // Iterate over all sections
442 for ($i = 0; $i <= $maxsection; $i++) {
443 // If the section $i doesn't exist, create it
444 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
445 $sectionrec = array(
446 'course' => $this->get_courseid(),
447 'section' => $i);
448 $DB->insert_record('course_sections', $sectionrec); // missing section created
452 // Rebuild cache now that all sections are in place
453 rebuild_course_cache($this->get_courseid());
458 * Review all the tasks having one after_restore method
459 * executing it to perform some final adjustments of information
460 * not available when the task was executed.
462 class restore_execute_after_restore extends restore_execution_step {
464 protected function define_execution() {
466 // Simply call to the execute_after_restore() method of the task
467 // that always is the restore_final_task
468 $this->task->launch_execute_after_restore();
474 * Review all the (pending) block positions in backup_ids, matching by
475 * contextid, creating positions as needed. This is executed by the
476 * final task, once all the contexts have been created
478 class restore_review_pending_block_positions extends restore_execution_step {
480 protected function define_execution() {
481 global $DB;
483 // Get all the block_position objects pending to match
484 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
485 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
486 // Process block positions, creating them or accumulating for final step
487 foreach($rs as $posrec) {
488 // Get the complete position object (stored as info)
489 $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
490 // If position is for one already mapped (known) contextid
491 // process it now, creating the position, else nothing to
492 // do, position finally discarded
493 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
494 $position->contextid = $newctx->newitemid;
495 // Create the block position
496 $DB->insert_record('block_positions', $position);
499 $rs->close();
504 * Process all the saved module availability records in backup_ids, matching
505 * course modules and grade item id once all them have been already restored.
506 * only if all matchings are satisfied the availability condition will be created.
507 * At the same time, it is required for the site to have that functionality enabled.
509 class restore_process_course_modules_availability extends restore_execution_step {
511 protected function define_execution() {
512 global $CFG, $DB;
514 // Site hasn't availability enabled
515 if (empty($CFG->enableavailability)) {
516 return;
519 // Get all the module_availability objects to process
520 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
521 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
522 // Process availabilities, creating them if everything matches ok
523 foreach($rs as $availrec) {
524 $allmatchesok = true;
525 // Get the complete availabilityobject
526 $availability = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_availability', $availrec->itemid)->info;
527 // Map the sourcecmid if needed and possible
528 if (!empty($availability->sourcecmid)) {
529 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
530 if ($newcm) {
531 $availability->sourcecmid = $newcm->newitemid;
532 } else {
533 $allmatchesok = false; // Failed matching, we won't create this availability rule
536 // Map the gradeitemid if needed and possible
537 if (!empty($availability->gradeitemid)) {
538 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
539 if ($newgi) {
540 $availability->gradeitemid = $newgi->newitemid;
541 } else {
542 $allmatchesok = false; // Failed matching, we won't create this availability rule
545 if ($allmatchesok) { // Everything ok, create the availability rule
546 $DB->insert_record('course_modules_availability', $availability);
549 $rs->close();
555 * Execution step that, *conditionally* (if there isn't preloaded information)
556 * will load the inforef files for all the included course/section/activity tasks
557 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
559 class restore_load_included_inforef_records extends restore_execution_step {
561 protected function define_execution() {
563 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
564 return;
567 // Get all the included tasks
568 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
569 foreach ($tasks as $task) {
570 // Load the inforef.xml file if exists
571 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
572 if (file_exists($inforefpath)) {
573 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath); // Load each inforef file to temp_ids
580 * Execution step that will load all the needed files into backup_files_temp
581 * - info: contains the whole original object (times, names...)
582 * (all them being original ids as loaded from xml)
584 class restore_load_included_files extends restore_structure_step {
586 protected function define_structure() {
588 $file = new restore_path_element('file', '/files/file');
590 return array($file);
593 // Processing functions go here
594 public function process_file($data) {
596 $data = (object)$data; // handy
598 // load it if needed:
599 // - it it is one of the annotated inforef files (course/section/activity/block)
600 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
601 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
602 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
603 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
604 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
605 $data->component == 'grouping' || $data->component == 'grade' ||
606 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
607 if ($isfileref || $iscomponent) {
608 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
614 * Execution step that, *conditionally* (if there isn't preloaded information),
615 * will load all the needed roles to backup_temp_ids. They will be stored with
616 * "role" itemname. Also it will perform one automatic mapping to roles existing
617 * in the target site, based in permissions of the user performing the restore,
618 * archetypes and other bits. At the end, each original role will have its associated
619 * target role or 0 if it's going to be skipped. Note we wrap everything over one
620 * restore_dbops method, as far as the same stuff is going to be also executed
621 * by restore prechecks
623 class restore_load_and_map_roles extends restore_execution_step {
625 protected function define_execution() {
626 if ($this->task->get_preloaded_information()) { // if info is already preloaded
627 return;
630 $file = $this->get_basepath() . '/roles.xml';
631 // Load needed toles to temp_ids
632 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
634 // Process roles, mapping/skipping. Any error throws exception
635 // Note we pass controller's info because it can contain role mapping information
636 // about manual mappings performed by UI
637 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);
642 * Execution step that, *conditionally* (if there isn't preloaded information
643 * and users have been selected in settings, will load all the needed users
644 * to backup_temp_ids. They will be stored with "user" itemname and with
645 * their original contextid as paremitemid
647 class restore_load_included_users extends restore_execution_step {
649 protected function define_execution() {
651 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
652 return;
654 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
655 return;
657 $file = $this->get_basepath() . '/users.xml';
658 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
663 * Execution step that, *conditionally* (if there isn't preloaded information
664 * and users have been selected in settings, will process all the needed users
665 * in order to decide and perform any action with them (create / map / error)
666 * Note: Any error will cause exception, as far as this is the same processing
667 * than the one into restore prechecks (that should have stopped process earlier)
669 class restore_process_included_users extends restore_execution_step {
671 protected function define_execution() {
673 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
674 return;
676 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
677 return;
679 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
684 * Execution step that will create all the needed users as calculated
685 * by @restore_process_included_users (those having newiteind = 0)
687 class restore_create_included_users extends restore_execution_step {
689 protected function define_execution() {
691 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->get_setting_value('user_files'), $this->task->get_userid());
696 * Structure step that will create all the needed groups and groupings
697 * by loading them from the groups.xml file performing the required matches.
698 * Note group members only will be added if restoring user info
700 class restore_groups_structure_step extends restore_structure_step {
702 protected function define_structure() {
704 $paths = array(); // Add paths here
706 $paths[] = new restore_path_element('group', '/groups/group');
707 if ($this->get_setting_value('users')) {
708 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
710 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
711 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
713 return $paths;
716 // Processing functions go here
717 public function process_group($data) {
718 global $DB;
720 $data = (object)$data; // handy
721 $data->courseid = $this->get_courseid();
723 $oldid = $data->id; // need this saved for later
725 $restorefiles = false; // Only if we end creating the group
727 // Search if the group already exists (by name & description) in the target course
728 $description_clause = '';
729 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
730 if (!empty($data->description)) {
731 $description_clause = ' AND ' .
732 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
733 $params['description'] = $data->description;
735 if (!$groupdb = $DB->get_record_sql("SELECT *
736 FROM {groups}
737 WHERE courseid = :courseid
738 AND name = :grname $description_clause", $params)) {
739 // group doesn't exist, create
740 $newitemid = $DB->insert_record('groups', $data);
741 $restorefiles = true; // We'll restore the files
742 } else {
743 // group exists, use it
744 $newitemid = $groupdb->id;
746 // Save the id mapping
747 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
750 public function process_member($data) {
751 global $DB;
753 $data = (object)$data; // handy
755 // get parent group->id
756 $data->groupid = $this->get_new_parentid('group');
758 // map user newitemid and insert if not member already
759 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
760 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
761 $DB->insert_record('groups_members', $data);
766 public function process_grouping($data) {
767 global $DB;
769 $data = (object)$data; // handy
770 $data->courseid = $this->get_courseid();
772 $oldid = $data->id; // need this saved for later
773 $restorefiles = false; // Only if we end creating the grouping
775 // Search if the grouping already exists (by name & description) in the target course
776 $description_clause = '';
777 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
778 if (!empty($data->description)) {
779 $description_clause = ' AND ' .
780 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
781 $params['description'] = $data->description;
783 if (!$groupingdb = $DB->get_record_sql("SELECT *
784 FROM {groupings}
785 WHERE courseid = :courseid
786 AND name = :grname $description_clause", $params)) {
787 // grouping doesn't exist, create
788 $newitemid = $DB->insert_record('groupings', $data);
789 $restorefiles = true; // We'll restore the files
790 } else {
791 // grouping exists, use it
792 $newitemid = $groupingdb->id;
794 // Save the id mapping
795 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
798 public function process_grouping_group($data) {
799 global $DB;
801 $data = (object)$data;
803 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
804 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
805 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
808 protected function after_execute() {
809 // Add group related files, matching with "group" mappings
810 $this->add_related_files('group', 'icon', 'group');
811 $this->add_related_files('group', 'description', 'group');
812 // Add grouping related files, matching with "grouping" mappings
813 $this->add_related_files('grouping', 'description', 'grouping');
819 * Structure step that will create all the needed scales
820 * by loading them from the scales.xml
822 class restore_scales_structure_step extends restore_structure_step {
824 protected function define_structure() {
826 $paths = array(); // Add paths here
827 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
828 return $paths;
831 protected function process_scale($data) {
832 global $DB;
834 $data = (object)$data;
836 $restorefiles = false; // Only if we end creating the group
838 $oldid = $data->id; // need this saved for later
840 // Look for scale (by 'scale' both in standard (course=0) and current course
841 // with priority to standard scales (ORDER clause)
842 // scale is not course unique, use get_record_sql to suppress warning
843 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
844 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
845 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
846 if (!$scadb = $DB->get_record_sql("SELECT *
847 FROM {scale}
848 WHERE courseid IN (0, :courseid)
849 AND $compare_scale_clause
850 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
851 // Remap the user if possible, defaut to user performing the restore if not
852 $userid = $this->get_mappingid('user', $data->userid);
853 $data->userid = $userid ? $userid : $this->task->get_userid();
854 // Remap the course if course scale
855 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
856 // If global scale (course=0), check the user has perms to create it
857 // falling to course scale if not
858 $systemctx = get_context_instance(CONTEXT_SYSTEM);
859 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
860 $data->courseid = $this->get_courseid();
862 // scale doesn't exist, create
863 $newitemid = $DB->insert_record('scale', $data);
864 $restorefiles = true; // We'll restore the files
865 } else {
866 // scale exists, use it
867 $newitemid = $scadb->id;
869 // Save the id mapping (with files support at system context)
870 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
873 protected function after_execute() {
874 // Add scales related files, matching with "scale" mappings
875 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
881 * Structure step that will create all the needed outocomes
882 * by loading them from the outcomes.xml
884 class restore_outcomes_structure_step extends restore_structure_step {
886 protected function define_structure() {
888 $paths = array(); // Add paths here
889 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
890 return $paths;
893 protected function process_outcome($data) {
894 global $DB;
896 $data = (object)$data;
898 $restorefiles = false; // Only if we end creating the group
900 $oldid = $data->id; // need this saved for later
902 // Look for outcome (by shortname both in standard (courseid=null) and current course
903 // with priority to standard outcomes (ORDER clause)
904 // outcome is not course unique, use get_record_sql to suppress warning
905 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
906 if (!$outdb = $DB->get_record_sql('SELECT *
907 FROM {grade_outcomes}
908 WHERE shortname = :shortname
909 AND (courseid = :courseid OR courseid IS NULL)
910 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
911 // Remap the user
912 $userid = $this->get_mappingid('user', $data->usermodified);
913 $data->usermodified = $userid ? $userid : $this->task->get_userid();
914 // Remap the scale
915 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
916 // Remap the course if course outcome
917 $data->courseid = $data->courseid ? $this->get_courseid() : null;
918 // If global outcome (course=null), check the user has perms to create it
919 // falling to course outcome if not
920 $systemctx = get_context_instance(CONTEXT_SYSTEM);
921 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
922 $data->courseid = $this->get_courseid();
924 // outcome doesn't exist, create
925 $newitemid = $DB->insert_record('grade_outcomes', $data);
926 $restorefiles = true; // We'll restore the files
927 } else {
928 // scale exists, use it
929 $newitemid = $outdb->id;
931 // Set the corresponding grade_outcomes_courses record
932 $outcourserec = new stdclass();
933 $outcourserec->courseid = $this->get_courseid();
934 $outcourserec->outcomeid = $newitemid;
935 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
936 $DB->insert_record('grade_outcomes_courses', $outcourserec);
938 // Save the id mapping (with files support at system context)
939 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
942 protected function after_execute() {
943 // Add outcomes related files, matching with "outcome" mappings
944 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
949 * Execution step that, *conditionally* (if there isn't preloaded information
950 * will load all the question categories and questions (header info only)
951 * to backup_temp_ids. They will be stored with "question_category" and
952 * "question" itemnames and with their original contextid and question category
953 * id as paremitemids
955 class restore_load_categories_and_questions extends restore_execution_step {
957 protected function define_execution() {
959 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
960 return;
962 $file = $this->get_basepath() . '/questions.xml';
963 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
968 * Execution step that, *conditionally* (if there isn't preloaded information)
969 * will process all the needed categories and questions
970 * in order to decide and perform any action with them (create / map / error)
971 * Note: Any error will cause exception, as far as this is the same processing
972 * than the one into restore prechecks (that should have stopped process earlier)
974 class restore_process_categories_and_questions extends restore_execution_step {
976 protected function define_execution() {
978 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
979 return;
981 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
986 * Structure step that will read the section.xml creating/updating sections
987 * as needed, rebuilding course cache and other friends
989 class restore_section_structure_step extends restore_structure_step {
991 protected function define_structure() {
992 $section = new restore_path_element('section', '/section');
994 // Apply for 'format' plugins optional paths at section level
995 $this->add_plugin_structure('format', $section);
997 return array($section);
1000 public function process_section($data) {
1001 global $DB;
1002 $data = (object)$data;
1003 $oldid = $data->id; // We'll need this later
1005 $restorefiles = false;
1007 // Look for the section
1008 $section = new stdclass();
1009 $section->course = $this->get_courseid();
1010 $section->section = $data->number;
1011 // Section doesn't exist, create it with all the info from backup
1012 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1013 $section->name = $data->name;
1014 $section->summary = $data->summary;
1015 $section->summaryformat = $data->summaryformat;
1016 $section->sequence = '';
1017 $section->visible = $data->visible;
1018 $newitemid = $DB->insert_record('course_sections', $section);
1019 $restorefiles = true;
1021 // Section exists, update non-empty information
1022 } else {
1023 $section->id = $secrec->id;
1024 if (empty($secrec->name)) {
1025 $section->name = $data->name;
1027 if (empty($secrec->summary)) {
1028 $section->summary = $data->summary;
1029 $section->summaryformat = $data->summaryformat;
1030 $restorefiles = true;
1032 $DB->update_record('course_sections', $section);
1033 $newitemid = $secrec->id;
1036 // Annotate the section mapping, with restorefiles option if needed
1037 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1039 // set the new course_section id in the task
1040 $this->task->set_sectionid($newitemid);
1043 // Commented out. We never modify course->numsections as far as that is used
1044 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1045 // Note: We keep the code here, to know about and because of the possibility of making this
1046 // optional based on some setting/attribute in the future
1047 // If needed, adjust course->numsections
1048 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1049 // if ($numsections < $section->section) {
1050 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1051 // }
1055 protected function after_execute() {
1056 // Add section related files, with 'course_section' itemid to match
1057 $this->add_related_files('course', 'section', 'course_section');
1063 * Structure step that will read the course.xml file, loading it and performing
1064 * various actions depending of the site/restore settings. Note that target
1065 * course always exist before arriving here so this step will be updating
1066 * the course record (never inserting)
1068 class restore_course_structure_step extends restore_structure_step {
1070 protected function define_structure() {
1072 $course = new restore_path_element('course', '/course');
1073 $category = new restore_path_element('category', '/course/category');
1074 $tag = new restore_path_element('tag', '/course/tags/tag');
1075 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1077 // Apply for 'format' plugins optional paths at course level
1078 $this->add_plugin_structure('format', $course);
1080 // Apply for 'theme' plugins optional paths at course level
1081 $this->add_plugin_structure('theme', $course);
1083 // Apply for 'course report' plugins optional paths at course level
1084 $this->add_plugin_structure('coursereport', $course);
1086 // Apply for plagiarism plugins optional paths at course level
1087 $this->add_plugin_structure('plagiarism', $course);
1089 return array($course, $category, $tag, $allowed_module);
1093 * Processing functions go here
1095 * @global moodledatabase $DB
1096 * @param stdClass $data
1098 public function process_course($data) {
1099 global $CFG, $DB;
1101 $data = (object)$data;
1102 $oldid = $data->id; // We'll need this later
1104 $fullname = $this->get_setting_value('course_fullname');
1105 $shortname = $this->get_setting_value('course_shortname');
1106 $startdate = $this->get_setting_value('course_startdate');
1108 // Calculate final course names, to avoid dupes
1109 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1111 // Need to change some fields before updating the course record
1112 $data->id = $this->get_courseid();
1113 $data->fullname = $fullname;
1114 $data->shortname= $shortname;
1115 $data->idnumber = '';
1117 // Only restrict modules if original course was and target site too for new courses
1118 $data->restrictmodules = $data->restrictmodules && !empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all';
1120 $data->startdate= $this->apply_date_offset($data->startdate);
1121 if ($data->defaultgroupingid) {
1122 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1124 if (empty($CFG->enablecompletion)) {
1125 $data->enablecompletion = 0;
1126 $data->completionstartonenrol = 0;
1127 $data->completionnotify = 0;
1129 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1130 if (!array_key_exists($data->lang, $languages)) {
1131 $data->lang = '';
1134 $themes = get_list_of_themes(); // Get themes for quick search later
1135 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1136 $data->theme = '';
1139 // Course record ready, update it
1140 $DB->update_record('course', $data);
1142 // Role name aliases
1143 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1146 public function process_category($data) {
1147 // Nothing to do with the category. UI sets it before restore starts
1150 public function process_tag($data) {
1151 global $CFG, $DB;
1153 $data = (object)$data;
1155 if (!empty($CFG->usetags)) { // if enabled in server
1156 // TODO: This is highly inneficient. Each time we add one tag
1157 // we fetch all the existing because tag_set() deletes them
1158 // so everything must be reinserted on each call
1159 $tags = array();
1160 $existingtags = tag_get_tags('course', $this->get_courseid());
1161 // Re-add all the existitng tags
1162 foreach ($existingtags as $existingtag) {
1163 $tags[] = $existingtag->rawname;
1165 // Add the one being restored
1166 $tags[] = $data->rawname;
1167 // Send all the tags back to the course
1168 tag_set('course', $this->get_courseid(), $tags);
1172 public function process_allowed_module($data) {
1173 global $CFG, $DB;
1175 $data = (object)$data;
1177 // only if enabled by admin setting
1178 if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all') {
1179 $available = get_plugin_list('mod');
1180 $mname = $data->modulename;
1181 if (array_key_exists($mname, $available)) {
1182 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
1183 $rec = new stdclass();
1184 $rec->course = $this->get_courseid();
1185 $rec->module = $module->id;
1186 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
1187 $DB->insert_record('course_allowed_modules', $rec);
1194 protected function after_execute() {
1195 // Add course related files, without itemid to match
1196 $this->add_related_files('course', 'summary', null);
1197 $this->add_related_files('course', 'legacy', null);
1203 * Structure step that will read the roles.xml file (at course/activity/block levels)
1204 * containig all the role_assignments and overrides for that context. If corresponding to
1205 * one mapped role, they will be applied to target context. Will observe the role_assignments
1206 * setting to decide if ras are restored.
1207 * Note: only ras with component == null are restored as far as the any ra with component
1208 * is handled by one enrolment plugin, hence it will createt the ras later
1210 class restore_ras_and_caps_structure_step extends restore_structure_step {
1212 protected function define_structure() {
1214 $paths = array();
1216 // Observe the role_assignments setting
1217 if ($this->get_setting_value('role_assignments')) {
1218 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1220 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1222 return $paths;
1226 * Assign roles
1228 * This has to be called after enrolments processing.
1230 * @param mixed $data
1231 * @return void
1233 public function process_assignment($data) {
1234 global $DB;
1236 $data = (object)$data;
1238 // Check roleid, userid are one of the mapped ones
1239 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1240 return;
1242 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1243 return;
1245 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1246 // Only assign roles to not deleted users
1247 return;
1249 if (!$contextid = $this->task->get_contextid()) {
1250 return;
1253 if (empty($data->component)) {
1254 // assign standard manual roles
1255 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1256 role_assign($newroleid, $newuserid, $contextid);
1258 } else if ((strpos($data->component, 'enrol_') === 0)) {
1259 // Deal with enrolment roles
1260 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1261 if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
1262 //note: we have to verify component because it might have changed
1263 if ($component === 'enrol_manual') {
1264 // manual is a special case, we do not use components - this owudl happen when converting from other plugin
1265 role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
1266 } else {
1267 role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
1274 public function process_override($data) {
1275 $data = (object)$data;
1277 // Check roleid is one of the mapped ones
1278 $newroleid = $this->get_mappingid('role', $data->roleid);
1279 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1280 if ($newroleid && $this->task->get_contextid()) {
1281 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1282 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1283 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1289 * This structure steps restores the enrol plugins and their underlying
1290 * enrolments, performing all the mappings and/or movements required
1292 class restore_enrolments_structure_step extends restore_structure_step {
1294 protected function define_structure() {
1296 $paths = array();
1298 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1299 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1301 return $paths;
1305 * Create enrolment instances.
1307 * This has to be called after creation of roles
1308 * and before adding of role assignments.
1310 * @param mixed $data
1311 * @return void
1313 public function process_enrol($data) {
1314 global $DB;
1316 $data = (object)$data;
1317 $oldid = $data->id; // We'll need this later
1319 $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);
1321 if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
1322 // TODO: add complex restore support via custom class
1323 debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
1324 $this->set_mapping('enrol', $oldid, 0);
1325 return;
1328 // Perform various checks to decide what to do with the enrol plugin
1329 if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
1330 // TODO: decide if we want to switch to manual enrol - we need UI for this
1331 debugging("Enrol plugin data can not be restored because it is not installed");
1332 $this->set_mapping('enrol', $oldid, 0);
1333 return;
1336 if (!enrol_is_enabled($data->enrol)) {
1337 // TODO: decide if we want to switch to manual enrol - we need UI for this
1338 debugging("Enrol plugin data can not be restored because it is not enabled");
1339 $this->set_mapping('enrol', $oldid, 0);
1340 return;
1343 // map standard fields - plugin has to process custom fields from own restore class
1344 $data->roleid = $this->get_mappingid('role', $data->roleid);
1345 //TODO: should we move the enrol start and end date here?
1347 // always add instance, if the course does not support multiple instances it just returns NULL
1348 $enrol = enrol_get_plugin($data->enrol);
1349 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1350 if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
1351 // ok
1352 } else {
1353 if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
1354 // most probably plugin that supports only one instance
1355 $newitemid = key($instances);
1356 } else {
1357 debugging('Can not create new enrol instance or reuse existing');
1358 $newitemid = 0;
1362 if ($restoretype === ENROL_RESTORE_NOUSERS) {
1363 // plugin requests to prevent restore of any users
1364 $newitemid = 0;
1367 $this->set_mapping('enrol', $oldid, $newitemid);
1371 * Create user enrolments
1373 * This has to be called after creation of enrolment instances
1374 * and before adding of role assignments.
1376 * @param mixed $data
1377 * @return void
1379 public function process_enrolment($data) {
1380 global $DB;
1382 $data = (object)$data;
1384 // Process only if parent instance have been mapped
1385 if ($enrolid = $this->get_new_parentid('enrol')) {
1386 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1387 // And only if user is a mapped one
1388 if ($userid = $this->get_mappingid('user', $data->userid)) {
1389 $enrol = enrol_get_plugin($instance->enrol);
1390 //TODO: do we need specify modifierid?
1391 $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
1392 //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
1401 * This structure steps restores the filters and their configs
1403 class restore_filters_structure_step extends restore_structure_step {
1405 protected function define_structure() {
1407 $paths = array();
1409 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1410 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1412 return $paths;
1415 public function process_active($data) {
1417 $data = (object)$data;
1419 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1420 return;
1422 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1425 public function process_config($data) {
1427 $data = (object)$data;
1429 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1430 return;
1432 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1438 * This structure steps restores the comments
1439 * Note: Cannot use the comments API because defaults to USER->id.
1440 * That should change allowing to pass $userid
1442 class restore_comments_structure_step extends restore_structure_step {
1444 protected function define_structure() {
1446 $paths = array();
1448 $paths[] = new restore_path_element('comment', '/comments/comment');
1450 return $paths;
1453 public function process_comment($data) {
1454 global $DB;
1456 $data = (object)$data;
1458 // First of all, if the comment has some itemid, ask to the task what to map
1459 $mapping = false;
1460 if ($data->itemid) {
1461 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1462 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
1464 // Only restore the comment if has no mapping OR we have found the matching mapping
1465 if (!$mapping || $data->itemid) {
1466 // Only if user mapping and context
1467 $data->userid = $this->get_mappingid('user', $data->userid);
1468 if ($data->userid && $this->task->get_contextid()) {
1469 $data->contextid = $this->task->get_contextid();
1470 // Only if there is another comment with same context/user/timecreated
1471 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1472 if (!$DB->record_exists('comments', $params)) {
1473 $DB->insert_record('comments', $data);
1480 class restore_course_completion_structure_step extends restore_structure_step {
1483 * Conditionally decide if this step should be executed.
1485 * This function checks parameters that are not immediate settings to ensure
1486 * that the enviroment is suitable for the restore of course completion info.
1488 * This function checks the following four parameters:
1490 * 1. Course completion is enabled on the site
1491 * 2. The backup includes course completion information
1492 * 3. All modules are restorable
1493 * 4. All modules are marked for restore.
1495 * @return bool True is safe to execute, false otherwise
1497 protected function execute_condition() {
1498 global $CFG;
1500 // First check course completion is enabled on this site
1501 if (empty($CFG->enablecompletion)) {
1502 // Disabled, don't restore course completion
1503 return false;
1506 // Check it is included in the backup
1507 $fullpath = $this->task->get_taskbasepath();
1508 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1509 if (!file_exists($fullpath)) {
1510 // Not found, can't restore course completion
1511 return false;
1514 // Check we are able to restore all backed up modules
1515 if ($this->task->is_missing_modules()) {
1516 return false;
1519 // Finally check all modules within the backup are being restored.
1520 if ($this->task->is_excluding_activities()) {
1521 return false;
1524 return true;
1528 * Define the course completion structure
1530 * @return array Array of restore_path_element
1532 protected function define_structure() {
1534 // To know if we are including user completion info
1535 $userinfo = $this->get_setting_value('userscompletion');
1537 $paths = array();
1538 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1539 $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1540 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1542 if ($userinfo) {
1543 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1544 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1547 return $paths;
1552 * Process course completion criteria
1554 * @global moodle_database $DB
1555 * @param stdClass $data
1557 public function process_course_completion_criteria($data) {
1558 global $DB;
1560 $data = (object)$data;
1561 $data->course = $this->get_courseid();
1563 // Apply the date offset to the time end field
1564 $data->timeend = $this->apply_date_offset($data->timeend);
1566 // Map the role from the criteria
1567 if (!empty($data->role)) {
1568 $data->role = $this->get_mappingid('role', $data->role);
1571 $skipcriteria = false;
1573 // If the completion criteria is for a module we need to map the module instance
1574 // to the new module id.
1575 if (!empty($data->moduleinstance) && !empty($data->module)) {
1576 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
1577 if (empty($data->moduleinstance)) {
1578 $skipcriteria = true;
1580 } else {
1581 $data->module = null;
1582 $data->moduleinstance = null;
1585 // We backup the course shortname rather than the ID so that we can match back to the course
1586 if (!empty($data->courseinstanceshortname)) {
1587 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1588 if (!$courseinstanceid) {
1589 $skipcriteria = true;
1591 } else {
1592 $courseinstanceid = null;
1594 $data->courseinstance = $courseinstanceid;
1596 if (!$skipcriteria) {
1597 $params = array(
1598 'course' => $data->course,
1599 'criteriatype' => $data->criteriatype,
1600 'enrolperiod' => $data->enrolperiod,
1601 'courseinstance' => $data->courseinstance,
1602 'module' => $data->module,
1603 'moduleinstance' => $data->moduleinstance,
1604 'timeend' => $data->timeend,
1605 'gradepass' => $data->gradepass,
1606 'role' => $data->role
1608 $newid = $DB->insert_record('course_completion_criteria', $params);
1609 $this->set_mapping('course_completion_criteria', $data->id, $newid);
1614 * Processes course compltion criteria complete records
1616 * @global moodle_database $DB
1617 * @param stdClass $data
1619 public function process_course_completion_crit_compl($data) {
1620 global $DB;
1622 $data = (object)$data;
1624 // This may be empty if criteria could not be restored
1625 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
1627 $data->course = $this->get_courseid();
1628 $data->userid = $this->get_mappingid('user', $data->userid);
1630 if (!empty($data->criteriaid) && !empty($data->userid)) {
1631 $params = array(
1632 'userid' => $data->userid,
1633 'course' => $data->course,
1634 'criteriaid' => $data->criteriaid,
1635 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1637 if (isset($data->gradefinal)) {
1638 $params['gradefinal'] = $data->gradefinal;
1640 if (isset($data->unenroled)) {
1641 $params['unenroled'] = $data->unenroled;
1643 if (isset($data->deleted)) {
1644 $params['deleted'] = $data->deleted;
1646 $DB->insert_record('course_completion_crit_compl', $params);
1651 * Process course completions
1653 * @global moodle_database $DB
1654 * @param stdClass $data
1656 public function process_course_completions($data) {
1657 global $DB;
1659 $data = (object)$data;
1661 $data->course = $this->get_courseid();
1662 $data->userid = $this->get_mappingid('user', $data->userid);
1664 if (!empty($data->userid)) {
1665 $params = array(
1666 'userid' => $data->userid,
1667 'course' => $data->course,
1668 'deleted' => $data->deleted,
1669 'timenotified' => $this->apply_date_offset($data->timenotified),
1670 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1671 'timestarted' => $this->apply_date_offset($data->timestarted),
1672 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1673 'reaggregate' => $data->reaggregate
1675 $DB->insert_record('course_completions', $params);
1680 * Process course completion notification records.
1682 * Note: As of Moodle 2.0 this table is not being used however it has been
1683 * left in in the hopes that one day the functionality there will be completed
1685 * @global moodle_database $DB
1686 * @param stdClass $data
1688 public function process_course_completion_notify($data) {
1689 global $DB;
1691 $data = (object)$data;
1693 $data->course = $this->get_courseid();
1694 if (!empty($data->role)) {
1695 $data->role = $this->get_mappingid('role', $data->role);
1698 $params = array(
1699 'course' => $data->course,
1700 'role' => $data->role,
1701 'message' => $data->message,
1702 'timesent' => $this->apply_date_offset($data->timesent),
1704 $DB->insert_record('course_completion_notify', $params);
1708 * Process course completion aggregate methods
1710 * @global moodle_database $DB
1711 * @param stdClass $data
1713 public function process_course_completion_aggr_methd($data) {
1714 global $DB;
1716 $data = (object)$data;
1718 $data->course = $this->get_courseid();
1720 $params = array(
1721 'course' => $data->course,
1722 'criteriatype' => $data->criteriatype,
1723 'method' => $data->method,
1724 'value' => $data->value,
1726 $DB->insert_record('course_completion_aggr_methd', $params);
1733 * This structure step restores course logs (cmid = 0), delegating
1734 * the hard work to the corresponding {@link restore_logs_processor} passing the
1735 * collection of {@link restore_log_rule} rules to be observed as they are defined
1736 * by the task. Note this is only executed based in the 'logs' setting.
1738 * NOTE: This is executed by final task, to have all the activities already restored
1740 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
1741 * records are. There are others like 'calendar' and 'upload' that will be handled
1742 * later.
1744 * NOTE: All the missing actions (not able to be restored) are sent to logs for
1745 * debugging purposes
1747 class restore_course_logs_structure_step extends restore_structure_step {
1750 * Conditionally decide if this step should be executed.
1752 * This function checks the following four parameters:
1754 * 1. the course/logs.xml file exists
1756 * @return bool true is safe to execute, false otherwise
1758 protected function execute_condition() {
1760 // Check it is included in the backup
1761 $fullpath = $this->task->get_taskbasepath();
1762 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1763 if (!file_exists($fullpath)) {
1764 // Not found, can't restore course logs
1765 return false;
1768 return true;
1771 protected function define_structure() {
1773 $paths = array();
1775 // Simple, one plain level of information contains them
1776 $paths[] = new restore_path_element('log', '/logs/log');
1778 return $paths;
1781 protected function process_log($data) {
1782 global $DB;
1784 $data = (object)($data);
1786 $data->time = $this->apply_date_offset($data->time);
1787 $data->userid = $this->get_mappingid('user', $data->userid);
1788 $data->course = $this->get_courseid();
1789 $data->cmid = 0;
1791 // For any reason user wasn't remapped ok, stop processing this
1792 if (empty($data->userid)) {
1793 return;
1796 // Everything ready, let's delegate to the restore_logs_processor
1798 // Set some fixed values that will save tons of DB requests
1799 $values = array(
1800 'course' => $this->get_courseid());
1801 // Get instance and process log record
1802 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
1804 // If we have data, insert it, else something went wrong in the restore_logs_processor
1805 if ($data) {
1806 $DB->insert_record('log', $data);
1812 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
1813 * sharing its same structure but modifying the way records are handled
1815 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
1817 protected function process_log($data) {
1818 global $DB;
1820 $data = (object)($data);
1822 $data->time = $this->apply_date_offset($data->time);
1823 $data->userid = $this->get_mappingid('user', $data->userid);
1824 $data->course = $this->get_courseid();
1825 $data->cmid = $this->task->get_moduleid();
1827 // For any reason user wasn't remapped ok, stop processing this
1828 if (empty($data->userid)) {
1829 return;
1832 // Everything ready, let's delegate to the restore_logs_processor
1834 // Set some fixed values that will save tons of DB requests
1835 $values = array(
1836 'course' => $this->get_courseid(),
1837 'course_module' => $this->task->get_moduleid(),
1838 $this->task->get_modulename() => $this->task->get_activityid());
1839 // Get instance and process log record
1840 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
1842 // If we have data, insert it, else something went wrong in the restore_logs_processor
1843 if ($data) {
1844 $DB->insert_record('log', $data);
1850 * This structure step restores the grade items associated with one activity
1851 * All the grade items are made child of the "course" grade item but the original
1852 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
1853 * the complete gradebook (categories and calculations), that information is
1854 * available there
1856 class restore_activity_grades_structure_step extends restore_structure_step {
1858 protected function define_structure() {
1860 $paths = array();
1861 $userinfo = $this->get_setting_value('userinfo');
1863 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
1864 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
1865 if ($userinfo) {
1866 $paths[] = new restore_path_element('grade_grade',
1867 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
1869 return $paths;
1872 protected function process_grade_item($data) {
1873 global $DB;
1875 $data = (object)($data);
1876 $oldid = $data->id; // We'll need these later
1877 $oldparentid = $data->categoryid;
1878 $courseid = $this->get_courseid();
1880 // make sure top course category exists, all grade items will be associated
1881 // to it. Later, if restoring the whole gradebook, categories will be introduced
1882 $coursecat = grade_category::fetch_course_category($courseid);
1883 $coursecatid = $coursecat->id; // Get the categoryid to be used
1885 $idnumber = null;
1886 if (!empty($data->idnumber)) {
1887 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
1888 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
1889 // so the best is to keep the ones already in the gradebook
1890 // Potential problem: duplicates if same items are restored more than once. :-(
1891 // This needs to be fixed in some way (outcomes & activities with multiple items)
1892 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
1893 // In any case, verify always for uniqueness
1894 $sql = "SELECT cm.id
1895 FROM {course_modules} cm
1896 WHERE cm.course = :courseid AND
1897 cm.idnumber = :idnumber AND
1898 cm.id <> :cmid";
1899 $params = array(
1900 'courseid' => $courseid,
1901 'idnumber' => $data->idnumber,
1902 'cmid' => $this->task->get_moduleid()
1904 if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
1905 $idnumber = $data->idnumber;
1909 unset($data->id);
1910 $data->categoryid = $coursecatid;
1911 $data->courseid = $this->get_courseid();
1912 $data->iteminstance = $this->task->get_activityid();
1913 $data->idnumber = $idnumber;
1914 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1915 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
1916 $data->timecreated = $this->apply_date_offset($data->timecreated);
1917 $data->timemodified = $this->apply_date_offset($data->timemodified);
1919 $gradeitem = new grade_item($data, false);
1920 $gradeitem->insert('restore');
1922 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
1923 $gradeitem->sortorder = $data->sortorder;
1924 $gradeitem->update('restore');
1926 // Set mapping, saving the original category id into parentitemid
1927 // gradebook restore (final task) will need it to reorganise items
1928 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
1931 protected function process_grade_grade($data) {
1932 $data = (object)($data);
1934 unset($data->id);
1935 $data->itemid = $this->get_new_parentid('grade_item');
1936 $data->userid = $this->get_mappingid('user', $data->userid);
1937 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
1938 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
1939 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
1940 $data->overridden = $this->apply_date_offset($data->overridden);
1942 $grade = new grade_grade($data, false);
1943 $grade->insert('restore');
1944 // no need to save any grade_grade mapping
1948 * process activity grade_letters. Note that, while these are possible,
1949 * because grade_letters are contextid based, in proctice, only course
1950 * context letters can be defined. So we keep here this method knowing
1951 * it won't be executed ever. gradebook restore will restore course letters.
1953 protected function process_grade_letter($data) {
1954 global $DB;
1956 $data = (object)$data;
1958 $data->contextid = $this->task->get_contextid();
1959 $newitemid = $DB->insert_record('grade_letters', $data);
1960 // no need to save any grade_letter mapping
1966 * This structure steps restores one instance + positions of one block
1967 * Note: Positions corresponding to one existing context are restored
1968 * here, but all the ones having unknown contexts are sent to backup_ids
1969 * for a later chance to be restored at the end (final task)
1971 class restore_block_instance_structure_step extends restore_structure_step {
1973 protected function define_structure() {
1975 $paths = array();
1977 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
1978 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
1980 return $paths;
1983 public function process_block($data) {
1984 global $DB, $CFG;
1986 $data = (object)$data; // Handy
1987 $oldcontextid = $data->contextid;
1988 $oldid = $data->id;
1989 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1991 // Look for the parent contextid
1992 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1993 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1996 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
1997 // If there is already one block of that type in the parent context
1998 // and the block is not multiple, stop processing
1999 // Use blockslib loader / method executor
2000 if (!block_method_result($data->blockname, 'instance_allow_multiple')) {
2001 if ($DB->record_exists_sql("SELECT bi.id
2002 FROM {block_instances} bi
2003 JOIN {block} b ON b.name = bi.blockname
2004 WHERE bi.parentcontextid = ?
2005 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
2006 return false;
2010 // If there is already one block of that type in the parent context
2011 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
2012 // stop processing
2013 $params = array(
2014 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
2015 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
2016 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
2017 if ($birecs = $DB->get_records('block_instances', $params)) {
2018 foreach($birecs as $birec) {
2019 if ($birec->configdata == $data->configdata) {
2020 return false;
2025 // Set task old contextid, blockid and blockname once we know them
2026 $this->task->set_old_contextid($oldcontextid);
2027 $this->task->set_old_blockid($oldid);
2028 $this->task->set_blockname($data->blockname);
2030 // Let's look for anything within configdata neededing processing
2031 // (nulls and uses of legacy file.php)
2032 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
2033 $configdata = (array)unserialize(base64_decode($data->configdata));
2034 foreach ($configdata as $attribute => $value) {
2035 if (in_array($attribute, $attrstotransform)) {
2036 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
2039 $data->configdata = base64_encode(serialize((object)$configdata));
2042 // Create the block instance
2043 $newitemid = $DB->insert_record('block_instances', $data);
2044 // Save the mapping (with restorefiles support)
2045 $this->set_mapping('block_instance', $oldid, $newitemid, true);
2046 // Create the block context
2047 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
2048 // Save the block contexts mapping and sent it to task
2049 $this->set_mapping('context', $oldcontextid, $newcontextid);
2050 $this->task->set_contextid($newcontextid);
2051 $this->task->set_blockid($newitemid);
2053 // Restore block fileareas if declared
2054 $component = 'block_' . $this->task->get_blockname();
2055 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
2056 $this->add_related_files($component, $filearea, null);
2059 // Process block positions, creating them or accumulating for final step
2060 foreach($positions as $position) {
2061 $position = (object)$position;
2062 $position->blockinstanceid = $newitemid; // The instance is always the restored one
2063 // If position is for one already mapped (known) contextid
2064 // process it now, creating the position
2065 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
2066 $position->contextid = $newpositionctxid;
2067 // Create the block position
2068 $DB->insert_record('block_positions', $position);
2070 // The position belongs to an unknown context, send it to backup_ids
2071 // to process them as part of the final steps of restore. We send the
2072 // whole $position object there, hence use the low level method.
2073 } else {
2074 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
2081 * Structure step to restore common course_module information
2083 * This step will process the module.xml file for one activity, in order to restore
2084 * the corresponding information to the course_modules table, skipping various bits
2085 * of information based on CFG settings (groupings, completion...) in order to fullfill
2086 * all the reqs to be able to create the context to be used by all the rest of steps
2087 * in the activity restore task
2089 class restore_module_structure_step extends restore_structure_step {
2091 protected function define_structure() {
2092 global $CFG;
2094 $paths = array();
2096 $module = new restore_path_element('module', '/module');
2097 $paths[] = $module;
2098 if ($CFG->enableavailability) {
2099 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
2102 // Apply for 'format' plugins optional paths at module level
2103 $this->add_plugin_structure('format', $module);
2105 // Apply for 'plagiarism' plugins optional paths at module level
2106 $this->add_plugin_structure('plagiarism', $module);
2108 return $paths;
2111 protected function process_module($data) {
2112 global $CFG, $DB;
2114 $data = (object)$data;
2115 $oldid = $data->id;
2117 $this->task->set_old_moduleversion($data->version);
2119 $data->course = $this->task->get_courseid();
2120 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
2121 // Map section (first try by course_section mapping match. Useful in course and section restores)
2122 $data->section = $this->get_mappingid('course_section', $data->sectionid);
2123 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
2124 $params = array(
2125 'course' => $this->get_courseid(),
2126 'section' => $data->sectionnumber);
2127 $data->section = $DB->get_field('course_sections', 'id', $params);
2129 if (!$data->section) { // sectionnumber failed, try to get first section in course
2130 $params = array(
2131 'course' => $this->get_courseid());
2132 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
2134 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
2135 $sectionrec = array(
2136 'course' => $this->get_courseid(),
2137 'section' => 0);
2138 $DB->insert_record('course_sections', $sectionrec); // section 0
2139 $sectionrec = array(
2140 'course' => $this->get_courseid(),
2141 'section' => 1);
2142 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
2144 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
2145 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
2146 $data->groupmembersonly = 0;
2148 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
2149 $data->idnumber = '';
2151 if (empty($CFG->enablecompletion)) { // completion
2152 $data->completion = 0;
2153 $data->completiongradeitemnumber = null;
2154 $data->completionview = 0;
2155 $data->completionexpected = 0;
2156 } else {
2157 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
2159 if (empty($CFG->enableavailability)) {
2160 $data->availablefrom = 0;
2161 $data->availableuntil = 0;
2162 $data->showavailability = 0;
2163 } else {
2164 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
2165 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
2167 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
2169 // course_module record ready, insert it
2170 $newitemid = $DB->insert_record('course_modules', $data);
2171 // save mapping
2172 $this->set_mapping('course_module', $oldid, $newitemid);
2173 // set the new course_module id in the task
2174 $this->task->set_moduleid($newitemid);
2175 // we can now create the context safely
2176 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
2177 // set the new context id in the task
2178 $this->task->set_contextid($ctxid);
2179 // update sequence field in course_section
2180 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
2181 $sequence .= ',' . $newitemid;
2182 } else {
2183 $sequence = $newitemid;
2185 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
2189 protected function process_availability($data) {
2190 $data = (object)$data;
2191 // Simply going to store the whole availability record now, we'll process
2192 // all them later in the final task (once all actvivities have been restored)
2193 // Let's call the low level one to be able to store the whole object
2194 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
2195 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
2200 * Structure step that will process the user activity completion
2201 * information if all these conditions are met:
2202 * - Target site has completion enabled ($CFG->enablecompletion)
2203 * - Activity includes completion info (file_exists)
2205 class restore_userscompletion_structure_step extends restore_structure_step {
2206 private $done = array();
2209 * To conditionally decide if this step must be executed
2210 * Note the "settings" conditions are evaluated in the
2211 * corresponding task. Here we check for other conditions
2212 * not being restore settings (files, site settings...)
2214 protected function execute_condition() {
2215 global $CFG;
2217 // Completion disabled in this site, don't execute
2218 if (empty($CFG->enablecompletion)) {
2219 return false;
2222 // No user completion info found, don't execute
2223 $fullpath = $this->task->get_taskbasepath();
2224 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2225 if (!file_exists($fullpath)) {
2226 return false;
2229 // Arrived here, execute the step
2230 return true;
2233 protected function define_structure() {
2235 $paths = array();
2237 $paths[] = new restore_path_element('completion', '/completions/completion');
2239 return $paths;
2242 protected function process_completion($data) {
2243 global $DB;
2245 $data = (object)$data;
2247 $data->coursemoduleid = $this->task->get_moduleid();
2248 $data->userid = $this->get_mappingid('user', $data->userid);
2249 $data->timemodified = $this->apply_date_offset($data->timemodified);
2251 // Check we didn't already insert one for this cmid and userid
2252 // (there aren't supposed to be duplicates in that field, but
2253 // it was possible until MDL-28021 was fixed).
2254 $key = $data->coursemoduleid . ',' . $data->userid;
2255 if (array_key_exists($key, $this->done)) {
2256 // Find the existing record
2257 $existing = $DB->get_record('course_modules_completion', array(
2258 'coursemoduleid' => $data->coursemoduleid,
2259 'userid' => $data->userid), 'id, timemodified');
2260 // Update it to these new values, but only if the time is newer
2261 if ($existing->timemodified < $data->timemodified) {
2262 $data->id = $existing->id;
2263 $DB->update_record('course_modules_completion', $data);
2265 } else {
2266 // Normal entry where it doesn't exist already
2267 $DB->insert_record('course_modules_completion', $data);
2268 // Remember this entry
2269 $this->done[$key] = true;
2273 protected function after_execute() {
2274 // This gets called once per activity (according to my testing).
2275 // Clearing the array isn't strictly required, but avoids using
2276 // unnecessary memory.
2277 $this->done = array();
2282 * Abstract structure step, parent of all the activity structure steps. Used to suuport
2283 * the main <activity ...> tag and process it. Also provides subplugin support for
2284 * activities.
2286 abstract class restore_activity_structure_step extends restore_structure_step {
2288 protected function add_subplugin_structure($subplugintype, $element) {
2290 global $CFG;
2292 // Check the requested subplugintype is a valid one
2293 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
2294 if (!file_exists($subpluginsfile)) {
2295 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
2297 include($subpluginsfile);
2298 if (!array_key_exists($subplugintype, $subplugins)) {
2299 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
2301 // Get all the restore path elements, looking across all the subplugin dirs
2302 $subpluginsdirs = get_plugin_list($subplugintype);
2303 foreach ($subpluginsdirs as $name => $subpluginsdir) {
2304 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
2305 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
2306 if (file_exists($restorefile)) {
2307 require_once($restorefile);
2308 $restoresubplugin = new $classname($subplugintype, $name, $this);
2309 // Add subplugin paths to the step
2310 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
2316 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
2317 * have the parent task available for wrapping purposes (get course/context....)
2318 * @return restore_task
2320 public function get_task() {
2321 return $this->task;
2325 * Adds support for the 'activity' path that is common to all the activities
2326 * and will be processed globally here
2328 protected function prepare_activity_structure($paths) {
2330 $paths[] = new restore_path_element('activity', '/activity');
2332 return $paths;
2336 * Process the activity path, informing the task about various ids, needed later
2338 protected function process_activity($data) {
2339 $data = (object)$data;
2340 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
2341 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
2342 $this->task->set_old_activityid($data->id); // Save old activityid in task
2346 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
2347 * and will adjust the new activity id (the instance) in various places
2349 protected function apply_activity_instance($newitemid) {
2350 global $DB;
2352 $this->task->set_activityid($newitemid); // Save activity id in task
2353 // Apply the id to course_sections->instanceid
2354 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
2355 // Do the mapping for modulename, preparing it for files by oldcontext
2356 $modulename = $this->task->get_modulename();
2357 $oldid = $this->task->get_old_activityid();
2358 $this->set_mapping($modulename, $oldid, $newitemid, true);
2363 * Structure step in charge of creating/mapping all the qcats and qs
2364 * by parsing the questions.xml file and checking it against the
2365 * results calculated by {@link restore_process_categories_and_questions}
2366 * and stored in backup_ids_temp
2368 class restore_create_categories_and_questions extends restore_structure_step {
2370 protected function define_structure() {
2372 $category = new restore_path_element('question_category', '/question_categories/question_category');
2373 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
2374 $hint = new restore_path_element('question_hint',
2375 '/question_categories/question_category/questions/question/question_hints/question_hint');
2377 // Apply for 'qtype' plugins optional paths at question level
2378 $this->add_plugin_structure('qtype', $question);
2380 return array($category, $question, $hint);
2383 protected function process_question_category($data) {
2384 global $DB;
2386 $data = (object)$data;
2387 $oldid = $data->id;
2389 // Check we have one mapping for this category
2390 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
2391 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
2394 // Check we have to create the category (newitemid = 0)
2395 if ($mapping->newitemid) {
2396 return; // newitemid != 0, this category is going to be mapped. Nothing to do
2399 // Arrived here, newitemid = 0, we need to create the category
2400 // we'll do it at parentitemid context, but for CONTEXT_MODULE
2401 // categories, that will be created at CONTEXT_COURSE and moved
2402 // to module context later when the activity is created
2403 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
2404 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
2406 $data->contextid = $mapping->parentitemid;
2408 // Let's create the question_category and save mapping
2409 $newitemid = $DB->insert_record('question_categories', $data);
2410 $this->set_mapping('question_category', $oldid, $newitemid);
2411 // Also annotate them as question_category_created, we need
2412 // that later when remapping parents
2413 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
2416 protected function process_question($data) {
2417 global $DB;
2419 $data = (object)$data;
2420 $oldid = $data->id;
2422 // Check we have one mapping for this question
2423 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
2424 return; // No mapping = this question doesn't need to be created/mapped
2427 // Get the mapped category (cannot use get_new_parentid() because not
2428 // all the categories have been created, so it is not always available
2429 // Instead we get the mapping for the question->parentitemid because
2430 // we have loaded qcatids there for all parsed questions
2431 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
2433 // In the past, there were some very sloppy values of penalty. Fix them.
2434 if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
2435 $data->penalty = 0.3333333;
2437 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
2438 $data->penalty = 0.6666667;
2440 if ($data->penalty >= 1) {
2441 $data->penalty = 1;
2444 $data->timecreated = $this->apply_date_offset($data->timecreated);
2445 $data->timemodified = $this->apply_date_offset($data->timemodified);
2447 $userid = $this->get_mappingid('user', $data->createdby);
2448 $data->createdby = $userid ? $userid : $this->task->get_userid();
2450 $userid = $this->get_mappingid('user', $data->modifiedby);
2451 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
2453 // With newitemid = 0, let's create the question
2454 if (!$questionmapping->newitemid) {
2455 $newitemid = $DB->insert_record('question', $data);
2456 $this->set_mapping('question', $oldid, $newitemid);
2457 // Also annotate them as question_created, we need
2458 // that later when remapping parents (keeping the old categoryid as parentid)
2459 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
2460 } else {
2461 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
2462 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
2463 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
2466 // Note, we don't restore any question files yet
2467 // as far as the CONTEXT_MODULE categories still
2468 // haven't their contexts to be restored to
2469 // The {@link restore_create_question_files}, executed in the final step
2470 // step will be in charge of restoring all the question files
2473 protected function process_question_hint($data) {
2474 global $DB;
2476 $data = (object)$data;
2477 $oldid = $data->id;
2479 // Detect if the question is created or mapped
2480 $oldquestionid = $this->get_old_parentid('question');
2481 $newquestionid = $this->get_new_parentid('question');
2482 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
2484 // If the question has been created by restore, we need to create its question_answers too
2485 if ($questioncreated) {
2486 // Adjust some columns
2487 $data->questionid = $newquestionid;
2488 // Insert record
2489 $newitemid = $DB->insert_record('question_hints', $data);
2491 // The question existed, we need to map the existing question_hints
2492 } else {
2493 // Look in question_hints by hint text matching
2494 $sql = 'SELECT id
2495 FROM {question_hints}
2496 WHERE questionid = ?
2497 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
2498 $params = array($newquestionid, $data->hint);
2499 $newitemid = $DB->get_field_sql($sql, $params);
2500 // If we haven't found the newitemid, something has gone really wrong, question in DB
2501 // is missing hints, exception
2502 if (!$newitemid) {
2503 $info = new stdClass();
2504 $info->filequestionid = $oldquestionid;
2505 $info->dbquestionid = $newquestionid;
2506 $info->hint = $data->hint;
2507 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
2510 // Create mapping (I'm not sure if this is really needed?)
2511 $this->set_mapping('question_hint', $oldid, $newitemid);
2514 protected function after_execute() {
2515 global $DB;
2517 // First of all, recode all the created question_categories->parent fields
2518 $qcats = $DB->get_records('backup_ids_temp', array(
2519 'backupid' => $this->get_restoreid(),
2520 'itemname' => 'question_category_created'));
2521 foreach ($qcats as $qcat) {
2522 $newparent = 0;
2523 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
2524 // Get new parent (mapped or created, so we look in quesiton_category mappings)
2525 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2526 'backupid' => $this->get_restoreid(),
2527 'itemname' => 'question_category',
2528 'itemid' => $dbcat->parent))) {
2529 // contextids must match always, as far as we always include complete qbanks, just check it
2530 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
2531 if ($dbcat->contextid == $newparentctxid) {
2532 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
2533 } else {
2534 $newparent = 0; // No ctx match for both cats, no parent relationship
2537 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
2538 if (!$newparent) {
2539 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
2543 // Now, recode all the created question->parent fields
2544 $qs = $DB->get_records('backup_ids_temp', array(
2545 'backupid' => $this->get_restoreid(),
2546 'itemname' => 'question_created'));
2547 foreach ($qs as $q) {
2548 $newparent = 0;
2549 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
2550 // Get new parent (mapped or created, so we look in question mappings)
2551 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2552 'backupid' => $this->get_restoreid(),
2553 'itemname' => 'question',
2554 'itemid' => $dbq->parent))) {
2555 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
2559 // Note, we don't restore any question files yet
2560 // as far as the CONTEXT_MODULE categories still
2561 // haven't their contexts to be restored to
2562 // The {@link restore_create_question_files}, executed in the final step
2563 // step will be in charge of restoring all the question files
2568 * Execution step that will move all the CONTEXT_MODULE question categories
2569 * created at early stages of restore in course context (because modules weren't
2570 * created yet) to their target module (matching by old-new-contextid mapping)
2572 class restore_move_module_questions_categories extends restore_execution_step {
2574 protected function define_execution() {
2575 global $DB;
2577 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
2578 foreach ($contexts as $contextid => $contextlevel) {
2579 // Only if context mapping exists (i.e. the module has been restored)
2580 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
2581 // Update all the qcats having their parentitemid set to the original contextid
2582 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
2583 FROM {backup_ids_temp}
2584 WHERE backupid = ?
2585 AND itemname = 'question_category'
2586 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
2587 foreach ($modulecats as $modulecat) {
2588 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
2589 // And set new contextid also in question_category mapping (will be
2590 // used by {@link restore_create_question_files} later
2591 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
2599 * Execution step that will create all the question/answers/qtype-specific files for the restored
2600 * questions. It must be executed after {@link restore_move_module_questions_categories}
2601 * because only then each question is in its final category and only then the
2602 * context can be determined
2604 * TODO: Improve this. Instead of looping over each question, it can be reduced to
2605 * be done by contexts (this will save a huge ammount of queries)
2607 class restore_create_question_files extends restore_execution_step {
2609 protected function define_execution() {
2610 global $DB;
2612 // Let's process only created questions
2613 $questionsrs = $DB->get_recordset_sql("SELECT bi.itemid, bi.newitemid, bi.parentitemid, q.qtype
2614 FROM {backup_ids_temp} bi
2615 JOIN {question} q ON q.id = bi.newitemid
2616 WHERE bi.backupid = ?
2617 AND bi.itemname = 'question_created'", array($this->get_restoreid()));
2618 foreach ($questionsrs as $question) {
2619 // Get question_category mapping, it contains the target context for the question
2620 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $question->parentitemid)) {
2621 // Something went really wrong, cannot find the question_category for the question
2622 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
2623 continue;
2625 // Calculate source and target contexts
2626 $oldctxid = $qcatmapping->info->contextid;
2627 $newctxid = $qcatmapping->parentitemid;
2629 // Add common question files (question and question_answer ones)
2630 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
2631 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2632 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
2633 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2634 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
2635 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
2636 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
2637 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
2638 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
2639 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true);
2640 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
2641 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2642 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
2643 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2644 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
2645 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2646 // Add qtype dependent files
2647 $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
2648 foreach ($components as $component => $fileareas) {
2649 foreach ($fileareas as $filearea => $mapping) {
2650 // Use itemid only if mapping is question_created
2651 $itemid = ($mapping == 'question_created') ? $question->itemid : null;
2652 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
2653 $oldctxid, $this->task->get_userid(), $mapping, $itemid, $newctxid, true);
2657 $questionsrs->close();
2662 * Abstract structure step, to be used by all the activities using core questions stuff
2663 * (like the quiz module), to support qtype plugins, states and sessions
2665 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
2666 /** @var array question_attempt->id to qtype. */
2667 protected $qtypes = array();
2668 /** @var array question_attempt->id to questionid. */
2669 protected $newquestionids = array();
2672 * Attach below $element (usually attempts) the needed restore_path_elements
2673 * to restore question_usages and all they contain.
2675 protected function add_question_usages($element, &$paths) {
2676 // Check $element is restore_path_element
2677 if (! $element instanceof restore_path_element) {
2678 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2680 // Check $paths is one array
2681 if (!is_array($paths)) {
2682 throw new restore_step_exception('paths_must_be_array', $paths);
2684 $paths[] = new restore_path_element('question_usage',
2685 $element->get_path() . '/question_usage');
2686 $paths[] = new restore_path_element('question_attempt',
2687 $element->get_path() . '/question_usage/question_attempts/question_attempt');
2688 $paths[] = new restore_path_element('question_attempt_step',
2689 $element->get_path() . '/question_usage/question_attempts/question_attempt/steps/step',
2690 true);
2691 $paths[] = new restore_path_element('question_attempt_step_data',
2692 $element->get_path() . '/question_usage/question_attempts/question_attempt/steps/step/response/variable');
2696 * Process question_usages
2698 protected function process_question_usage($data) {
2699 global $DB;
2701 // Clear our caches.
2702 $this->qtypes = array();
2703 $this->newquestionids = array();
2705 $data = (object)$data;
2706 $oldid = $data->id;
2708 $oldcontextid = $this->get_task()->get_old_contextid();
2709 $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
2711 // Everything ready, insert (no mapping needed)
2712 $newitemid = $DB->insert_record('question_usages', $data);
2714 $this->inform_new_usage_id($newitemid);
2716 $this->set_mapping('question_usage', $oldid, $newitemid, false);
2720 * When process_question_usage creates the new usage, it calls this method
2721 * to let the activity link to the new usage. For example, the quiz uses
2722 * this method to set quiz_attempts.uniqueid to the new usage id.
2723 * @param integer $newusageid
2725 abstract protected function inform_new_usage_id($newusageid);
2728 * Process question_attempts
2730 protected function process_question_attempt($data) {
2731 global $DB;
2733 $data = (object)$data;
2734 $oldid = $data->id;
2735 $question = $this->get_mapping('question', $data->questionid);
2737 $data->questionusageid = $this->get_new_parentid('question_usage');
2738 $data->questionid = $question->newitemid;
2739 $data->timemodified = $this->apply_date_offset($data->timemodified);
2741 $newitemid = $DB->insert_record('question_attempts', $data);
2743 $this->set_mapping('question_attempt', $oldid, $newitemid);
2744 $this->qtypes[$newitemid] = $question->info->qtype;
2745 $this->newquestionids[$newitemid] = $data->questionid;
2749 * Process question_attempt_steps
2751 protected function process_question_attempt_step($data) {
2752 global $DB;
2754 $data = (object)$data;
2755 $oldid = $data->id;
2757 // Pull out the response data.
2758 $response = array();
2759 if (!empty($data->response['variable'])) {
2760 foreach ($data->response['variable'] as $variable) {
2761 $response[$variable['name']] = $variable['value'];
2764 unset($data->response);
2766 $data->questionattemptid = $this->get_new_parentid('question_attempt');
2767 $data->timecreated = $this->apply_date_offset($data->timecreated);
2768 $data->userid = $this->get_mappingid('user', $data->userid);
2770 // Everything ready, insert and create mapping (needed by question_sessions)
2771 $newitemid = $DB->insert_record('question_attempt_steps', $data);
2772 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
2774 // Now process the response data.
2775 $response = $this->questions_recode_response_data(
2776 $this->qtypes[$data->questionattemptid],
2777 $this->newquestionids[$data->questionattemptid],
2778 $data->sequencenumber, $response);
2779 foreach ($response as $name => $value) {
2780 $row = new stdClass();
2781 $row->attemptstepid = $newitemid;
2782 $row->name = $name;
2783 $row->value = $value;
2784 $DB->insert_record('question_attempt_step_data', $row, false);
2789 * Recode the respones data for a particular step of an attempt at at particular question.
2790 * @param string $qtype the question type.
2791 * @param int $newquestionid the question id.
2792 * @param int $sequencenumber the sequence number.
2793 * @param array $response the response data to recode.
2795 public function questions_recode_response_data(
2796 $qtype, $newquestionid, $sequencenumber, array $response) {
2797 $qtyperestorer = $this->get_qtype_restorer($qtype);
2798 if ($qtyperestorer) {
2799 $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
2801 return $response;
2805 * Given a list of question->ids, separated by commas, returns the
2806 * recoded list, with all the restore question mappings applied.
2807 * Note: Used by quiz->questions and quiz_attempts->layout
2808 * Note: 0 = page break (unconverted)
2810 protected function questions_recode_layout($layout) {
2811 // Extracts question id from sequence
2812 if ($questionids = explode(',', $layout)) {
2813 foreach ($questionids as $id => $questionid) {
2814 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
2815 $newquestionid = $this->get_mappingid('question', $questionid);
2816 $questionids[$id] = $newquestionid;
2820 return implode(',', $questionids);
2824 * Get the restore_qtype_plugin subclass for a specific question type.
2825 * @param string $qtype e.g. multichoice.
2826 * @return restore_qtype_plugin instance.
2828 protected function get_qtype_restorer($qtype) {
2829 // Build one static cache to store {@link restore_qtype_plugin}
2830 // while we are needing them, just to save zillions of instantiations
2831 // or using static stuff that will break our nice API
2832 static $qtypeplugins = array();
2834 if (!isset($qtypeplugins[$qtype])) {
2835 $classname = 'restore_qtype_' . $qtype . '_plugin';
2836 if (class_exists($classname)) {
2837 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
2838 } else {
2839 $qtypeplugins[$qtype] = null;
2842 return $qtypeplugins[$qtype];
2845 protected function after_execute() {
2846 parent::after_execute();
2848 // Restore any files belonging to responses.
2849 foreach (question_engine::get_all_response_file_areas() as $filearea) {
2850 $this->add_related_files('question', $filearea, 'question_attempt_step');
2855 * Attach below $element (usually attempts) the needed restore_path_elements
2856 * to restore question attempt data from Moodle 2.0.
2858 * When using this method, the parent element ($element) must be defined with
2859 * $grouped = true. Then, in that elements process method, you must call
2860 * {@link process_legacy_attempt_data()} with the groupded data. See, for
2861 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
2862 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
2863 * @param array $paths the paths array that is being built to describe the
2864 * structure.
2866 protected function add_legacy_question_attempt_data($element, &$paths) {
2867 global $CFG;
2868 require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
2870 // Check $element is restore_path_element
2871 if (!($element instanceof restore_path_element)) {
2872 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2874 // Check $paths is one array
2875 if (!is_array($paths)) {
2876 throw new restore_step_exception('paths_must_be_array', $paths);
2879 $paths[] = new restore_path_element('question_state',
2880 $element->get_path() . '/states/state');
2881 $paths[] = new restore_path_element('question_session',
2882 $element->get_path() . '/sessions/session');
2885 protected function get_attempt_upgrader() {
2886 if (empty($this->attemptupgrader)) {
2887 $this->attemptupgrader = new question_engine_attempt_upgrader();
2888 $this->attemptupgrader->prepare_to_restore();
2890 return $this->attemptupgrader;
2894 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
2895 * @param object $data contains all the grouped attempt data ot process.
2896 * @param pbject $quiz data about the activity the attempts belong to. Required
2897 * fields are (basically this only works for the quiz module):
2898 * oldquestions => list of question ids in this activity - using old ids.
2899 * preferredbehaviour => the behaviour to use for questionattempts.
2901 protected function process_legacy_quiz_attempt_data($data, $quiz) {
2902 global $DB;
2903 $upgrader = $this->get_attempt_upgrader();
2905 $data = (object)$data;
2907 $layout = explode(',', $data->layout);
2908 $newlayout = $layout;
2910 // Convert each old question_session into a question_attempt.
2911 $qas = array();
2912 foreach (explode(',', $quiz->oldquestions) as $questionid) {
2913 if ($questionid == 0) {
2914 continue;
2917 $newquestionid = $this->get_mappingid('question', $questionid);
2918 if (!$newquestionid) {
2919 throw new restore_step_exception('questionattemptreferstomissingquestion',
2920 $questionid, $questionid);
2923 $question = $upgrader->load_question($newquestionid, $quiz->id);
2925 foreach ($layout as $key => $qid) {
2926 if ($qid == $questionid) {
2927 $newlayout[$key] = $newquestionid;
2931 list($qsession, $qstates) = $this->find_question_session_and_states(
2932 $data, $questionid);
2934 if (empty($qsession) || empty($qstates)) {
2935 throw new restore_step_exception('questionattemptdatamissing',
2936 $questionid, $questionid);
2939 list($qsession, $qstates) = $this->recode_legacy_response_data(
2940 $question, $qsession, $qstates);
2942 $data->layout = implode(',', $newlayout);
2943 $qas[$newquestionid] = $upgrader->convert_question_attempt(
2944 $quiz, $data, $question, $qsession, $qstates);
2947 // Now create a new question_usage.
2948 $usage = new stdClass();
2949 $usage->component = 'mod_quiz';
2950 $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
2951 $usage->preferredbehaviour = $quiz->preferredbehaviour;
2952 $usage->id = $DB->insert_record('question_usages', $usage);
2954 $this->inform_new_usage_id($usage->id);
2956 $data->uniqueid = $usage->id;
2957 $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas, $quiz->questions);
2960 protected function find_question_session_and_states($data, $questionid) {
2961 $qsession = null;
2962 foreach ($data->sessions['session'] as $session) {
2963 if ($session['questionid'] == $questionid) {
2964 $qsession = (object) $session;
2965 break;
2969 $qstates = array();
2970 foreach ($data->states['state'] as $state) {
2971 if ($state['question'] == $questionid) {
2972 // It would be natural to use $state['seq_number'] as the array-key
2973 // here, but it seems that buggy behaviour in 2.0 and early can
2974 // mean that that is not unique, so we use id, which is guaranteed
2975 // to be unique.
2976 $qstates[$state['id']] = (object) $state;
2979 ksort($qstates);
2980 $qstates = array_values($qstates);
2982 return array($qsession, $qstates);
2986 * Recode any ids in the response data
2987 * @param object $question the question data
2988 * @param object $qsession the question sessions.
2989 * @param array $qstates the question states.
2991 protected function recode_legacy_response_data($question, $qsession, $qstates) {
2992 $qsession->questionid = $question->id;
2994 foreach ($qstates as &$state) {
2995 $state->question = $question->id;
2996 $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
2999 return array($qsession, $qstates);
3003 * Recode the legacy answer field.
3004 * @param object $state the state to recode the answer of.
3005 * @param string $qtype the question type.
3007 public function restore_recode_legacy_answer($state, $qtype) {
3008 $restorer = $this->get_qtype_restorer($qtype);
3009 if ($restorer) {
3010 return $restorer->recode_legacy_state_answer($state);
3011 } else {
3012 return $state->answer;