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