MDL-27639 restore of attempt data from 2.0 - first attempt.
[moodle.git] / backup / moodle2 / restore_stepslib.php
blob22ec715177510bfaaf7a6b7e1f359bfa0d2d5117
2 <?php
4 // This file is part of Moodle - http://moodle.org/
5 //
6 // Moodle is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
11 // Moodle is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 /**
20 * @package moodlecore
21 * @subpackage backup-moodle2
22 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 /**
27 * Define all the restore steps that will be used by common tasks in restore
30 /**
31 * delete old directories and conditionally create backup_temp_ids table
33 class restore_create_and_clean_temp_stuff extends restore_execution_step {
35 protected function define_execution() {
36 $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
37 // If the table already exists, it's because restore_prechecks have been executed in the same
38 // request (without problems) and it already contains a bunch of preloaded information (users...)
39 // that we aren't going to execute again
40 if ($exists) { // Inform plan about preloaded information
41 $this->task->set_preloaded_information();
43 // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
44 $itemid = $this->task->get_old_contextid();
45 $newitemid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
46 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
47 // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
48 $itemid = $this->task->get_old_system_contextid();
49 $newitemid = get_context_instance(CONTEXT_SYSTEM)->id;
50 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
51 // Create the old-course-id to new-course-id mapping, we need that available since the beginning
52 $itemid = $this->task->get_old_courseid();
53 $newitemid = $this->get_courseid();
54 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
59 /**
60 * delete the temp dir used by backup/restore (conditionally),
61 * delete old directories and drop temp ids table
63 class restore_drop_and_clean_temp_stuff extends restore_execution_step {
65 protected function define_execution() {
66 global $CFG;
67 restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
68 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
69 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
70 backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
75 /**
76 * Restore calculated grade items, grade categories etc
78 class restore_gradebook_structure_step extends restore_structure_step {
80 /**
81 * To conditionally decide if this step must be executed
82 * Note the "settings" conditions are evaluated in the
83 * corresponding task. Here we check for other conditions
84 * not being restore settings (files, site settings...)
86 protected function execute_condition() {
87 global $CFG, $DB;
89 // No gradebook info found, don't execute
90 $fullpath = $this->task->get_taskbasepath();
91 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
92 if (!file_exists($fullpath)) {
93 return false;
96 // Some module present in backup file isn't available to restore
97 // in this site, don't execute
98 if ($this->task->is_missing_modules()) {
99 return false;
102 // Some activity has been excluded to be restored, don't execute
103 if ($this->task->is_excluding_activities()) {
104 return false;
107 // There should only be one grade category (the 1 associated with the course itself)
108 // If other categories already exist we're restoring into an existing course.
109 // Restoring categories into a course with an existing category structure is unlikely to go well
110 $category = new stdclass();
111 $category->courseid = $this->get_courseid();
112 $catcount = $DB->count_records('grade_categories', (array)$category);
113 if ($catcount>1) {
114 return false;
117 // Arrived here, execute the step
118 return true;
121 protected function define_structure() {
122 $paths = array();
123 $userinfo = $this->task->get_setting_value('users');
125 $paths[] = new restore_path_element('gradebook', '/gradebook');
126 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
127 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
128 if ($userinfo) {
129 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
131 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
132 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
134 return $paths;
137 protected function process_gradebook($data) {
140 protected function process_grade_item($data) {
141 global $DB;
143 $data = (object)$data;
145 $oldid = $data->id;
146 $data->course = $this->get_courseid();
148 $data->courseid = $this->get_courseid();
150 //manual grade items store category id in categoryid
151 if ($data->itemtype=='manual') {
152 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
153 } //course and category grade items store their category id in iteminstance
154 else if ($data->itemtype=='course' || $data->itemtype=='category') {
155 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
158 $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
159 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
161 $data->locktime = $this->apply_date_offset($data->locktime);
162 $data->timecreated = $this->apply_date_offset($data->timecreated);
163 $data->timemodified = $this->apply_date_offset($data->timemodified);
165 $coursecategory = $newitemid = null;
166 //course grade item should already exist so updating instead of inserting
167 if($data->itemtype=='course') {
168 //get the ID of the already created grade item
169 $gi = new stdclass();
170 $gi->courseid = $this->get_courseid();
171 $gi->itemtype = $data->itemtype;
173 //need to get the id of the grade_category that was automatically created for the course
174 $category = new stdclass();
175 $category->courseid = $this->get_courseid();
176 $category->parent = null;
177 //course category fullname starts out as ? but may be edited
178 //$category->fullname = '?';
179 $coursecategory = $DB->get_record('grade_categories', (array)$category);
180 $gi->iteminstance = $coursecategory->id;
182 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
183 if (!empty($existinggradeitem)) {
184 $data->id = $newitemid = $existinggradeitem->id;
185 $DB->update_record('grade_items', $data);
189 if (empty($newitemid)) {
190 //in case we found the course category but still need to insert the course grade item
191 if ($data->itemtype=='course' && !empty($coursecategory)) {
192 $data->iteminstance = $coursecategory->id;
195 $newitemid = $DB->insert_record('grade_items', $data);
197 $this->set_mapping('grade_item', $oldid, $newitemid);
200 protected function process_grade_grade($data) {
201 global $DB;
203 $data = (object)$data;
204 $oldid = $data->id;
206 $data->itemid = $this->get_new_parentid('grade_item');
208 $data->userid = $this->get_mappingid('user', $data->userid, NULL);
209 $data->usermodified = $this->get_mappingid('user', $data->usermodified, NULL);
210 $data->locktime = $this->apply_date_offset($data->locktime);
211 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
212 $data->overridden = $this->apply_date_offset($data->overridden);
213 $data->timecreated = $this->apply_date_offset($data->timecreated);
214 $data->timemodified = $this->apply_date_offset($data->timemodified);
216 $newitemid = $DB->insert_record('grade_grades', $data);
217 //$this->set_mapping('grade_grade', $oldid, $newitemid);
219 protected function process_grade_category($data) {
220 global $DB;
222 $data = (object)$data;
223 $oldid = $data->id;
225 $data->course = $this->get_courseid();
226 $data->courseid = $data->course;
228 $data->timecreated = $this->apply_date_offset($data->timecreated);
229 $data->timemodified = $this->apply_date_offset($data->timemodified);
231 $newitemid = null;
232 //no parent means a course level grade category. That may have been created when the course was created
233 if(empty($data->parent)) {
234 //parent was being saved as 0 when it should be null
235 $data->parent = null;
237 //get the already created course level grade category
238 $category = new stdclass();
239 $category->courseid = $this->get_courseid();
241 $coursecategory = $DB->get_record('grade_categories', (array)$category);
242 if (!empty($coursecategory)) {
243 $data->id = $newitemid = $coursecategory->id;
244 $DB->update_record('grade_categories', $data);
248 //need to insert a course category
249 if (empty($newitemid)) {
250 $newitemid = $DB->insert_record('grade_categories', $data);
252 $this->set_mapping('grade_category', $oldid, $newitemid);
254 protected function process_grade_letter($data) {
255 global $DB;
257 $data = (object)$data;
258 $oldid = $data->id;
260 $data->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
262 $newitemid = $DB->insert_record('grade_letters', $data);
263 $this->set_mapping('grade_letter', $oldid, $newitemid);
265 protected function process_grade_setting($data) {
266 global $DB;
268 $data = (object)$data;
269 $oldid = $data->id;
271 $data->courseid = $this->get_courseid();
273 $newitemid = $DB->insert_record('grade_settings', $data);
274 //$this->set_mapping('grade_setting', $oldid, $newitemid);
277 //put all activity grade items in the correct grade category and mark all for recalculation
278 protected function after_execute() {
279 global $DB;
281 $conditions = array(
282 'backupid' => $this->get_restoreid(),
283 'itemname' => 'grade_item'//,
284 //'itemid' => $itemid
286 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
288 if (!empty($rs)) {
289 foreach($rs as $grade_item_backup) {
290 $updateobj = new stdclass();
291 $updateobj->id = $grade_item_backup->newitemid;
293 //if this is an activity grade item that needs to be put back in its correct category
294 if (!empty($grade_item_backup->parentitemid)) {
295 $updateobj->categoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid);
296 } else {
297 //mark course and category items as needing to be recalculated
298 $updateobj->needsupdate=1;
300 $DB->update_record('grade_items', $updateobj);
303 $rs->close();
305 //need to correct the grade category path and parent
306 $conditions = array(
307 'courseid' => $this->get_courseid()
309 $grade_category = new stdclass();
311 $rs = $DB->get_recordset('grade_categories', $conditions);
312 if (!empty($rs)) {
313 //get all the parents correct first as grade_category::build_path() loads category parents from the DB
314 foreach($rs as $gc) {
315 if (!empty($gc->parent)) {
316 $grade_category->id = $gc->id;
317 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
318 $DB->update_record('grade_categories', $grade_category);
322 if (isset($grade_category->parent)) {
323 unset($grade_category->parent);
325 $rs->close();
327 $rs = $DB->get_recordset('grade_categories', $conditions);
328 if (!empty($rs)) {
329 //now we can rebuild all the paths
330 foreach($rs as $gc) {
331 $grade_category->id = $gc->id;
332 $grade_category->path = grade_category::build_path($gc);
333 $DB->update_record('grade_categories', $grade_category);
336 $rs->close();
338 //Restore marks items as needing update. Update everything now.
339 grade_regrade_final_grades($this->get_courseid());
344 * decode all the interlinks present in restored content
345 * relying 100% in the restore_decode_processor that handles
346 * both the contents to modify and the rules to be applied
348 class restore_decode_interlinks extends restore_execution_step {
350 protected function define_execution() {
351 // Get the decoder (from the plan)
352 $decoder = $this->task->get_decoder();
353 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
354 // And launch it, everything will be processed
355 $decoder->execute();
360 * first, ensure that we have no gaps in section numbers
361 * and then, rebuid the course cache
363 class restore_rebuild_course_cache extends restore_execution_step {
365 protected function define_execution() {
366 global $DB;
368 // Although there is some sort of auto-recovery of missing sections
369 // present in course/formats... here we check that all the sections
370 // from 0 to MAX(section->section) exist, creating them if necessary
371 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
372 // Iterate over all sections
373 for ($i = 0; $i <= $maxsection; $i++) {
374 // If the section $i doesn't exist, create it
375 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
376 $sectionrec = array(
377 'course' => $this->get_courseid(),
378 'section' => $i);
379 $DB->insert_record('course_sections', $sectionrec); // missing section created
383 // Rebuild cache now that all sections are in place
384 rebuild_course_cache($this->get_courseid());
389 * Review all the tasks having one after_restore method
390 * executing it to perform some final adjustments of information
391 * not available when the task was executed.
393 class restore_execute_after_restore extends restore_execution_step {
395 protected function define_execution() {
397 // Simply call to the execute_after_restore() method of the task
398 // that always is the restore_final_task
399 $this->task->launch_execute_after_restore();
405 * Review all the (pending) block positions in backup_ids, matching by
406 * contextid, creating positions as needed. This is executed by the
407 * final task, once all the contexts have been created
409 class restore_review_pending_block_positions extends restore_execution_step {
411 protected function define_execution() {
412 global $DB;
414 // Get all the block_position objects pending to match
415 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
416 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
417 // Process block positions, creating them or accumulating for final step
418 foreach($rs as $posrec) {
419 // Get the complete position object (stored as info)
420 $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
421 // If position is for one already mapped (known) contextid
422 // process it now, creating the position, else nothing to
423 // do, position finally discarded
424 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
425 $position->contextid = $newctx->newitemid;
426 // Create the block position
427 $DB->insert_record('block_positions', $position);
430 $rs->close();
435 * Process all the saved module availability records in backup_ids, matching
436 * course modules and grade item id once all them have been already restored.
437 * only if all matchings are satisfied the availability condition will be created.
438 * At the same time, it is required for the site to have that functionality enabled.
440 class restore_process_course_modules_availability extends restore_execution_step {
442 protected function define_execution() {
443 global $CFG, $DB;
445 // Site hasn't availability enabled
446 if (empty($CFG->enableavailability)) {
447 return;
450 // Get all the module_availability objects to process
451 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
452 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
453 // Process availabilities, creating them if everything matches ok
454 foreach($rs as $availrec) {
455 $allmatchesok = true;
456 // Get the complete availabilityobject
457 $availability = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_availability', $availrec->itemid)->info;
458 // Map the sourcecmid if needed and possible
459 if (!empty($availability->sourcecmid)) {
460 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
461 if ($newcm) {
462 $availability->sourcecmid = $newcm->newitemid;
463 } else {
464 $allmatchesok = false; // Failed matching, we won't create this availability rule
467 // Map the gradeitemid if needed and possible
468 if (!empty($availability->gradeitemid)) {
469 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
470 if ($newgi) {
471 $availability->gradeitemid = $newgi->newitemid;
472 } else {
473 $allmatchesok = false; // Failed matching, we won't create this availability rule
476 if ($allmatchesok) { // Everything ok, create the availability rule
477 $DB->insert_record('course_modules_availability', $availability);
480 $rs->close();
486 * Execution step that, *conditionally* (if there isn't preloaded information)
487 * will load the inforef files for all the included course/section/activity tasks
488 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
490 class restore_load_included_inforef_records extends restore_execution_step {
492 protected function define_execution() {
494 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
495 return;
498 // Get all the included tasks
499 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
500 foreach ($tasks as $task) {
501 // Load the inforef.xml file if exists
502 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
503 if (file_exists($inforefpath)) {
504 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath); // Load each inforef file to temp_ids
511 * Execution step that will load all the needed files into backup_files_temp
512 * - info: contains the whole original object (times, names...)
513 * (all them being original ids as loaded from xml)
515 class restore_load_included_files extends restore_structure_step {
517 protected function define_structure() {
519 $file = new restore_path_element('file', '/files/file');
521 return array($file);
524 // Processing functions go here
525 public function process_file($data) {
527 $data = (object)$data; // handy
529 // load it if needed:
530 // - it it is one of the annotated inforef files (course/section/activity/block)
531 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
532 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
533 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
534 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
535 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
536 $data->component == 'grouping' || $data->component == 'grade' ||
537 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
538 if ($isfileref || $iscomponent) {
539 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
545 * Execution step that, *conditionally* (if there isn't preloaded information),
546 * will load all the needed roles to backup_temp_ids. They will be stored with
547 * "role" itemname. Also it will perform one automatic mapping to roles existing
548 * in the target site, based in permissions of the user performing the restore,
549 * archetypes and other bits. At the end, each original role will have its associated
550 * target role or 0 if it's going to be skipped. Note we wrap everything over one
551 * restore_dbops method, as far as the same stuff is going to be also executed
552 * by restore prechecks
554 class restore_load_and_map_roles extends restore_execution_step {
556 protected function define_execution() {
557 if ($this->task->get_preloaded_information()) { // if info is already preloaded
558 return;
561 $file = $this->get_basepath() . '/roles.xml';
562 // Load needed toles to temp_ids
563 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
565 // Process roles, mapping/skipping. Any error throws exception
566 // Note we pass controller's info because it can contain role mapping information
567 // about manual mappings performed by UI
568 restore_dbops::process_included_roles($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_info()->role_mappings);
573 * Execution step that, *conditionally* (if there isn't preloaded information
574 * and users have been selected in settings, will load all the needed users
575 * to backup_temp_ids. They will be stored with "user" itemname and with
576 * their original contextid as paremitemid
578 class restore_load_included_users extends restore_execution_step {
580 protected function define_execution() {
582 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
583 return;
585 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
586 return;
588 $file = $this->get_basepath() . '/users.xml';
589 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
594 * Execution step that, *conditionally* (if there isn't preloaded information
595 * and users have been selected in settings, will process all the needed users
596 * in order to decide and perform any action with them (create / map / error)
597 * Note: Any error will cause exception, as far as this is the same processing
598 * than the one into restore prechecks (that should have stopped process earlier)
600 class restore_process_included_users extends restore_execution_step {
602 protected function define_execution() {
604 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
605 return;
607 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
608 return;
610 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
615 * Execution step that will create all the needed users as calculated
616 * by @restore_process_included_users (those having newiteind = 0)
618 class restore_create_included_users extends restore_execution_step {
620 protected function define_execution() {
622 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->get_setting_value('user_files'), $this->task->get_userid());
627 * Structure step that will create all the needed groups and groupings
628 * by loading them from the groups.xml file performing the required matches.
629 * Note group members only will be added if restoring user info
631 class restore_groups_structure_step extends restore_structure_step {
633 protected function define_structure() {
635 $paths = array(); // Add paths here
637 $paths[] = new restore_path_element('group', '/groups/group');
638 if ($this->get_setting_value('users')) {
639 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
641 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
642 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
644 return $paths;
647 // Processing functions go here
648 public function process_group($data) {
649 global $DB;
651 $data = (object)$data; // handy
652 $data->courseid = $this->get_courseid();
654 $oldid = $data->id; // need this saved for later
656 $restorefiles = false; // Only if we end creating the group
658 // Search if the group already exists (by name & description) in the target course
659 $description_clause = '';
660 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
661 if (!empty($data->description)) {
662 $description_clause = ' AND ' .
663 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
664 $params['description'] = $data->description;
666 if (!$groupdb = $DB->get_record_sql("SELECT *
667 FROM {groups}
668 WHERE courseid = :courseid
669 AND name = :grname $description_clause", $params)) {
670 // group doesn't exist, create
671 $newitemid = $DB->insert_record('groups', $data);
672 $restorefiles = true; // We'll restore the files
673 } else {
674 // group exists, use it
675 $newitemid = $groupdb->id;
677 // Save the id mapping
678 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
681 public function process_member($data) {
682 global $DB;
684 $data = (object)$data; // handy
686 // get parent group->id
687 $data->groupid = $this->get_new_parentid('group');
689 // map user newitemid and insert if not member already
690 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
691 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
692 $DB->insert_record('groups_members', $data);
697 public function process_grouping($data) {
698 global $DB;
700 $data = (object)$data; // handy
701 $data->courseid = $this->get_courseid();
703 $oldid = $data->id; // need this saved for later
704 $restorefiles = false; // Only if we end creating the grouping
706 // Search if the grouping already exists (by name & description) in the target course
707 $description_clause = '';
708 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
709 if (!empty($data->description)) {
710 $description_clause = ' AND ' .
711 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
712 $params['description'] = $data->description;
714 if (!$groupingdb = $DB->get_record_sql("SELECT *
715 FROM {groupings}
716 WHERE courseid = :courseid
717 AND name = :grname $description_clause", $params)) {
718 // grouping doesn't exist, create
719 $newitemid = $DB->insert_record('groupings', $data);
720 $restorefiles = true; // We'll restore the files
721 } else {
722 // grouping exists, use it
723 $newitemid = $groupingdb->id;
725 // Save the id mapping
726 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
729 public function process_grouping_group($data) {
730 global $DB;
732 $data = (object)$data;
734 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
735 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
736 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
739 protected function after_execute() {
740 // Add group related files, matching with "group" mappings
741 $this->add_related_files('group', 'icon', 'group');
742 $this->add_related_files('group', 'description', 'group');
743 // Add grouping related files, matching with "grouping" mappings
744 $this->add_related_files('grouping', 'description', 'grouping');
750 * Structure step that will create all the needed scales
751 * by loading them from the scales.xml
753 class restore_scales_structure_step extends restore_structure_step {
755 protected function define_structure() {
757 $paths = array(); // Add paths here
758 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
759 return $paths;
762 protected function process_scale($data) {
763 global $DB;
765 $data = (object)$data;
767 $restorefiles = false; // Only if we end creating the group
769 $oldid = $data->id; // need this saved for later
771 // Look for scale (by 'scale' both in standard (course=0) and current course
772 // with priority to standard scales (ORDER clause)
773 // scale is not course unique, use get_record_sql to suppress warning
774 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
775 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
776 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
777 if (!$scadb = $DB->get_record_sql("SELECT *
778 FROM {scale}
779 WHERE courseid IN (0, :courseid)
780 AND $compare_scale_clause
781 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
782 // Remap the user if possible, defaut to user performing the restore if not
783 $userid = $this->get_mappingid('user', $data->userid);
784 $data->userid = $userid ? $userid : $this->task->get_userid();
785 // Remap the course if course scale
786 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
787 // If global scale (course=0), check the user has perms to create it
788 // falling to course scale if not
789 $systemctx = get_context_instance(CONTEXT_SYSTEM);
790 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
791 $data->courseid = $this->get_courseid();
793 // scale doesn't exist, create
794 $newitemid = $DB->insert_record('scale', $data);
795 $restorefiles = true; // We'll restore the files
796 } else {
797 // scale exists, use it
798 $newitemid = $scadb->id;
800 // Save the id mapping (with files support at system context)
801 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
804 protected function after_execute() {
805 // Add scales related files, matching with "scale" mappings
806 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
812 * Structure step that will create all the needed outocomes
813 * by loading them from the outcomes.xml
815 class restore_outcomes_structure_step extends restore_structure_step {
817 protected function define_structure() {
819 $paths = array(); // Add paths here
820 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
821 return $paths;
824 protected function process_outcome($data) {
825 global $DB;
827 $data = (object)$data;
829 $restorefiles = false; // Only if we end creating the group
831 $oldid = $data->id; // need this saved for later
833 // Look for outcome (by shortname both in standard (courseid=null) and current course
834 // with priority to standard outcomes (ORDER clause)
835 // outcome is not course unique, use get_record_sql to suppress warning
836 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
837 if (!$outdb = $DB->get_record_sql('SELECT *
838 FROM {grade_outcomes}
839 WHERE shortname = :shortname
840 AND (courseid = :courseid OR courseid IS NULL)
841 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
842 // Remap the user
843 $userid = $this->get_mappingid('user', $data->usermodified);
844 $data->usermodified = $userid ? $userid : $this->task->get_userid();
845 // Remap the scale
846 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
847 // Remap the course if course outcome
848 $data->courseid = $data->courseid ? $this->get_courseid() : null;
849 // If global outcome (course=null), check the user has perms to create it
850 // falling to course outcome if not
851 $systemctx = get_context_instance(CONTEXT_SYSTEM);
852 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
853 $data->courseid = $this->get_courseid();
855 // outcome doesn't exist, create
856 $newitemid = $DB->insert_record('grade_outcomes', $data);
857 $restorefiles = true; // We'll restore the files
858 } else {
859 // scale exists, use it
860 $newitemid = $outdb->id;
862 // Set the corresponding grade_outcomes_courses record
863 $outcourserec = new stdclass();
864 $outcourserec->courseid = $this->get_courseid();
865 $outcourserec->outcomeid = $newitemid;
866 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
867 $DB->insert_record('grade_outcomes_courses', $outcourserec);
869 // Save the id mapping (with files support at system context)
870 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
873 protected function after_execute() {
874 // Add outcomes related files, matching with "outcome" mappings
875 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
880 * Execution step that, *conditionally* (if there isn't preloaded information
881 * will load all the question categories and questions (header info only)
882 * to backup_temp_ids. They will be stored with "question_category" and
883 * "question" itemnames and with their original contextid and question category
884 * id as paremitemids
886 class restore_load_categories_and_questions extends restore_execution_step {
888 protected function define_execution() {
890 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
891 return;
893 $file = $this->get_basepath() . '/questions.xml';
894 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
899 * Execution step that, *conditionally* (if there isn't preloaded information)
900 * will process all the needed categories and questions
901 * in order to decide and perform any action with them (create / map / error)
902 * Note: Any error will cause exception, as far as this is the same processing
903 * than the one into restore prechecks (that should have stopped process earlier)
905 class restore_process_categories_and_questions extends restore_execution_step {
907 protected function define_execution() {
909 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
910 return;
912 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
917 * Structure step that will read the section.xml creating/updating sections
918 * as needed, rebuilding course cache and other friends
920 class restore_section_structure_step extends restore_structure_step {
922 protected function define_structure() {
923 $section = new restore_path_element('section', '/section');
925 // Apply for 'format' plugins optional paths at section level
926 $this->add_plugin_structure('format', $section);
928 return array($section);
931 public function process_section($data) {
932 global $DB;
933 $data = (object)$data;
934 $oldid = $data->id; // We'll need this later
936 $restorefiles = false;
938 // Look for the section
939 $section = new stdclass();
940 $section->course = $this->get_courseid();
941 $section->section = $data->number;
942 // Section doesn't exist, create it with all the info from backup
943 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
944 $section->name = $data->name;
945 $section->summary = $data->summary;
946 $section->summaryformat = $data->summaryformat;
947 $section->sequence = '';
948 $section->visible = $data->visible;
949 $newitemid = $DB->insert_record('course_sections', $section);
950 $restorefiles = true;
952 // Section exists, update non-empty information
953 } else {
954 $section->id = $secrec->id;
955 if (empty($secrec->name)) {
956 $section->name = $data->name;
958 if (empty($secrec->summary)) {
959 $section->summary = $data->summary;
960 $section->summaryformat = $data->summaryformat;
961 $restorefiles = true;
963 $DB->update_record('course_sections', $section);
964 $newitemid = $secrec->id;
967 // Annotate the section mapping, with restorefiles option if needed
968 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
970 // set the new course_section id in the task
971 $this->task->set_sectionid($newitemid);
974 // Commented out. We never modify course->numsections as far as that is used
975 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
976 // Note: We keep the code here, to know about and because of the possibility of making this
977 // optional based on some setting/attribute in the future
978 // If needed, adjust course->numsections
979 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
980 // if ($numsections < $section->section) {
981 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
982 // }
986 protected function after_execute() {
987 // Add section related files, with 'course_section' itemid to match
988 $this->add_related_files('course', 'section', 'course_section');
994 * Structure step that will read the course.xml file, loading it and performing
995 * various actions depending of the site/restore settings. Note that target
996 * course always exist before arriving here so this step will be updating
997 * the course record (never inserting)
999 class restore_course_structure_step extends restore_structure_step {
1001 protected function define_structure() {
1003 $course = new restore_path_element('course', '/course');
1004 $category = new restore_path_element('category', '/course/category');
1005 $tag = new restore_path_element('tag', '/course/tags/tag');
1006 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1008 // Apply for 'format' plugins optional paths at course level
1009 $this->add_plugin_structure('format', $course);
1011 // Apply for 'theme' plugins optional paths at course level
1012 $this->add_plugin_structure('theme', $course);
1014 // Apply for 'course report' plugins optional paths at course level
1015 $this->add_plugin_structure('coursereport', $course);
1017 // Apply for plagiarism plugins optional paths at course level
1018 $this->add_plugin_structure('plagiarism', $course);
1020 return array($course, $category, $tag, $allowed_module);
1024 * Processing functions go here
1026 * @global moodledatabase $DB
1027 * @param stdClass $data
1029 public function process_course($data) {
1030 global $CFG, $DB;
1032 $data = (object)$data;
1033 $oldid = $data->id; // We'll need this later
1035 $fullname = $this->get_setting_value('course_fullname');
1036 $shortname = $this->get_setting_value('course_shortname');
1037 $startdate = $this->get_setting_value('course_startdate');
1039 // Calculate final course names, to avoid dupes
1040 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1042 // Need to change some fields before updating the course record
1043 $data->id = $this->get_courseid();
1044 $data->fullname = $fullname;
1045 $data->shortname= $shortname;
1046 $data->idnumber = '';
1048 // Only restrict modules if original course was and target site too for new courses
1049 $data->restrictmodules = $data->restrictmodules && !empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all';
1051 $data->startdate= $this->apply_date_offset($data->startdate);
1052 if ($data->defaultgroupingid) {
1053 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1055 if (empty($CFG->enablecompletion)) {
1056 $data->enablecompletion = 0;
1057 $data->completionstartonenrol = 0;
1058 $data->completionnotify = 0;
1060 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1061 if (!array_key_exists($data->lang, $languages)) {
1062 $data->lang = '';
1065 $themes = get_list_of_themes(); // Get themes for quick search later
1066 if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1067 $data->theme = '';
1070 // Course record ready, update it
1071 $DB->update_record('course', $data);
1073 // Role name aliases
1074 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1077 public function process_category($data) {
1078 // Nothing to do with the category. UI sets it before restore starts
1081 public function process_tag($data) {
1082 global $CFG, $DB;
1084 $data = (object)$data;
1086 if (!empty($CFG->usetags)) { // if enabled in server
1087 // TODO: This is highly inneficient. Each time we add one tag
1088 // we fetch all the existing because tag_set() deletes them
1089 // so everything must be reinserted on each call
1090 $tags = array();
1091 $existingtags = tag_get_tags('course', $this->get_courseid());
1092 // Re-add all the existitng tags
1093 foreach ($existingtags as $existingtag) {
1094 $tags[] = $existingtag->rawname;
1096 // Add the one being restored
1097 $tags[] = $data->rawname;
1098 // Send all the tags back to the course
1099 tag_set('course', $this->get_courseid(), $tags);
1103 public function process_allowed_module($data) {
1104 global $CFG, $DB;
1106 $data = (object)$data;
1108 // only if enabled by admin setting
1109 if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all') {
1110 $available = get_plugin_list('mod');
1111 $mname = $data->modulename;
1112 if (array_key_exists($mname, $available)) {
1113 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
1114 $rec = new stdclass();
1115 $rec->course = $this->get_courseid();
1116 $rec->module = $module->id;
1117 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
1118 $DB->insert_record('course_allowed_modules', $rec);
1125 protected function after_execute() {
1126 // Add course related files, without itemid to match
1127 $this->add_related_files('course', 'summary', null);
1128 $this->add_related_files('course', 'legacy', null);
1134 * Structure step that will read the roles.xml file (at course/activity/block levels)
1135 * containig all the role_assignments and overrides for that context. If corresponding to
1136 * one mapped role, they will be applied to target context. Will observe the role_assignments
1137 * setting to decide if ras are restored.
1138 * Note: only ras with component == null are restored as far as the any ra with component
1139 * is handled by one enrolment plugin, hence it will createt the ras later
1141 class restore_ras_and_caps_structure_step extends restore_structure_step {
1143 protected function define_structure() {
1145 $paths = array();
1147 // Observe the role_assignments setting
1148 if ($this->get_setting_value('role_assignments')) {
1149 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1151 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1153 return $paths;
1157 * Assign roles
1159 * This has to be called after enrolments processing.
1161 * @param mixed $data
1162 * @return void
1164 public function process_assignment($data) {
1165 global $DB;
1167 $data = (object)$data;
1169 // Check roleid, userid are one of the mapped ones
1170 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1171 return;
1173 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1174 return;
1176 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1177 // Only assign roles to not deleted users
1178 return;
1180 if (!$contextid = $this->task->get_contextid()) {
1181 return;
1184 if (empty($data->component)) {
1185 // assign standard manual roles
1186 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1187 role_assign($newroleid, $newuserid, $contextid);
1189 } else if ((strpos($data->component, 'enrol_') === 0)) {
1190 // Deal with enrolment roles
1191 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1192 if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
1193 //note: we have to verify component because it might have changed
1194 if ($component === 'enrol_manual') {
1195 // manual is a special case, we do not use components - this owudl happen when converting from other plugin
1196 role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
1197 } else {
1198 role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
1205 public function process_override($data) {
1206 $data = (object)$data;
1208 // Check roleid is one of the mapped ones
1209 $newroleid = $this->get_mappingid('role', $data->roleid);
1210 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1211 if ($newroleid && $this->task->get_contextid()) {
1212 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1213 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1214 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1220 * This structure steps restores the enrol plugins and their underlying
1221 * enrolments, performing all the mappings and/or movements required
1223 class restore_enrolments_structure_step extends restore_structure_step {
1225 protected function define_structure() {
1227 $paths = array();
1229 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1230 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1232 return $paths;
1236 * Create enrolment instances.
1238 * This has to be called after creation of roles
1239 * and before adding of role assignments.
1241 * @param mixed $data
1242 * @return void
1244 public function process_enrol($data) {
1245 global $DB;
1247 $data = (object)$data;
1248 $oldid = $data->id; // We'll need this later
1250 $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);
1252 if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
1253 // TODO: add complex restore support via custom class
1254 debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
1255 $this->set_mapping('enrol', $oldid, 0);
1256 return;
1259 // Perform various checks to decide what to do with the enrol plugin
1260 if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
1261 // TODO: decide if we want to switch to manual enrol - we need UI for this
1262 debugging("Enrol plugin data can not be restored because it is not installed");
1263 $this->set_mapping('enrol', $oldid, 0);
1264 return;
1267 if (!enrol_is_enabled($data->enrol)) {
1268 // TODO: decide if we want to switch to manual enrol - we need UI for this
1269 debugging("Enrol plugin data can not be restored because it is not enabled");
1270 $this->set_mapping('enrol', $oldid, 0);
1271 return;
1274 // map standard fields - plugin has to process custom fields from own restore class
1275 $data->roleid = $this->get_mappingid('role', $data->roleid);
1276 //TODO: should we move the enrol start and end date here?
1278 // always add instance, if the course does not support multiple instances it just returns NULL
1279 $enrol = enrol_get_plugin($data->enrol);
1280 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1281 if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
1282 // ok
1283 } else {
1284 if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
1285 // most probably plugin that supports only one instance
1286 $newitemid = key($instances);
1287 } else {
1288 debugging('Can not create new enrol instance or reuse existing');
1289 $newitemid = 0;
1293 if ($restoretype === ENROL_RESTORE_NOUSERS) {
1294 // plugin requests to prevent restore of any users
1295 $newitemid = 0;
1298 $this->set_mapping('enrol', $oldid, $newitemid);
1302 * Create user enrolments
1304 * This has to be called after creation of enrolment instances
1305 * and before adding of role assignments.
1307 * @param mixed $data
1308 * @return void
1310 public function process_enrolment($data) {
1311 global $DB;
1313 $data = (object)$data;
1315 // Process only if parent instance have been mapped
1316 if ($enrolid = $this->get_new_parentid('enrol')) {
1317 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1318 // And only if user is a mapped one
1319 if ($userid = $this->get_mappingid('user', $data->userid)) {
1320 $enrol = enrol_get_plugin($instance->enrol);
1321 //TODO: do we need specify modifierid?
1322 $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
1323 //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
1332 * This structure steps restores the filters and their configs
1334 class restore_filters_structure_step extends restore_structure_step {
1336 protected function define_structure() {
1338 $paths = array();
1340 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1341 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1343 return $paths;
1346 public function process_active($data) {
1348 $data = (object)$data;
1350 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1351 return;
1353 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1356 public function process_config($data) {
1358 $data = (object)$data;
1360 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1361 return;
1363 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1369 * This structure steps restores the comments
1370 * Note: Cannot use the comments API because defaults to USER->id.
1371 * That should change allowing to pass $userid
1373 class restore_comments_structure_step extends restore_structure_step {
1375 protected function define_structure() {
1377 $paths = array();
1379 $paths[] = new restore_path_element('comment', '/comments/comment');
1381 return $paths;
1384 public function process_comment($data) {
1385 global $DB;
1387 $data = (object)$data;
1389 // First of all, if the comment has some itemid, ask to the task what to map
1390 $mapping = false;
1391 if ($data->itemid) {
1392 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1393 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
1395 // Only restore the comment if has no mapping OR we have found the matching mapping
1396 if (!$mapping || $data->itemid) {
1397 // Only if user mapping and context
1398 $data->userid = $this->get_mappingid('user', $data->userid);
1399 if ($data->userid && $this->task->get_contextid()) {
1400 $data->contextid = $this->task->get_contextid();
1401 // Only if there is another comment with same context/user/timecreated
1402 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1403 if (!$DB->record_exists('comments', $params)) {
1404 $DB->insert_record('comments', $data);
1411 class restore_course_completion_structure_step extends restore_structure_step {
1414 * Conditionally decide if this step should be executed.
1416 * This function checks parameters that are not immediate settings to ensure
1417 * that the enviroment is suitable for the restore of course completion info.
1419 * This function checks the following four parameters:
1421 * 1. Course completion is enabled on the site
1422 * 2. The backup includes course completion information
1423 * 3. All modules are restorable
1424 * 4. All modules are marked for restore.
1426 * @return bool True is safe to execute, false otherwise
1428 protected function execute_condition() {
1429 global $CFG;
1431 // First check course completion is enabled on this site
1432 if (empty($CFG->enablecompletion)) {
1433 // Disabled, don't restore course completion
1434 return false;
1437 // Check it is included in the backup
1438 $fullpath = $this->task->get_taskbasepath();
1439 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1440 if (!file_exists($fullpath)) {
1441 // Not found, can't restore course completion
1442 return false;
1445 // Check we are able to restore all backed up modules
1446 if ($this->task->is_missing_modules()) {
1447 return false;
1450 // Finally check all modules within the backup are being restored.
1451 if ($this->task->is_excluding_activities()) {
1452 return false;
1455 return true;
1459 * Define the course completion structure
1461 * @return array Array of restore_path_element
1463 protected function define_structure() {
1465 // To know if we are including user completion info
1466 $userinfo = $this->get_setting_value('userscompletion');
1468 $paths = array();
1469 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1470 $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1471 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1473 if ($userinfo) {
1474 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1475 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1478 return $paths;
1483 * Process course completion criteria
1485 * @global moodle_database $DB
1486 * @param stdClass $data
1488 public function process_course_completion_criteria($data) {
1489 global $DB;
1491 $data = (object)$data;
1492 $data->course = $this->get_courseid();
1494 // Apply the date offset to the time end field
1495 $data->timeend = $this->apply_date_offset($data->timeend);
1497 // Map the role from the criteria
1498 if (!empty($data->role)) {
1499 $data->role = $this->get_mappingid('role', $data->role);
1502 $skipcriteria = false;
1504 // If the completion criteria is for a module we need to map the module instance
1505 // to the new module id.
1506 if (!empty($data->moduleinstance) && !empty($data->module)) {
1507 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
1508 if (empty($data->moduleinstance)) {
1509 $skipcriteria = true;
1511 } else {
1512 $data->module = null;
1513 $data->moduleinstance = null;
1516 // We backup the course shortname rather than the ID so that we can match back to the course
1517 if (!empty($data->courseinstanceshortname)) {
1518 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1519 if (!$courseinstanceid) {
1520 $skipcriteria = true;
1522 } else {
1523 $courseinstanceid = null;
1525 $data->courseinstance = $courseinstanceid;
1527 if (!$skipcriteria) {
1528 $params = array(
1529 'course' => $data->course,
1530 'criteriatype' => $data->criteriatype,
1531 'enrolperiod' => $data->enrolperiod,
1532 'courseinstance' => $data->courseinstance,
1533 'module' => $data->module,
1534 'moduleinstance' => $data->moduleinstance,
1535 'timeend' => $data->timeend,
1536 'gradepass' => $data->gradepass,
1537 'role' => $data->role
1539 $newid = $DB->insert_record('course_completion_criteria', $params);
1540 $this->set_mapping('course_completion_criteria', $data->id, $newid);
1545 * Processes course compltion criteria complete records
1547 * @global moodle_database $DB
1548 * @param stdClass $data
1550 public function process_course_completion_crit_compl($data) {
1551 global $DB;
1553 $data = (object)$data;
1555 // This may be empty if criteria could not be restored
1556 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
1558 $data->course = $this->get_courseid();
1559 $data->userid = $this->get_mappingid('user', $data->userid);
1561 if (!empty($data->criteriaid) && !empty($data->userid)) {
1562 $params = array(
1563 'userid' => $data->userid,
1564 'course' => $data->course,
1565 'criteriaid' => $data->criteriaid,
1566 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1568 if (isset($data->gradefinal)) {
1569 $params['gradefinal'] = $data->gradefinal;
1571 if (isset($data->unenroled)) {
1572 $params['unenroled'] = $data->unenroled;
1574 if (isset($data->deleted)) {
1575 $params['deleted'] = $data->deleted;
1577 $DB->insert_record('course_completion_crit_compl', $params);
1582 * Process course completions
1584 * @global moodle_database $DB
1585 * @param stdClass $data
1587 public function process_course_completions($data) {
1588 global $DB;
1590 $data = (object)$data;
1592 $data->course = $this->get_courseid();
1593 $data->userid = $this->get_mappingid('user', $data->userid);
1595 if (!empty($data->userid)) {
1596 $params = array(
1597 'userid' => $data->userid,
1598 'course' => $data->course,
1599 'deleted' => $data->deleted,
1600 'timenotified' => $this->apply_date_offset($data->timenotified),
1601 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1602 'timestarted' => $this->apply_date_offset($data->timestarted),
1603 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1604 'reaggregate' => $data->reaggregate
1606 $DB->insert_record('course_completions', $params);
1611 * Process course completion notification records.
1613 * Note: As of Moodle 2.0 this table is not being used however it has been
1614 * left in in the hopes that one day the functionality there will be completed
1616 * @global moodle_database $DB
1617 * @param stdClass $data
1619 public function process_course_completion_notify($data) {
1620 global $DB;
1622 $data = (object)$data;
1624 $data->course = $this->get_courseid();
1625 if (!empty($data->role)) {
1626 $data->role = $this->get_mappingid('role', $data->role);
1629 $params = array(
1630 'course' => $data->course,
1631 'role' => $data->role,
1632 'message' => $data->message,
1633 'timesent' => $this->apply_date_offset($data->timesent),
1635 $DB->insert_record('course_completion_notify', $params);
1639 * Process course completion aggregate methods
1641 * @global moodle_database $DB
1642 * @param stdClass $data
1644 public function process_course_completion_aggr_methd($data) {
1645 global $DB;
1647 $data = (object)$data;
1649 $data->course = $this->get_courseid();
1651 $params = array(
1652 'course' => $data->course,
1653 'criteriatype' => $data->criteriatype,
1654 'method' => $data->method,
1655 'value' => $data->value,
1657 $DB->insert_record('course_completion_aggr_methd', $params);
1664 * This structure step restores course logs (cmid = 0), delegating
1665 * the hard work to the corresponding {@link restore_logs_processor} passing the
1666 * collection of {@link restore_log_rule} rules to be observed as they are defined
1667 * by the task. Note this is only executed based in the 'logs' setting.
1669 * NOTE: This is executed by final task, to have all the activities already restored
1671 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
1672 * records are. There are others like 'calendar' and 'upload' that will be handled
1673 * later.
1675 * NOTE: All the missing actions (not able to be restored) are sent to logs for
1676 * debugging purposes
1678 class restore_course_logs_structure_step extends restore_structure_step {
1681 * Conditionally decide if this step should be executed.
1683 * This function checks the following four parameters:
1685 * 1. the course/logs.xml file exists
1687 * @return bool true is safe to execute, false otherwise
1689 protected function execute_condition() {
1691 // Check it is included in the backup
1692 $fullpath = $this->task->get_taskbasepath();
1693 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1694 if (!file_exists($fullpath)) {
1695 // Not found, can't restore course logs
1696 return false;
1699 return true;
1702 protected function define_structure() {
1704 $paths = array();
1706 // Simple, one plain level of information contains them
1707 $paths[] = new restore_path_element('log', '/logs/log');
1709 return $paths;
1712 protected function process_log($data) {
1713 global $DB;
1715 $data = (object)($data);
1717 $data->time = $this->apply_date_offset($data->time);
1718 $data->userid = $this->get_mappingid('user', $data->userid);
1719 $data->course = $this->get_courseid();
1720 $data->cmid = 0;
1722 // For any reason user wasn't remapped ok, stop processing this
1723 if (empty($data->userid)) {
1724 return;
1727 // Everything ready, let's delegate to the restore_logs_processor
1729 // Set some fixed values that will save tons of DB requests
1730 $values = array(
1731 'course' => $this->get_courseid());
1732 // Get instance and process log record
1733 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
1735 // If we have data, insert it, else something went wrong in the restore_logs_processor
1736 if ($data) {
1737 $DB->insert_record('log', $data);
1743 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
1744 * sharing its same structure but modifying the way records are handled
1746 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
1748 protected function process_log($data) {
1749 global $DB;
1751 $data = (object)($data);
1753 $data->time = $this->apply_date_offset($data->time);
1754 $data->userid = $this->get_mappingid('user', $data->userid);
1755 $data->course = $this->get_courseid();
1756 $data->cmid = $this->task->get_moduleid();
1758 // For any reason user wasn't remapped ok, stop processing this
1759 if (empty($data->userid)) {
1760 return;
1763 // Everything ready, let's delegate to the restore_logs_processor
1765 // Set some fixed values that will save tons of DB requests
1766 $values = array(
1767 'course' => $this->get_courseid(),
1768 'course_module' => $this->task->get_moduleid(),
1769 $this->task->get_modulename() => $this->task->get_activityid());
1770 // Get instance and process log record
1771 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
1773 // If we have data, insert it, else something went wrong in the restore_logs_processor
1774 if ($data) {
1775 $DB->insert_record('log', $data);
1781 * This structure step restores the grade items associated with one activity
1782 * All the grade items are made child of the "course" grade item but the original
1783 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
1784 * the complete gradebook (categories and calculations), that information is
1785 * available there
1787 class restore_activity_grades_structure_step extends restore_structure_step {
1789 protected function define_structure() {
1791 $paths = array();
1792 $userinfo = $this->get_setting_value('userinfo');
1794 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
1795 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
1796 if ($userinfo) {
1797 $paths[] = new restore_path_element('grade_grade',
1798 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
1800 return $paths;
1803 protected function process_grade_item($data) {
1805 $data = (object)($data);
1806 $oldid = $data->id; // We'll need these later
1807 $oldparentid = $data->categoryid;
1809 // make sure top course category exists, all grade items will be associated
1810 // to it. Later, if restoring the whole gradebook, categories will be introduced
1811 $coursecat = grade_category::fetch_course_category($this->get_courseid());
1812 $coursecatid = $coursecat->id; // Get the categoryid to be used
1814 unset($data->id);
1815 $data->categoryid = $coursecatid;
1816 $data->courseid = $this->get_courseid();
1817 $data->iteminstance = $this->task->get_activityid();
1818 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
1819 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
1820 // so the best is to keep the ones already in the gradebook
1821 // Potential problem: duplicates if same items are restored more than once. :-(
1822 // This needs to be fixed in some way (outcomes & activities with multiple items)
1823 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
1824 // In any case, verify always for uniqueness
1825 $data->idnumber = grade_verify_idnumber($data->idnumber, $this->get_courseid()) ? $data->idnumber : null;
1826 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1827 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
1828 $data->timecreated = $this->apply_date_offset($data->timecreated);
1829 $data->timemodified = $this->apply_date_offset($data->timemodified);
1831 $gradeitem = new grade_item($data, false);
1832 $gradeitem->insert('restore');
1834 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
1835 $gradeitem->sortorder = $data->sortorder;
1836 $gradeitem->update('restore');
1838 // Set mapping, saving the original category id into parentitemid
1839 // gradebook restore (final task) will need it to reorganise items
1840 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
1843 protected function process_grade_grade($data) {
1844 $data = (object)($data);
1846 unset($data->id);
1847 $data->itemid = $this->get_new_parentid('grade_item');
1848 $data->userid = $this->get_mappingid('user', $data->userid);
1849 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
1850 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
1851 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
1852 $data->overridden = $this->apply_date_offset($data->overridden);
1854 $grade = new grade_grade($data, false);
1855 $grade->insert('restore');
1856 // no need to save any grade_grade mapping
1860 * process activity grade_letters. Note that, while these are possible,
1861 * because grade_letters are contextid based, in proctice, only course
1862 * context letters can be defined. So we keep here this method knowing
1863 * it won't be executed ever. gradebook restore will restore course letters.
1865 protected function process_grade_letter($data) {
1866 global $DB;
1868 $data = (object)$data;
1870 $data->contextid = $this->task->get_contextid();
1871 $newitemid = $DB->insert_record('grade_letters', $data);
1872 // no need to save any grade_letter mapping
1878 * This structure steps restores one instance + positions of one block
1879 * Note: Positions corresponding to one existing context are restored
1880 * here, but all the ones having unknown contexts are sent to backup_ids
1881 * for a later chance to be restored at the end (final task)
1883 class restore_block_instance_structure_step extends restore_structure_step {
1885 protected function define_structure() {
1887 $paths = array();
1889 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
1890 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
1892 return $paths;
1895 public function process_block($data) {
1896 global $DB, $CFG;
1898 $data = (object)$data; // Handy
1899 $oldcontextid = $data->contextid;
1900 $oldid = $data->id;
1901 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1903 // Look for the parent contextid
1904 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1905 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1908 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
1909 // If there is already one block of that type in the parent context
1910 // and the block is not multiple, stop processing
1911 // Use blockslib loader / method executor
1912 if (!block_method_result($data->blockname, 'instance_allow_multiple')) {
1913 if ($DB->record_exists_sql("SELECT bi.id
1914 FROM {block_instances} bi
1915 JOIN {block} b ON b.name = bi.blockname
1916 WHERE bi.parentcontextid = ?
1917 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
1918 return false;
1922 // If there is already one block of that type in the parent context
1923 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
1924 // stop processing
1925 $params = array(
1926 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
1927 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
1928 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
1929 if ($birecs = $DB->get_records('block_instances', $params)) {
1930 foreach($birecs as $birec) {
1931 if ($birec->configdata == $data->configdata) {
1932 return false;
1937 // Set task old contextid, blockid and blockname once we know them
1938 $this->task->set_old_contextid($oldcontextid);
1939 $this->task->set_old_blockid($oldid);
1940 $this->task->set_blockname($data->blockname);
1942 // Let's look for anything within configdata neededing processing
1943 // (nulls and uses of legacy file.php)
1944 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1945 $configdata = (array)unserialize(base64_decode($data->configdata));
1946 foreach ($configdata as $attribute => $value) {
1947 if (in_array($attribute, $attrstotransform)) {
1948 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
1951 $data->configdata = base64_encode(serialize((object)$configdata));
1954 // Create the block instance
1955 $newitemid = $DB->insert_record('block_instances', $data);
1956 // Save the mapping (with restorefiles support)
1957 $this->set_mapping('block_instance', $oldid, $newitemid, true);
1958 // Create the block context
1959 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
1960 // Save the block contexts mapping and sent it to task
1961 $this->set_mapping('context', $oldcontextid, $newcontextid);
1962 $this->task->set_contextid($newcontextid);
1963 $this->task->set_blockid($newitemid);
1965 // Restore block fileareas if declared
1966 $component = 'block_' . $this->task->get_blockname();
1967 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
1968 $this->add_related_files($component, $filearea, null);
1971 // Process block positions, creating them or accumulating for final step
1972 foreach($positions as $position) {
1973 $position = (object)$position;
1974 $position->blockinstanceid = $newitemid; // The instance is always the restored one
1975 // If position is for one already mapped (known) contextid
1976 // process it now, creating the position
1977 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
1978 $position->contextid = $newpositionctxid;
1979 // Create the block position
1980 $DB->insert_record('block_positions', $position);
1982 // The position belongs to an unknown context, send it to backup_ids
1983 // to process them as part of the final steps of restore. We send the
1984 // whole $position object there, hence use the low level method.
1985 } else {
1986 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
1993 * Structure step to restore common course_module information
1995 * This step will process the module.xml file for one activity, in order to restore
1996 * the corresponding information to the course_modules table, skipping various bits
1997 * of information based on CFG settings (groupings, completion...) in order to fullfill
1998 * all the reqs to be able to create the context to be used by all the rest of steps
1999 * in the activity restore task
2001 class restore_module_structure_step extends restore_structure_step {
2003 protected function define_structure() {
2004 global $CFG;
2006 $paths = array();
2008 $module = new restore_path_element('module', '/module');
2009 $paths[] = $module;
2010 if ($CFG->enableavailability) {
2011 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
2014 // Apply for 'format' plugins optional paths at module level
2015 $this->add_plugin_structure('format', $module);
2017 // Apply for 'plagiarism' plugins optional paths at module level
2018 $this->add_plugin_structure('plagiarism', $module);
2020 return $paths;
2023 protected function process_module($data) {
2024 global $CFG, $DB;
2026 $data = (object)$data;
2027 $oldid = $data->id;
2029 $this->task->set_old_moduleversion($data->version);
2031 $data->course = $this->task->get_courseid();
2032 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
2033 // Map section (first try by course_section mapping match. Useful in course and section restores)
2034 $data->section = $this->get_mappingid('course_section', $data->sectionid);
2035 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
2036 $params = array(
2037 'course' => $this->get_courseid(),
2038 'section' => $data->sectionnumber);
2039 $data->section = $DB->get_field('course_sections', 'id', $params);
2041 if (!$data->section) { // sectionnumber failed, try to get first section in course
2042 $params = array(
2043 'course' => $this->get_courseid());
2044 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
2046 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
2047 $sectionrec = array(
2048 'course' => $this->get_courseid(),
2049 'section' => 0);
2050 $DB->insert_record('course_sections', $sectionrec); // section 0
2051 $sectionrec = array(
2052 'course' => $this->get_courseid(),
2053 'section' => 1);
2054 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
2056 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
2057 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
2058 $data->groupmembersonly = 0;
2060 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
2061 $data->idnumber = '';
2063 if (empty($CFG->enablecompletion)) { // completion
2064 $data->completion = 0;
2065 $data->completiongradeitemnumber = null;
2066 $data->completionview = 0;
2067 $data->completionexpected = 0;
2068 } else {
2069 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
2071 if (empty($CFG->enableavailability)) {
2072 $data->availablefrom = 0;
2073 $data->availableuntil = 0;
2074 $data->showavailability = 0;
2075 } else {
2076 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
2077 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
2079 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
2081 // course_module record ready, insert it
2082 $newitemid = $DB->insert_record('course_modules', $data);
2083 // save mapping
2084 $this->set_mapping('course_module', $oldid, $newitemid);
2085 // set the new course_module id in the task
2086 $this->task->set_moduleid($newitemid);
2087 // we can now create the context safely
2088 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
2089 // set the new context id in the task
2090 $this->task->set_contextid($ctxid);
2091 // update sequence field in course_section
2092 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
2093 $sequence .= ',' . $newitemid;
2094 } else {
2095 $sequence = $newitemid;
2097 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
2101 protected function process_availability($data) {
2102 $data = (object)$data;
2103 // Simply going to store the whole availability record now, we'll process
2104 // all them later in the final task (once all actvivities have been restored)
2105 // Let's call the low level one to be able to store the whole object
2106 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
2107 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
2112 * Structure step that will process the user activity completion
2113 * information if all these conditions are met:
2114 * - Target site has completion enabled ($CFG->enablecompletion)
2115 * - Activity includes completion info (file_exists)
2117 class restore_userscompletion_structure_step extends restore_structure_step {
2120 * To conditionally decide if this step must be executed
2121 * Note the "settings" conditions are evaluated in the
2122 * corresponding task. Here we check for other conditions
2123 * not being restore settings (files, site settings...)
2125 protected function execute_condition() {
2126 global $CFG;
2128 // Completion disabled in this site, don't execute
2129 if (empty($CFG->enablecompletion)) {
2130 return false;
2133 // No user completion info found, don't execute
2134 $fullpath = $this->task->get_taskbasepath();
2135 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2136 if (!file_exists($fullpath)) {
2137 return false;
2140 // Arrived here, execute the step
2141 return true;
2144 protected function define_structure() {
2146 $paths = array();
2148 $paths[] = new restore_path_element('completion', '/completions/completion');
2150 return $paths;
2153 protected function process_completion($data) {
2154 global $DB;
2156 $data = (object)$data;
2158 $data->coursemoduleid = $this->task->get_moduleid();
2159 $data->userid = $this->get_mappingid('user', $data->userid);
2160 $data->timemodified = $this->apply_date_offset($data->timemodified);
2162 $DB->insert_record('course_modules_completion', $data);
2167 * Abstract structure step, parent of all the activity structure steps. Used to suuport
2168 * the main <activity ...> tag and process it. Also provides subplugin support for
2169 * activities.
2171 abstract class restore_activity_structure_step extends restore_structure_step {
2173 protected function add_subplugin_structure($subplugintype, $element) {
2175 global $CFG;
2177 // Check the requested subplugintype is a valid one
2178 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
2179 if (!file_exists($subpluginsfile)) {
2180 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
2182 include($subpluginsfile);
2183 if (!array_key_exists($subplugintype, $subplugins)) {
2184 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
2186 // Get all the restore path elements, looking across all the subplugin dirs
2187 $subpluginsdirs = get_plugin_list($subplugintype);
2188 foreach ($subpluginsdirs as $name => $subpluginsdir) {
2189 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
2190 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
2191 if (file_exists($restorefile)) {
2192 require_once($restorefile);
2193 $restoresubplugin = new $classname($subplugintype, $name, $this);
2194 // Add subplugin paths to the step
2195 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
2201 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
2202 * have the parent task available for wrapping purposes (get course/context....)
2203 * @return restore_task
2205 public function get_task() {
2206 return $this->task;
2210 * Adds support for the 'activity' path that is common to all the activities
2211 * and will be processed globally here
2213 protected function prepare_activity_structure($paths) {
2215 $paths[] = new restore_path_element('activity', '/activity');
2217 return $paths;
2221 * Process the activity path, informing the task about various ids, needed later
2223 protected function process_activity($data) {
2224 $data = (object)$data;
2225 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
2226 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
2227 $this->task->set_old_activityid($data->id); // Save old activityid in task
2231 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
2232 * and will adjust the new activity id (the instance) in various places
2234 protected function apply_activity_instance($newitemid) {
2235 global $DB;
2237 $this->task->set_activityid($newitemid); // Save activity id in task
2238 // Apply the id to course_sections->instanceid
2239 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
2240 // Do the mapping for modulename, preparing it for files by oldcontext
2241 $modulename = $this->task->get_modulename();
2242 $oldid = $this->task->get_old_activityid();
2243 $this->set_mapping($modulename, $oldid, $newitemid, true);
2248 * Structure step in charge of creating/mapping all the qcats and qs
2249 * by parsing the questions.xml file and checking it against the
2250 * results calculated by {@link restore_process_categories_and_questions}
2251 * and stored in backup_ids_temp
2253 class restore_create_categories_and_questions extends restore_structure_step {
2255 protected function define_structure() {
2257 $category = new restore_path_element('question_category', '/question_categories/question_category');
2258 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
2260 // Apply for 'qtype' plugins optional paths at question level
2261 $this->add_plugin_structure('qtype', $question);
2263 return array($category, $question);
2266 protected function process_question_category($data) {
2267 global $DB;
2269 $data = (object)$data;
2270 $oldid = $data->id;
2272 // Check we have one mapping for this category
2273 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
2274 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
2277 // Check we have to create the category (newitemid = 0)
2278 if ($mapping->newitemid) {
2279 return; // newitemid != 0, this category is going to be mapped. Nothing to do
2282 // Arrived here, newitemid = 0, we need to create the category
2283 // we'll do it at parentitemid context, but for CONTEXT_MODULE
2284 // categories, that will be created at CONTEXT_COURSE and moved
2285 // to module context later when the activity is created
2286 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
2287 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
2289 $data->contextid = $mapping->parentitemid;
2291 // Let's create the question_category and save mapping
2292 $newitemid = $DB->insert_record('question_categories', $data);
2293 $this->set_mapping('question_category', $oldid, $newitemid);
2294 // Also annotate them as question_category_created, we need
2295 // that later when remapping parents
2296 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
2299 protected function process_question($data) {
2300 global $DB;
2302 $data = (object)$data;
2303 $oldid = $data->id;
2305 // Check we have one mapping for this question
2306 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
2307 return; // No mapping = this question doesn't need to be created/mapped
2310 // Get the mapped category (cannot use get_new_parentid() because not
2311 // all the categories have been created, so it is not always available
2312 // Instead we get the mapping for the question->parentitemid because
2313 // we have loaded qcatids there for all parsed questions
2314 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
2316 // In the past, there were some very sloppy values of penalty. Fix them.
2317 if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
2318 $data->penalty = 0.3333333;
2320 if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
2321 $data->penalty = 0.6666667;
2323 if ($data->penalty >= 1) {
2324 $data->penalty = 1;
2327 $data->timecreated = $this->apply_date_offset($data->timecreated);
2328 $data->timemodified = $this->apply_date_offset($data->timemodified);
2330 $userid = $this->get_mappingid('user', $data->createdby);
2331 $data->createdby = $userid ? $userid : $this->task->get_userid();
2333 $userid = $this->get_mappingid('user', $data->modifiedby);
2334 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
2336 // With newitemid = 0, let's create the question
2337 if (!$questionmapping->newitemid) {
2338 $newitemid = $DB->insert_record('question', $data);
2339 $this->set_mapping('question', $oldid, $newitemid);
2340 // Also annotate them as question_created, we need
2341 // that later when remapping parents (keeping the old categoryid as parentid)
2342 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
2343 } else {
2344 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
2345 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
2346 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
2349 // Note, we don't restore any question files yet
2350 // as far as the CONTEXT_MODULE categories still
2351 // haven't their contexts to be restored to
2352 // The {@link restore_create_question_files}, executed in the final step
2353 // step will be in charge of restoring all the question files
2356 protected function process_question_hint($data) {
2357 global $DB;
2359 $data = (object)$data;
2360 $oldid = $data->id;
2362 // Detect if the question is created or mapped
2363 $oldquestionid = $this->get_old_parentid('question');
2364 $newquestionid = $this->get_new_parentid('question');
2365 $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
2367 // If the question has been created by restore, we need to create its question_answers too
2368 if ($questioncreated) {
2369 // Adjust some columns
2370 $data->questionid = $newquestionid;
2371 // Insert record
2372 $newitemid = $DB->insert_record('question_answers', $data);
2374 // The question existed, we need to map the existing question_answers
2375 } else {
2376 // Look in question_answers by answertext matching
2377 $sql = 'SELECT id
2378 FROM {question_hints}
2379 WHERE questionid = ?
2380 AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
2381 $params = array($newquestionid, $data->hint);
2382 $newitemid = $DB->get_field_sql($sql, $params);
2383 // If we haven't found the newitemid, something has gone really wrong, question in DB
2384 // is missing answers, exception
2385 if (!$newitemid) {
2386 $info = new stdClass();
2387 $info->filequestionid = $oldquestionid;
2388 $info->dbquestionid = $newquestionid;
2389 $info->hint = $data->hint;
2390 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
2393 // Create mapping (we'll use this intensively when restoring question_states. And also answerfeedback files)
2394 $this->set_mapping('question_hint', $oldid, $newitemid);
2397 protected function after_execute() {
2398 global $DB;
2400 // First of all, recode all the created question_categories->parent fields
2401 $qcats = $DB->get_records('backup_ids_temp', array(
2402 'backupid' => $this->get_restoreid(),
2403 'itemname' => 'question_category_created'));
2404 foreach ($qcats as $qcat) {
2405 $newparent = 0;
2406 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
2407 // Get new parent (mapped or created, so we look in quesiton_category mappings)
2408 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2409 'backupid' => $this->get_restoreid(),
2410 'itemname' => 'question_category',
2411 'itemid' => $dbcat->parent))) {
2412 // contextids must match always, as far as we always include complete qbanks, just check it
2413 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
2414 if ($dbcat->contextid == $newparentctxid) {
2415 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
2416 } else {
2417 $newparent = 0; // No ctx match for both cats, no parent relationship
2420 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
2421 if (!$newparent) {
2422 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
2426 // Now, recode all the created question->parent fields
2427 $qs = $DB->get_records('backup_ids_temp', array(
2428 'backupid' => $this->get_restoreid(),
2429 'itemname' => 'question_created'));
2430 foreach ($qs as $q) {
2431 $newparent = 0;
2432 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
2433 // Get new parent (mapped or created, so we look in question mappings)
2434 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2435 'backupid' => $this->get_restoreid(),
2436 'itemname' => 'question',
2437 'itemid' => $dbq->parent))) {
2438 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
2442 // Note, we don't restore any question files yet
2443 // as far as the CONTEXT_MODULE categories still
2444 // haven't their contexts to be restored to
2445 // The {@link restore_create_question_files}, executed in the final step
2446 // step will be in charge of restoring all the question files
2451 * Execution step that will move all the CONTEXT_MODULE question categories
2452 * created at early stages of restore in course context (because modules weren't
2453 * created yet) to their target module (matching by old-new-contextid mapping)
2455 class restore_move_module_questions_categories extends restore_execution_step {
2457 protected function define_execution() {
2458 global $DB;
2460 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
2461 foreach ($contexts as $contextid => $contextlevel) {
2462 // Only if context mapping exists (i.e. the module has been restored)
2463 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
2464 // Update all the qcats having their parentitemid set to the original contextid
2465 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
2466 FROM {backup_ids_temp}
2467 WHERE backupid = ?
2468 AND itemname = 'question_category'
2469 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
2470 foreach ($modulecats as $modulecat) {
2471 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
2472 // And set new contextid also in question_category mapping (will be
2473 // used by {@link restore_create_question_files} later
2474 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
2482 * Execution step that will create all the question/answers/qtype-specific files for the restored
2483 * questions. It must be executed after {@link restore_move_module_questions_categories}
2484 * because only then each question is in its final category and only then the
2485 * context can be determined
2487 * TODO: Improve this. Instead of looping over each question, it can be reduced to
2488 * be done by contexts (this will save a huge ammount of queries)
2490 class restore_create_question_files extends restore_execution_step {
2492 protected function define_execution() {
2493 global $DB;
2495 // Let's process only created questions
2496 $questionsrs = $DB->get_recordset_sql("SELECT bi.itemid, bi.newitemid, bi.parentitemid, q.qtype
2497 FROM {backup_ids_temp} bi
2498 JOIN {question} q ON q.id = bi.newitemid
2499 WHERE bi.backupid = ?
2500 AND bi.itemname = 'question_created'", array($this->get_restoreid()));
2501 foreach ($questionsrs as $question) {
2502 // Get question_category mapping, it contains the target context for the question
2503 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $question->parentitemid)) {
2504 // Something went really wrong, cannot find the question_category for the question
2505 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
2506 continue;
2508 // Calculate source and target contexts
2509 $oldctxid = $qcatmapping->info->contextid;
2510 $newctxid = $qcatmapping->parentitemid;
2512 // Add common question files (question and question_answer ones)
2513 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
2514 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2515 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
2516 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2517 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
2518 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
2519 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
2520 $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true);
2521 // Add qtype dependent files
2522 $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
2523 foreach ($components as $component => $fileareas) {
2524 foreach ($fileareas as $filearea => $mapping) {
2525 // Use itemid only if mapping is question_created
2526 $itemid = ($mapping == 'question_created') ? $question->itemid : null;
2527 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
2528 $oldctxid, $this->task->get_userid(), $mapping, $itemid, $newctxid, true);
2532 $questionsrs->close();
2537 * Abstract structure step, to be used by all the activities using core questions stuff
2538 * (like the quiz module), to support qtype plugins, states and sessions
2540 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
2541 /** @var array question_attempt->id to qtype. */
2542 protected $qtypes = array();
2543 /** @var array question_attempt->id to questionid. */
2544 protected $newquestionids = array();
2547 * Attach below $element (usually attempts) the needed restore_path_elements
2548 * to restore question_usages and all they contain.
2550 protected function add_question_usages($element, &$paths) {
2551 // Check $element is restore_path_element
2552 if (! $element instanceof restore_path_element) {
2553 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2555 // Check $paths is one array
2556 if (!is_array($paths)) {
2557 throw new restore_step_exception('paths_must_be_array', $paths);
2559 $paths[] = new restore_path_element('question_usage',
2560 $element->get_path() . '/question_usage');
2561 $paths[] = new restore_path_element('question_attempt',
2562 $element->get_path() . '/question_usage/question_attempts/question_attempt');
2563 $paths[] = new restore_path_element('question_attempt_step',
2564 $element->get_path() . '/question_usage/question_attempts/question_attempt/steps/step',
2565 true);
2566 $paths[] = new restore_path_element('question_attempt_step_data',
2567 $element->get_path() . '/question_usage/question_attempts/question_attempt/steps/step/response/variable');
2571 * Process question_usages
2573 protected function process_question_usage($data) {
2574 global $DB;
2576 // Clear our caches.
2577 $this->qtypes = array();
2578 $this->newquestionids = array();
2580 $data = (object)$data;
2581 $oldid = $data->id;
2583 $oldcontextid = $this->get_task()->get_old_contextid();
2584 $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
2586 // Everything ready, insert (no mapping needed)
2587 $newitemid = $DB->insert_record('question_usages', $data);
2589 $this->inform_new_usage_id($newitemid);
2591 $this->set_mapping('question_usage', $oldid, $newitemid, false);
2595 * When process_question_usage creates the new usage, it calls this method
2596 * to let the activity link to the new usage. For example, the quiz uses
2597 * this method to set quiz_attempts.uniqueid to the new usage id.
2598 * @param integer $newusageid
2600 abstract protected function inform_new_usage_id($newusageid);
2603 * Process question_attempts
2605 protected function process_question_attempt($data) {
2606 global $DB;
2608 $data = (object)$data;
2609 $oldid = $data->id;
2610 $question = $this->get_mapping('question', $data->questionid);
2612 $data->questionusageid = $this->get_new_parentid('question_usage');
2613 $data->questionid = $question->newitemid;
2614 $data->timemodified = $this->apply_date_offset($data->timemodified);
2616 $newitemid = $DB->insert_record('question_attempts', $data);
2618 $this->set_mapping('question_attempt', $oldid, $newitemid);
2619 $this->qtypes[$newitemid] = $question->info->qtype;
2620 $this->newquestionids[$newitemid] = $data->questionid;
2624 * Process question_attempt_steps
2626 protected function process_question_attempt_step($data) {
2627 global $DB;
2629 $data = (object)$data;
2630 $oldid = $data->id;
2632 // Pull out the response data.
2633 $response = array();
2634 if (!empty($data->response['variable'])) {
2635 foreach ($data->response['variable'] as $variable) {
2636 $response[$variable['name']] = $variable['value'];
2639 unset($data->response);
2641 $data->questionattemptid = $this->get_new_parentid('question_attempt');
2642 $data->timecreated = $this->apply_date_offset($data->timecreated);
2643 $data->userid = $this->get_mappingid('user', $data->userid);
2645 // Everything ready, insert and create mapping (needed by question_sessions)
2646 $newitemid = $DB->insert_record('question_attempt_steps', $data);
2647 $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
2649 // Now process the response data.
2650 $qtyperestorer = $this->get_qtype_restorer($this->qtypes[$data->questionattemptid]);
2651 if ($qtyperestorer) {
2652 $response = $qtyperestorer->recode_response(
2653 $this->newquestionids[$data->questionattemptid],
2654 $data->sequencenumber, $response);
2656 foreach ($response as $name => $value) {
2657 $row = new stdClass();
2658 $row->attemptstepid = $newitemid;
2659 $row->name = $name;
2660 $row->value = $value;
2661 $DB->insert_record('question_attempt_step_data', $row, false);
2666 * Given a list of question->ids, separated by commas, returns the
2667 * recoded list, with all the restore question mappings applied.
2668 * Note: Used by quiz->questions and quiz_attempts->layout
2669 * Note: 0 = page break (unconverted)
2671 protected function questions_recode_layout($layout) {
2672 // Extracts question id from sequence
2673 if ($questionids = explode(',', $layout)) {
2674 foreach ($questionids as $id => $questionid) {
2675 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
2676 $newquestionid = $this->get_mappingid('question', $questionid);
2677 $questionids[$id] = $newquestionid;
2681 return implode(',', $questionids);
2685 * Get the restore_qtype_plugin subclass for a specific question type.
2686 * @param string $qtype e.g. multichoice.
2687 * @return restore_qtype_plugin instance.
2689 protected function get_qtype_restorer($qtype) {
2690 // Build one static cache to store {@link restore_qtype_plugin}
2691 // while we are needing them, just to save zillions of instantiations
2692 // or using static stuff that will break our nice API
2693 static $qtypeplugins = array();
2695 if (!isset($qtypeplugins[$qtype])) {
2696 $classname = 'restore_qtype_' . $qtype . '_plugin';
2697 if (class_exists($classname)) {
2698 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
2699 } else {
2700 $qtypeplugins[$qtype] = null;
2703 return $qtypeplugins[$qtype];
2706 protected function after_execute() {
2707 parent::after_execute();
2709 // Restore any files belonging to responses.
2710 foreach (question_engine::get_all_response_file_areas() as $filearea) {
2711 $this->add_related_files('question', $filearea, 'question_attempt_step');
2716 * Attach below $element (usually attempts) the needed restore_path_elements
2717 * to restore question attempt data from Moodle 2.0.
2719 * When using this method, the parent element ($element) must be defined with
2720 * $grouped = true. Then, in that elements process method, you must call
2721 * {@link process_legacy_attempt_data()} with the groupded data. See, for
2722 * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
2723 * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
2724 * @param array $paths the paths array that is being built to describe the
2725 * structure.
2727 protected function add_legacy_question_attempt_data($element, &$paths) {
2728 global $CFG;
2729 require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
2731 // Check $element is restore_path_element
2732 if (!($element instanceof restore_path_element)) {
2733 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2735 // Check $paths is one array
2736 if (!is_array($paths)) {
2737 throw new restore_step_exception('paths_must_be_array', $paths);
2740 $paths[] = new restore_path_element('question_state',
2741 $element->get_path() . '/states/state');
2742 $paths[] = new restore_path_element('question_session',
2743 $element->get_path() . '/sessions/session');
2746 protected function get_attempt_upgrader() {
2747 if (empty($this->attemptupgrader)) {
2748 $this->attemptupgrader = new question_engine_attempt_upgrader();
2749 $this->attemptupgrader->prepare_to_restore();
2751 return $this->attemptupgrader;
2755 * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
2756 * @param object $data contains all the grouped attempt data ot process.
2757 * @param pbject $quiz data about the activity the attempts belong to. Required
2758 * fields are (basically this only works for the quiz module):
2759 * oldquestions => list of question ids in this activity - using old ids.
2760 * preferredbehaviour => the behaviour to use for questionattempts.
2762 protected function process_legacy_quiz_attempt_data($data, $quiz) {
2763 global $DB;
2764 $upgrader = $this->get_attempt_upgrader();
2766 $data = (object)$data;
2768 $layout = explode(',', $data->layout);
2769 $newlayout = $layout;
2771 // Convert each old question_session into a question_attempt.
2772 $qas = array();
2773 foreach (explode(',', $quiz->oldquestions) as $questionid) {
2774 if ($questionid == 0) {
2775 continue;
2778 $newquestionid = $this->get_mappingid('question', $questionid);
2779 if (!$newquestionid) {
2780 throw new restore_step_exception('questionattemptreferstomissingquestion',
2781 $questionid, $questionid);
2784 $question = $upgrader->load_question($newquestionid, $quiz->id);
2786 foreach ($layout as $key => $qid) {
2787 if ($qid == $questionid) {
2788 $newlayout[$key] = $newquestionid;
2792 list($qsession, $qstates) = $this->find_question_session_and_states(
2793 $data, $questionid);
2795 if (empty($qsession) || empty($qstates)) {
2796 throw new restore_step_exception('questionattemptdatamissing',
2797 $questionid, $questionid);
2800 list($qsession, $qstates) = $this->recode_legacy_response_data(
2801 $question, $qsession, $qstates);
2803 $data->layout = implode(',', $newlayout);
2804 $qas[$newquestionid] = $upgrader->convert_question_attempt(
2805 $quiz, $data, $question, $qsession, $qstates);
2808 // Now create a new question_usage.
2809 $usage = new stdClass();
2810 $usage->component = 'mod_quiz';
2811 $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
2812 $usage->preferredbehaviour = $quiz->preferredbehaviour;
2813 $usage->id = $DB->insert_record('question_usages', $usage);
2815 $DB->set_field('quiz_attempts', 'uniqueid', $usage->id,
2816 array('id' => $this->get_mappingid('quiz_attempt', $data->id)));
2818 $data->uniqueid = $usage->id;
2819 $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas, $quiz->questions);
2822 protected function find_question_session_and_states($data, $questionid) {
2823 $qsession = null;
2824 foreach ($data->sessions['session'] as $session) {
2825 if ($session['questionid'] == $questionid) {
2826 $qsession = (object) $session;
2827 break;
2831 $qstates = array();
2832 foreach ($data->states['state'] as $state) {
2833 if ($state['question'] == $questionid) {
2834 $qstates[$state['seq_number']] = (object) $state;
2837 ksort($qstates);
2839 return array($qsession, $qstates);
2843 * Recode any ids in the response data
2844 * @param object $question the question data
2845 * @param object $qsession the question sessions.
2846 * @param array $qstates the question states.
2848 protected function recode_legacy_response_data($question, $qsession, $qstates) {
2849 $qsession->questionid = $question->id;
2851 foreach ($qstates as &$state) {
2852 $state->question = $question->id;
2853 $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
2856 return array($qsession, $qstates);
2860 * Recode the legacy answer field.
2861 * @param object $state the state to recode the answer of.
2862 * @param string $qtype the question type.
2864 public function restore_recode_legacy_answer($state, $qtype) {
2865 $restorer = $this->get_qtype_restorer($qtype);
2866 if ($restorer) {
2867 return $restorer->recode_legacy_state_answer($state);
2868 } else {
2869 return $state->answer;