9ee8f5ac171f6dd9780eb255197d484ca5bac1e2
[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  * Defines various restore steps that will be used by common tasks in restore
20  *
21  * @package     core_backup
22  * @subpackage  moodle2
23  * @category    backup
24  * @copyright   2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
25  * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 defined('MOODLE_INTERNAL') || die();
30 /**
31  * delete old directories and conditionally create backup_temp_ids table
32  */
33 class restore_create_and_clean_temp_stuff extends restore_execution_step {
35     protected function define_execution() {
36         $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
37         // If the table already exists, it's because restore_prechecks have been executed in the same
38         // request (without problems) and it already contains a bunch of preloaded information (users...)
39         // that we aren't going to execute again
40         if ($exists) { // Inform plan about preloaded information
41             $this->task->set_preloaded_information();
42         }
43         // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
44         $itemid = $this->task->get_old_contextid();
45         $newitemid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
46         restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
47         // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
48         $itemid = $this->task->get_old_system_contextid();
49         $newitemid = get_context_instance(CONTEXT_SYSTEM)->id;
50         restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
51         // Create the old-course-id to new-course-id mapping, we need that available since the beginning
52         $itemid = $this->task->get_old_courseid();
53         $newitemid = $this->get_courseid();
54         restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
56     }
57 }
59 /**
60  * delete the temp dir used by backup/restore (conditionally),
61  * delete old directories and drop temp ids table
62  */
63 class restore_drop_and_clean_temp_stuff extends restore_execution_step {
65     protected function define_execution() {
66         global $CFG;
67         restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
68         backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60));              // Delete > 4 hours temp dirs
69         if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
70             backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
71         }
72     }
73 }
75 /**
76  * Restore calculated grade items, grade categories etc
77  */
78 class restore_gradebook_structure_step extends restore_structure_step {
80     /**
81      * To conditionally decide if this step must be executed
82      * Note the "settings" conditions are evaluated in the
83      * corresponding task. Here we check for other conditions
84      * not being restore settings (files, site settings...)
85      */
86      protected function execute_condition() {
87         global $CFG, $DB;
89         // No gradebook info found, don't execute
90         $fullpath = $this->task->get_taskbasepath();
91         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
92         if (!file_exists($fullpath)) {
93             return false;
94         }
96         // Some module present in backup file isn't available to restore
97         // in this site, don't execute
98         if ($this->task->is_missing_modules()) {
99             return false;
100         }
102         // Some activity has been excluded to be restored, don't execute
103         if ($this->task->is_excluding_activities()) {
104             return false;
105         }
107         // There should only be one grade category (the 1 associated with the course itself)
108         // If other categories already exist we're restoring into an existing course.
109         // Restoring categories into a course with an existing category structure is unlikely to go well
110         $category = new stdclass();
111         $category->courseid  = $this->get_courseid();
112         $catcount = $DB->count_records('grade_categories', (array)$category);
113         if ($catcount>1) {
114             return false;
115         }
117         // Arrived here, execute the step
118         return true;
119      }
121     protected function define_structure() {
122         $paths = array();
123         $userinfo = $this->task->get_setting_value('users');
125         $paths[] = new restore_path_element('gradebook', '/gradebook');
126         $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
127         $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
128         if ($userinfo) {
129             $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
130         }
131         $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
132         $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
134         return $paths;
135     }
137     protected function process_gradebook($data) {
138     }
140     protected function process_grade_item($data) {
141         global $DB;
143         $data = (object)$data;
145         $oldid = $data->id;
146         $data->course = $this->get_courseid();
148         $data->courseid = $this->get_courseid();
150         if ($data->itemtype=='manual') {
151             // manual grade items store category id in categoryid
152             $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
153         } else if ($data->itemtype=='course') {
154             // course grade item stores their category id in iteminstance
155             $coursecat = grade_category::fetch_course_category($this->get_courseid());
156             $data->iteminstance = $coursecat->id;
157         } else if ($data->itemtype=='category') {
158             // category grade items store their category id in iteminstance
159             $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
160         } else {
161             throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
162         }
164         $data->scaleid   = $this->get_mappingid('scale', $data->scaleid, NULL);
165         $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
167         $data->locktime     = $this->apply_date_offset($data->locktime);
168         $data->timecreated  = $this->apply_date_offset($data->timecreated);
169         $data->timemodified = $this->apply_date_offset($data->timemodified);
171         $coursecategory = $newitemid = null;
172         //course grade item should already exist so updating instead of inserting
173         if($data->itemtype=='course') {
174             //get the ID of the already created grade item
175             $gi = new stdclass();
176             $gi->courseid  = $this->get_courseid();
177             $gi->itemtype  = $data->itemtype;
179             //need to get the id of the grade_category that was automatically created for the course
180             $category = new stdclass();
181             $category->courseid  = $this->get_courseid();
182             $category->parent  = null;
183             //course category fullname starts out as ? but may be edited
184             //$category->fullname  = '?';
185             $coursecategory = $DB->get_record('grade_categories', (array)$category);
186             $gi->iteminstance = $coursecategory->id;
188             $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
189             if (!empty($existinggradeitem)) {
190                 $data->id = $newitemid = $existinggradeitem->id;
191                 $DB->update_record('grade_items', $data);
192             }
193         }
195         if (empty($newitemid)) {
196             //in case we found the course category but still need to insert the course grade item
197             if ($data->itemtype=='course' && !empty($coursecategory)) {
198                 $data->iteminstance = $coursecategory->id;
199             }
201             $newitemid = $DB->insert_record('grade_items', $data);
202         }
203         $this->set_mapping('grade_item', $oldid, $newitemid);
204     }
206     protected function process_grade_grade($data) {
207         global $DB;
209         $data = (object)$data;
210         $olduserid = $data->userid;
212         $data->itemid = $this->get_new_parentid('grade_item');
214         $data->userid = $this->get_mappingid('user', $data->userid, null);
215         if (!empty($data->userid)) {
216             $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
217             $data->locktime     = $this->apply_date_offset($data->locktime);
218             // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
219             $data->overridden = $this->apply_date_offset($data->overridden);
220             $data->timecreated  = $this->apply_date_offset($data->timecreated);
221             $data->timemodified = $this->apply_date_offset($data->timemodified);
223             $newitemid = $DB->insert_record('grade_grades', $data);
224         } else {
225             debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
226         }
227     }
229     protected function process_grade_category($data) {
230         global $DB;
232         $data = (object)$data;
233         $oldid = $data->id;
235         $data->course = $this->get_courseid();
236         $data->courseid = $data->course;
238         $data->timecreated  = $this->apply_date_offset($data->timecreated);
239         $data->timemodified = $this->apply_date_offset($data->timemodified);
241         $newitemid = null;
242         //no parent means a course level grade category. That may have been created when the course was created
243         if(empty($data->parent)) {
244             //parent was being saved as 0 when it should be null
245             $data->parent = null;
247             //get the already created course level grade category
248             $category = new stdclass();
249             $category->courseid = $this->get_courseid();
250             $category->parent = null;
252             $coursecategory = $DB->get_record('grade_categories', (array)$category);
253             if (!empty($coursecategory)) {
254                 $data->id = $newitemid = $coursecategory->id;
255                 $DB->update_record('grade_categories', $data);
256             }
257         }
259         //need to insert a course category
260         if (empty($newitemid)) {
261             $newitemid = $DB->insert_record('grade_categories', $data);
262         }
263         $this->set_mapping('grade_category', $oldid, $newitemid);
264     }
265     protected function process_grade_letter($data) {
266         global $DB;
268         $data = (object)$data;
269         $oldid = $data->id;
271         $data->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
273         $newitemid = $DB->insert_record('grade_letters', $data);
274         $this->set_mapping('grade_letter', $oldid, $newitemid);
275     }
276     protected function process_grade_setting($data) {
277         global $DB;
279         $data = (object)$data;
280         $oldid = $data->id;
282         $data->courseid = $this->get_courseid();
284         $newitemid = $DB->insert_record('grade_settings', $data);
285         //$this->set_mapping('grade_setting', $oldid, $newitemid);
286     }
288     /**
289      * put all activity grade items in the correct grade category and mark all for recalculation
290      */
291     protected function after_execute() {
292         global $DB;
294         $conditions = array(
295             'backupid' => $this->get_restoreid(),
296             'itemname' => 'grade_item'//,
297             //'itemid'   => $itemid
298         );
299         $rs = $DB->get_recordset('backup_ids_temp', $conditions);
301         // We need this for calculation magic later on.
302         $mappings = array();
304         if (!empty($rs)) {
305             foreach($rs as $grade_item_backup) {
307                 // Store the oldid with the new id.
308                 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
310                 $updateobj = new stdclass();
311                 $updateobj->id = $grade_item_backup->newitemid;
313                 //if this is an activity grade item that needs to be put back in its correct category
314                 if (!empty($grade_item_backup->parentitemid)) {
315                     $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
316                     if (!is_null($oldcategoryid)) {
317                         $updateobj->categoryid = $oldcategoryid;
318                         $DB->update_record('grade_items', $updateobj);
319                     }
320                 } else {
321                     //mark course and category items as needing to be recalculated
322                     $updateobj->needsupdate=1;
323                     $DB->update_record('grade_items', $updateobj);
324                 }
325             }
326         }
327         $rs->close();
329         // We need to update the calculations for calculated grade items that may reference old
330         // grade item ids using ##gi\d+##.
331         // $mappings can be empty, use 0 if so (won't match ever)
332         list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
333         $sql = "SELECT gi.id, gi.calculation
334                   FROM {grade_items} gi
335                  WHERE gi.id {$sql} AND
336                        calculation IS NOT NULL";
337         $rs = $DB->get_recordset_sql($sql, $params);
338         foreach ($rs as $gradeitem) {
339             // Collect all of the used grade item id references
340             if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
341                 // This calculation doesn't reference any other grade items... EASY!
342                 continue;
343             }
344             // For this next bit we are going to do the replacement of id's in two steps:
345             // 1. We will replace all old id references with a special mapping reference.
346             // 2. We will replace all mapping references with id's
347             // Why do we do this?
348             // Because there potentially there will be an overlap of ids within the query and we
349             // we substitute the wrong id.. safest way around this is the two step system
350             $calculationmap = array();
351             $mapcount = 0;
352             foreach ($matches[1] as $match) {
353                 // Check that the old id is known to us, if not it was broken to begin with and will
354                 // continue to be broken.
355                 if (!array_key_exists($match, $mappings)) {
356                     continue;
357                 }
358                 // Our special mapping key
359                 $mapping = '##MAPPING'.$mapcount.'##';
360                 // The old id that exists within the calculation now
361                 $oldid = '##gi'.$match.'##';
362                 // The new id that we want to replace the old one with.
363                 $newid = '##gi'.$mappings[$match].'##';
364                 // Replace in the special mapping key
365                 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
366                 // And record the mapping
367                 $calculationmap[$mapping] = $newid;
368                 $mapcount++;
369             }
370             // Iterate all special mappings for this calculation and replace in the new id's
371             foreach ($calculationmap as $mapping => $newid) {
372                 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
373             }
374             // Update the calculation now that its being remapped
375             $DB->update_record('grade_items', $gradeitem);
376         }
377         $rs->close();
379         // Need to correct the grade category path and parent
380         $conditions = array(
381             'courseid' => $this->get_courseid()
382         );
384         $rs = $DB->get_recordset('grade_categories', $conditions);
385         // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
386         foreach ($rs as $gc) {
387             if (!empty($gc->parent)) {
388                 $grade_category = new stdClass();
389                 $grade_category->id = $gc->id;
390                 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
391                 $DB->update_record('grade_categories', $grade_category);
392             }
393         }
394         $rs->close();
396         // Now we can rebuild all the paths
397         $rs = $DB->get_recordset('grade_categories', $conditions);
398         foreach ($rs as $gc) {
399             $grade_category = new stdClass();
400             $grade_category->id = $gc->id;
401             $grade_category->path = grade_category::build_path($gc);
402             $grade_category->depth = substr_count($grade_category->path, '/') - 1;
403             $DB->update_record('grade_categories', $grade_category);
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     /**
594      * Processing functions go here
595      *
596      * @param array $data one file record including repositoryid and reference
597      */
598     public function process_file($data) {
600         $data = (object)$data; // handy
602         $isreference = !empty($data->repositoryid);
603         $issamesite = $this->task->is_samesite();
605         // If it's not samesite, we skip file refernces
606         if (!$issamesite && $isreference) {
607             return;
608         }
610         // load it if needed:
611         //   - it it is one of the annotated inforef files (course/section/activity/block)
612         //   - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
613         // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
614         //       but then we'll need to change it to load plugins itself (because this is executed too early in restore)
615         $isfileref   = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
616         $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
617                         $data->component == 'grouping' || $data->component == 'grade' ||
618                         $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
619         if ($isfileref || $iscomponent) {
620             // Process files
621             restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
622         }
623     }
626 /**
627  * Execution step that, *conditionally* (if there isn't preloaded information),
628  * will load all the needed roles to backup_temp_ids. They will be stored with
629  * "role" itemname. Also it will perform one automatic mapping to roles existing
630  * in the target site, based in permissions of the user performing the restore,
631  * archetypes and other bits. At the end, each original role will have its associated
632  * target role or 0 if it's going to be skipped. Note we wrap everything over one
633  * restore_dbops method, as far as the same stuff is going to be also executed
634  * by restore prechecks
635  */
636 class restore_load_and_map_roles extends restore_execution_step {
638     protected function define_execution() {
639         if ($this->task->get_preloaded_information()) { // if info is already preloaded
640             return;
641         }
643         $file = $this->get_basepath() . '/roles.xml';
644         // Load needed toles to temp_ids
645         restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
647         // Process roles, mapping/skipping. Any error throws exception
648         // Note we pass controller's info because it can contain role mapping information
649         // about manual mappings performed by UI
650         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);
651     }
654 /**
655  * Execution step that, *conditionally* (if there isn't preloaded information
656  * and users have been selected in settings, will load all the needed users
657  * to backup_temp_ids. They will be stored with "user" itemname and with
658  * their original contextid as paremitemid
659  */
660 class restore_load_included_users extends restore_execution_step {
662     protected function define_execution() {
664         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
665             return;
666         }
667         if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
668             return;
669         }
670         $file = $this->get_basepath() . '/users.xml';
671         restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
672     }
675 /**
676  * Execution step that, *conditionally* (if there isn't preloaded information
677  * and users have been selected in settings, will process all the needed users
678  * in order to decide and perform any action with them (create / map / error)
679  * Note: Any error will cause exception, as far as this is the same processing
680  * than the one into restore prechecks (that should have stopped process earlier)
681  */
682 class restore_process_included_users extends restore_execution_step {
684     protected function define_execution() {
686         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
687             return;
688         }
689         if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
690             return;
691         }
692         restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
693     }
696 /**
697  * Execution step that will create all the needed users as calculated
698  * by @restore_process_included_users (those having newiteind = 0)
699  */
700 class restore_create_included_users extends restore_execution_step {
702     protected function define_execution() {
704         restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->task->get_userid());
705     }
708 /**
709  * Structure step that will create all the needed groups and groupings
710  * by loading them from the groups.xml file performing the required matches.
711  * Note group members only will be added if restoring user info
712  */
713 class restore_groups_structure_step extends restore_structure_step {
715     protected function define_structure() {
717         $paths = array(); // Add paths here
719         $paths[] = new restore_path_element('group', '/groups/group');
720         if ($this->get_setting_value('users')) {
721             $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
722         }
723         $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
724         $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
726         return $paths;
727     }
729     // Processing functions go here
730     public function process_group($data) {
731         global $DB;
733         $data = (object)$data; // handy
734         $data->courseid = $this->get_courseid();
736         // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
737         // another a group in the same course
738         $context = context_course::instance($data->courseid);
739         if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
740             if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
741                 unset($data->idnumber);
742             }
743         } else {
744             unset($data->idnumber);
745         }
747         $oldid = $data->id;    // need this saved for later
749         $restorefiles = false; // Only if we end creating the group
751         // Search if the group already exists (by name & description) in the target course
752         $description_clause = '';
753         $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
754         if (!empty($data->description)) {
755             $description_clause = ' AND ' .
756                                   $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
757            $params['description'] = $data->description;
758         }
759         if (!$groupdb = $DB->get_record_sql("SELECT *
760                                                FROM {groups}
761                                               WHERE courseid = :courseid
762                                                 AND name = :grname $description_clause", $params)) {
763             // group doesn't exist, create
764             $newitemid = $DB->insert_record('groups', $data);
765             $restorefiles = true; // We'll restore the files
766         } else {
767             // group exists, use it
768             $newitemid = $groupdb->id;
769         }
770         // Save the id mapping
771         $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
772     }
774     public function process_member($data) {
775         global $DB;
777         $data = (object)$data; // handy
779         // get parent group->id
780         $data->groupid = $this->get_new_parentid('group');
782         // map user newitemid and insert if not member already
783         if ($data->userid = $this->get_mappingid('user', $data->userid)) {
784             if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
785                 $DB->insert_record('groups_members', $data);
786             }
787         }
788     }
790     public function process_grouping($data) {
791         global $DB;
793         $data = (object)$data; // handy
794         $data->courseid = $this->get_courseid();
796         // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
797         // another a grouping in the same course
798         $context = context_course::instance($data->courseid);
799         if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
800             if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
801                 unset($data->idnumber);
802             }
803         } else {
804             unset($data->idnumber);
805         }
807         $oldid = $data->id;    // need this saved for later
808         $restorefiles = false; // Only if we end creating the grouping
810         // Search if the grouping already exists (by name & description) in the target course
811         $description_clause = '';
812         $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
813         if (!empty($data->description)) {
814             $description_clause = ' AND ' .
815                                   $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
816            $params['description'] = $data->description;
817         }
818         if (!$groupingdb = $DB->get_record_sql("SELECT *
819                                                   FROM {groupings}
820                                                  WHERE courseid = :courseid
821                                                    AND name = :grname $description_clause", $params)) {
822             // grouping doesn't exist, create
823             $newitemid = $DB->insert_record('groupings', $data);
824             $restorefiles = true; // We'll restore the files
825         } else {
826             // grouping exists, use it
827             $newitemid = $groupingdb->id;
828         }
829         // Save the id mapping
830         $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
831     }
833     public function process_grouping_group($data) {
834         global $DB;
836         $data = (object)$data;
838         $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
839         $data->groupid    = $this->get_mappingid('group', $data->groupid); // Get from mappings
841         $params = array();
842         $params['groupingid'] = $data->groupingid;
843         $params['groupid']    = $data->groupid;
845         if (!$DB->record_exists('groupings_groups', $params)) {
846             $DB->insert_record('groupings_groups', $data);  // No need to set this mapping (no child info nor files)
847         }
848     }
850     protected function after_execute() {
851         // Add group related files, matching with "group" mappings
852         $this->add_related_files('group', 'icon', 'group');
853         $this->add_related_files('group', 'description', 'group');
854         // Add grouping related files, matching with "grouping" mappings
855         $this->add_related_files('grouping', 'description', 'grouping');
856     }
860 /**
861  * Structure step that will create all the needed scales
862  * by loading them from the scales.xml
863  */
864 class restore_scales_structure_step extends restore_structure_step {
866     protected function define_structure() {
868         $paths = array(); // Add paths here
869         $paths[] = new restore_path_element('scale', '/scales_definition/scale');
870         return $paths;
871     }
873     protected function process_scale($data) {
874         global $DB;
876         $data = (object)$data;
878         $restorefiles = false; // Only if we end creating the group
880         $oldid = $data->id;    // need this saved for later
882         // Look for scale (by 'scale' both in standard (course=0) and current course
883         // with priority to standard scales (ORDER clause)
884         // scale is not course unique, use get_record_sql to suppress warning
885         // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
886         $compare_scale_clause = $DB->sql_compare_text('scale')  . ' = ' . $DB->sql_compare_text(':scaledesc');
887         $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
888         if (!$scadb = $DB->get_record_sql("SELECT *
889                                             FROM {scale}
890                                            WHERE courseid IN (0, :courseid)
891                                              AND $compare_scale_clause
892                                         ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
893             // Remap the user if possible, defaut to user performing the restore if not
894             $userid = $this->get_mappingid('user', $data->userid);
895             $data->userid = $userid ? $userid : $this->task->get_userid();
896             // Remap the course if course scale
897             $data->courseid = $data->courseid ? $this->get_courseid() : 0;
898             // If global scale (course=0), check the user has perms to create it
899             // falling to course scale if not
900             $systemctx = get_context_instance(CONTEXT_SYSTEM);
901             if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
902                 $data->courseid = $this->get_courseid();
903             }
904             // scale doesn't exist, create
905             $newitemid = $DB->insert_record('scale', $data);
906             $restorefiles = true; // We'll restore the files
907         } else {
908             // scale exists, use it
909             $newitemid = $scadb->id;
910         }
911         // Save the id mapping (with files support at system context)
912         $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
913     }
915     protected function after_execute() {
916         // Add scales related files, matching with "scale" mappings
917         $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
918     }
922 /**
923  * Structure step that will create all the needed outocomes
924  * by loading them from the outcomes.xml
925  */
926 class restore_outcomes_structure_step extends restore_structure_step {
928     protected function define_structure() {
930         $paths = array(); // Add paths here
931         $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
932         return $paths;
933     }
935     protected function process_outcome($data) {
936         global $DB;
938         $data = (object)$data;
940         $restorefiles = false; // Only if we end creating the group
942         $oldid = $data->id;    // need this saved for later
944         // Look for outcome (by shortname both in standard (courseid=null) and current course
945         // with priority to standard outcomes (ORDER clause)
946         // outcome is not course unique, use get_record_sql to suppress warning
947         $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
948         if (!$outdb = $DB->get_record_sql('SELECT *
949                                              FROM {grade_outcomes}
950                                             WHERE shortname = :shortname
951                                               AND (courseid = :courseid OR courseid IS NULL)
952                                          ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
953             // Remap the user
954             $userid = $this->get_mappingid('user', $data->usermodified);
955             $data->usermodified = $userid ? $userid : $this->task->get_userid();
956             // Remap the scale
957             $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
958             // Remap the course if course outcome
959             $data->courseid = $data->courseid ? $this->get_courseid() : null;
960             // If global outcome (course=null), check the user has perms to create it
961             // falling to course outcome if not
962             $systemctx = get_context_instance(CONTEXT_SYSTEM);
963             if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
964                 $data->courseid = $this->get_courseid();
965             }
966             // outcome doesn't exist, create
967             $newitemid = $DB->insert_record('grade_outcomes', $data);
968             $restorefiles = true; // We'll restore the files
969         } else {
970             // scale exists, use it
971             $newitemid = $outdb->id;
972         }
973         // Set the corresponding grade_outcomes_courses record
974         $outcourserec = new stdclass();
975         $outcourserec->courseid  = $this->get_courseid();
976         $outcourserec->outcomeid = $newitemid;
977         if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
978             $DB->insert_record('grade_outcomes_courses', $outcourserec);
979         }
980         // Save the id mapping (with files support at system context)
981         $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
982     }
984     protected function after_execute() {
985         // Add outcomes related files, matching with "outcome" mappings
986         $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
987     }
990 /**
991  * Execution step that, *conditionally* (if there isn't preloaded information
992  * will load all the question categories and questions (header info only)
993  * to backup_temp_ids. They will be stored with "question_category" and
994  * "question" itemnames and with their original contextid and question category
995  * id as paremitemids
996  */
997 class restore_load_categories_and_questions extends restore_execution_step {
999     protected function define_execution() {
1001         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1002             return;
1003         }
1004         $file = $this->get_basepath() . '/questions.xml';
1005         restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1006     }
1009 /**
1010  * Execution step that, *conditionally* (if there isn't preloaded information)
1011  * will process all the needed categories and questions
1012  * in order to decide and perform any action with them (create / map / error)
1013  * Note: Any error will cause exception, as far as this is the same processing
1014  * than the one into restore prechecks (that should have stopped process earlier)
1015  */
1016 class restore_process_categories_and_questions extends restore_execution_step {
1018     protected function define_execution() {
1020         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1021             return;
1022         }
1023         restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1024     }
1027 /**
1028  * Structure step that will read the section.xml creating/updating sections
1029  * as needed, rebuilding course cache and other friends
1030  */
1031 class restore_section_structure_step extends restore_structure_step {
1033     protected function define_structure() {
1034         global $CFG;
1036         $paths = array();
1038         $section = new restore_path_element('section', '/section');
1039         $paths[] = $section;
1040         if ($CFG->enableavailability) {
1041             $paths[] = new restore_path_element('availability', '/section/availability');
1042         }
1044         // Apply for 'format' plugins optional paths at section level
1045         $this->add_plugin_structure('format', $section);
1047         return $paths;
1048     }
1050     public function process_section($data) {
1051         global $CFG, $DB;
1052         $data = (object)$data;
1053         $oldid = $data->id; // We'll need this later
1055         $restorefiles = false;
1057         // Look for the section
1058         $section = new stdclass();
1059         $section->course  = $this->get_courseid();
1060         $section->section = $data->number;
1061         // Section doesn't exist, create it with all the info from backup
1062         if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1063             $section->name = $data->name;
1064             $section->summary = $data->summary;
1065             $section->summaryformat = $data->summaryformat;
1066             $section->sequence = '';
1067             $section->visible = $data->visible;
1068             if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1069                 $section->availablefrom = 0;
1070                 $section->availableuntil = 0;
1071                 $section->showavailability = 0;
1072             } else {
1073                 $section->availablefrom = isset($data->availablefrom) ? $this->apply_date_offset($data->availablefrom) : 0;
1074                 $section->availableuntil = isset($data->availableuntil) ? $this->apply_date_offset($data->availableuntil) : 0;
1075                 $section->showavailability = isset($data->showavailability) ? $data->showavailability : 0;
1076             }
1077             if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
1078                 $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
1079             }
1080             $newitemid = $DB->insert_record('course_sections', $section);
1081             $restorefiles = true;
1083         // Section exists, update non-empty information
1084         } else {
1085             $section->id = $secrec->id;
1086             if (empty($secrec->name)) {
1087                 $section->name = $data->name;
1088             }
1089             if (empty($secrec->summary)) {
1090                 $section->summary = $data->summary;
1091                 $section->summaryformat = $data->summaryformat;
1092                 $restorefiles = true;
1093             }
1094             if (empty($secrec->groupingid)) {
1095                 if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
1096                     $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
1097                 }
1098             }
1100             // Don't update available from, available until, or show availability
1101             // (I didn't see a useful way to define whether existing or new one should
1102             // take precedence).
1104             $DB->update_record('course_sections', $section);
1105             $newitemid = $secrec->id;
1106         }
1108         // Annotate the section mapping, with restorefiles option if needed
1109         $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1111         // set the new course_section id in the task
1112         $this->task->set_sectionid($newitemid);
1115         // Commented out. We never modify course->numsections as far as that is used
1116         // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1117         // Note: We keep the code here, to know about and because of the possibility of making this
1118         // optional based on some setting/attribute in the future
1119         // If needed, adjust course->numsections
1120         //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1121         //    if ($numsections < $section->section) {
1122         //        $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1123         //    }
1124         //}
1125     }
1127     public function process_availability($data) {
1128         global $DB;
1129         $data = (object)$data;
1131         $data->coursesectionid = $this->task->get_sectionid();
1133         // NOTE: Other values in $data need updating, but these (cm,
1134         // grade items) have not yet been restored, so are done later.
1136         $newid = $DB->insert_record('course_sections_availability', $data);
1138         // We do not need to map between old and new id but storing a mapping
1139         // means it gets added to the backup_ids table to record which ones
1140         // need updating. The mapping is stored with $newid => $newid for
1141         // convenience.
1142         $this->set_mapping('course_sections_availability', $newid, $newid);
1143     }
1145     protected function after_execute() {
1146         // Add section related files, with 'course_section' itemid to match
1147         $this->add_related_files('course', 'section', 'course_section');
1148     }
1150     public function after_restore() {
1151         global $DB;
1153         $sectionid = $this->get_task()->get_sectionid();
1155         // Get data object for current section availability (if any).
1156         $data = $DB->get_record('course_sections_availability',
1157                 array('coursesectionid' => $sectionid), 'id, sourcecmid, gradeitemid', IGNORE_MISSING);
1159         // If it exists, update mappings.
1160         if ($data) {
1161             // Only update mappings for entries which are created by this restore.
1162             // Otherwise, when you restore to an existing course, it will mess up
1163             // existing section availability entries.
1164             if (!$this->get_mappingid('course_sections_availability', $data->id, false)) {
1165                 return;
1166             }
1168             // Update source cmid / grade id to new value.
1169             $data->sourcecmid = $this->get_mappingid('course_module', $data->sourcecmid);
1170             if (!$data->sourcecmid) {
1171                 $data->sourcecmid = null;
1172             }
1173             $data->gradeitemid = $this->get_mappingid('grade_item', $data->gradeitemid);
1174             if (!$data->gradeitemid) {
1175                 $data->gradeitemid = null;
1176             }
1178             $DB->update_record('course_sections_availability', $data);
1179         }
1180     }
1184 /**
1185  * Structure step that will read the course.xml file, loading it and performing
1186  * various actions depending of the site/restore settings. Note that target
1187  * course always exist before arriving here so this step will be updating
1188  * the course record (never inserting)
1189  */
1190 class restore_course_structure_step extends restore_structure_step {
1191     /**
1192      * @var bool this gets set to true by {@link process_course()} if we are
1193      * restoring an old coures that used the legacy 'module security' feature.
1194      * If so, we have to do more work in {@link after_execute()}.
1195      */
1196     protected $legacyrestrictmodules = false;
1198     /**
1199      * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1200      * array with array keys the module names ('forum', 'quiz', etc.). These are
1201      * the modules that are allowed according to the data in the backup file.
1202      * In {@link after_execute()} we then have to prevent adding of all the other
1203      * types of activity.
1204      */
1205     protected $legacyallowedmodules = array();
1207     protected function define_structure() {
1209         $course = new restore_path_element('course', '/course');
1210         $category = new restore_path_element('category', '/course/category');
1211         $tag = new restore_path_element('tag', '/course/tags/tag');
1212         $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1214         // Apply for 'format' plugins optional paths at course level
1215         $this->add_plugin_structure('format', $course);
1217         // Apply for 'theme' plugins optional paths at course level
1218         $this->add_plugin_structure('theme', $course);
1220         // Apply for 'report' plugins optional paths at course level
1221         $this->add_plugin_structure('report', $course);
1223         // Apply for 'course report' plugins optional paths at course level
1224         $this->add_plugin_structure('coursereport', $course);
1226         // Apply for plagiarism plugins optional paths at course level
1227         $this->add_plugin_structure('plagiarism', $course);
1229         return array($course, $category, $tag, $allowed_module);
1230     }
1232     /**
1233      * Processing functions go here
1234      *
1235      * @global moodledatabase $DB
1236      * @param stdClass $data
1237      */
1238     public function process_course($data) {
1239         global $CFG, $DB;
1241         $data = (object)$data;
1243         $fullname  = $this->get_setting_value('course_fullname');
1244         $shortname = $this->get_setting_value('course_shortname');
1245         $startdate = $this->get_setting_value('course_startdate');
1247         // Calculate final course names, to avoid dupes
1248         list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1250         // Need to change some fields before updating the course record
1251         $data->id = $this->get_courseid();
1252         $data->fullname = $fullname;
1253         $data->shortname= $shortname;
1255         $context = get_context_instance_by_id($this->task->get_contextid());
1256         if (has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1257             $data->idnumber = '';
1258         } else {
1259             unset($data->idnumber);
1260         }
1262         // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1263         // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1264         if (empty($data->hiddensections)) {
1265             $data->hiddensections = 0;
1266         }
1268         // Set legacyrestrictmodules to true if the course was resticting modules. If so
1269         // then we will need to process restricted modules after execution.
1270         $this->legacyrestrictmodules = !empty($data->restrictmodules);
1272         $data->startdate= $this->apply_date_offset($data->startdate);
1273         if ($data->defaultgroupingid) {
1274             $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1275         }
1276         if (empty($CFG->enablecompletion)) {
1277             $data->enablecompletion = 0;
1278             $data->completionstartonenrol = 0;
1279             $data->completionnotify = 0;
1280         }
1281         $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1282         if (!array_key_exists($data->lang, $languages)) {
1283             $data->lang = '';
1284         }
1286         $themes = get_list_of_themes(); // Get themes for quick search later
1287         if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1288             $data->theme = '';
1289         }
1291         // Course record ready, update it
1292         $DB->update_record('course', $data);
1294         // Role name aliases
1295         restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1296     }
1298     public function process_category($data) {
1299         // Nothing to do with the category. UI sets it before restore starts
1300     }
1302     public function process_tag($data) {
1303         global $CFG, $DB;
1305         $data = (object)$data;
1307         if (!empty($CFG->usetags)) { // if enabled in server
1308             // TODO: This is highly inneficient. Each time we add one tag
1309             // we fetch all the existing because tag_set() deletes them
1310             // so everything must be reinserted on each call
1311             $tags = array();
1312             $existingtags = tag_get_tags('course', $this->get_courseid());
1313             // Re-add all the existitng tags
1314             foreach ($existingtags as $existingtag) {
1315                 $tags[] = $existingtag->rawname;
1316             }
1317             // Add the one being restored
1318             $tags[] = $data->rawname;
1319             // Send all the tags back to the course
1320             tag_set('course', $this->get_courseid(), $tags);
1321         }
1322     }
1324     public function process_allowed_module($data) {
1325         $data = (object)$data;
1327         // Backwards compatiblity support for the data that used to be in the
1328         // course_allowed_modules table.
1329         if ($this->legacyrestrictmodules) {
1330             $this->legacyallowedmodules[$data->modulename] = 1;
1331         }
1332     }
1334     protected function after_execute() {
1335         global $DB;
1337         // Add course related files, without itemid to match
1338         $this->add_related_files('course', 'summary', null);
1339         $this->add_related_files('course', 'legacy', null);
1341         // Deal with legacy allowed modules.
1342         if ($this->legacyrestrictmodules) {
1343             $context = context_course::instance($this->get_courseid());
1345             list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1346             list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1347             foreach ($managerroleids as $roleid) {
1348                 unset($roleids[$roleid]);
1349             }
1351             foreach (get_plugin_list('mod') as $modname => $notused) {
1352                 if (isset($this->legacyallowedmodules[$modname])) {
1353                     // Module is allowed, no worries.
1354                     continue;
1355                 }
1357                 $capability = 'mod/' . $modname . ':addinstance';
1358                 foreach ($roleids as $roleid) {
1359                     assign_capability($capability, CAP_PREVENT, $roleid, $context);
1360                 }
1361             }
1362         }
1363     }
1367 /*
1368  * Structure step that will read the roles.xml file (at course/activity/block levels)
1369  * containig all the role_assignments and overrides for that context. If corresponding to
1370  * one mapped role, they will be applied to target context. Will observe the role_assignments
1371  * setting to decide if ras are restored.
1372  * Note: only ras with component == null are restored as far as the any ra with component
1373  * is handled by one enrolment plugin, hence it will createt the ras later
1374  */
1375 class restore_ras_and_caps_structure_step extends restore_structure_step {
1377     protected function define_structure() {
1379         $paths = array();
1381         // Observe the role_assignments setting
1382         if ($this->get_setting_value('role_assignments')) {
1383             $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1384         }
1385         $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1387         return $paths;
1388     }
1390     /**
1391      * Assign roles
1392      *
1393      * This has to be called after enrolments processing.
1394      *
1395      * @param mixed $data
1396      * @return void
1397      */
1398     public function process_assignment($data) {
1399         global $DB;
1401         $data = (object)$data;
1403         // Check roleid, userid are one of the mapped ones
1404         if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1405             return;
1406         }
1407         if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1408             return;
1409         }
1410         if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1411             // Only assign roles to not deleted users
1412             return;
1413         }
1414         if (!$contextid = $this->task->get_contextid()) {
1415             return;
1416         }
1418         if (empty($data->component)) {
1419             // assign standard manual roles
1420             // TODO: role_assign() needs one userid param to be able to specify our restore userid
1421             role_assign($newroleid, $newuserid, $contextid);
1423         } else if ((strpos($data->component, 'enrol_') === 0)) {
1424             // Deal with enrolment roles
1425             if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1426                 if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
1427                     //note: we have to verify component because it might have changed
1428                     if ($component === 'enrol_manual') {
1429                         // manual is a special case, we do not use components - this owudl happen when converting from other plugin
1430                         role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
1431                     } else {
1432                         role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
1433                     }
1434                 }
1435             }
1436         }
1437     }
1439     public function process_override($data) {
1440         $data = (object)$data;
1442         // Check roleid is one of the mapped ones
1443         $newroleid = $this->get_mappingid('role', $data->roleid);
1444         // If newroleid and context are valid assign it via API (it handles dupes and so on)
1445         if ($newroleid && $this->task->get_contextid()) {
1446             // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1447             // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1448             assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1449         }
1450     }
1453 /**
1454  * This structure steps restores the enrol plugins and their underlying
1455  * enrolments, performing all the mappings and/or movements required
1456  */
1457 class restore_enrolments_structure_step extends restore_structure_step {
1459     /**
1460      * Conditionally decide if this step should be executed.
1461      *
1462      * This function checks the following parameter:
1463      *
1464      *   1. the course/enrolments.xml file exists
1465      *
1466      * @return bool true is safe to execute, false otherwise
1467      */
1468     protected function execute_condition() {
1470         // Check it is included in the backup
1471         $fullpath = $this->task->get_taskbasepath();
1472         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1473         if (!file_exists($fullpath)) {
1474             // Not found, can't restore enrolments info
1475             return false;
1476         }
1478         return true;
1479     }
1481     protected function define_structure() {
1483         $paths = array();
1485         $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1486         $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1488         return $paths;
1489     }
1491     /**
1492      * Create enrolment instances.
1493      *
1494      * This has to be called after creation of roles
1495      * and before adding of role assignments.
1496      *
1497      * @param mixed $data
1498      * @return void
1499      */
1500     public function process_enrol($data) {
1501         global $DB;
1503         $data = (object)$data;
1504         $oldid = $data->id; // We'll need this later
1506         $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);
1508         if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
1509             // TODO: add complex restore support via custom class
1510             debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
1511             $this->set_mapping('enrol', $oldid, 0);
1512             return;
1513         }
1515         // Perform various checks to decide what to do with the enrol plugin
1516         if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
1517             // TODO: decide if we want to switch to manual enrol - we need UI for this
1518             debugging("Enrol plugin data can not be restored because it is not installed");
1519             $this->set_mapping('enrol', $oldid, 0);
1520             return;
1522         }
1523         if (!enrol_is_enabled($data->enrol)) {
1524             // TODO: decide if we want to switch to manual enrol - we need UI for this
1525             debugging("Enrol plugin data can not be restored because it is not enabled");
1526             $this->set_mapping('enrol', $oldid, 0);
1527             return;
1528         }
1530         // map standard fields - plugin has to process custom fields from own restore class
1531         $data->roleid = $this->get_mappingid('role', $data->roleid);
1532         //TODO: should we move the enrol start and end date here?
1534         // always add instance, if the course does not support multiple instances it just returns NULL
1535         $enrol = enrol_get_plugin($data->enrol);
1536         $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1537         if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
1538             // ok
1539         } else {
1540             if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
1541                 // most probably plugin that supports only one instance
1542                 $newitemid = key($instances);
1543             } else {
1544                 debugging('Can not create new enrol instance or reuse existing');
1545                 $newitemid = 0;
1546             }
1547         }
1549         if ($restoretype === ENROL_RESTORE_NOUSERS) {
1550             // plugin requests to prevent restore of any users
1551             $newitemid = 0;
1552         }
1554         $this->set_mapping('enrol', $oldid, $newitemid);
1555     }
1557     /**
1558      * Create user enrolments
1559      *
1560      * This has to be called after creation of enrolment instances
1561      * and before adding of role assignments.
1562      *
1563      * @param mixed $data
1564      * @return void
1565      */
1566     public function process_enrolment($data) {
1567         global $DB;
1569         $data = (object)$data;
1571         // Process only if parent instance have been mapped
1572         if ($enrolid = $this->get_new_parentid('enrol')) {
1573             if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1574                 // And only if user is a mapped one
1575                 if ($userid = $this->get_mappingid('user', $data->userid)) {
1576                     $enrol = enrol_get_plugin($instance->enrol);
1577                     //TODO: do we need specify modifierid?
1578                     $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
1579                     //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
1580                 }
1581             }
1582         }
1583     }
1587 /**
1588  * Make sure the user restoring the course can actually access it.
1589  */
1590 class restore_fix_restorer_access_step extends restore_execution_step {
1591     protected function define_execution() {
1592         global $CFG, $DB;
1594         if (!$userid = $this->task->get_userid()) {
1595             return;
1596         }
1598         if (empty($CFG->restorernewroleid)) {
1599             // Bad luck, no fallback role for restorers specified
1600             return;
1601         }
1603         $courseid = $this->get_courseid();
1604         $context = context_course::instance($courseid);
1606         if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1607             // Current user may access the course (admin, category manager or restored teacher enrolment usually)
1608             return;
1609         }
1611         // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
1612         role_assign($CFG->restorernewroleid, $userid, $context);
1614         if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1615             // Extra role is enough, yay!
1616             return;
1617         }
1619         // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
1620         // hopefully admin selected suitable $CFG->restorernewroleid ...
1621         if (!enrol_is_enabled('manual')) {
1622             return;
1623         }
1624         if (!$enrol = enrol_get_plugin('manual')) {
1625             return;
1626         }
1627         if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
1628             $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
1629             $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
1630             $enrol->add_instance($course, $fields);
1631         }
1633         enrol_try_internal_enrol($courseid, $userid);
1634     }
1638 /**
1639  * This structure steps restores the filters and their configs
1640  */
1641 class restore_filters_structure_step extends restore_structure_step {
1643     protected function define_structure() {
1645         $paths = array();
1647         $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1648         $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1650         return $paths;
1651     }
1653     public function process_active($data) {
1655         $data = (object)$data;
1657         if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1658             return;
1659         }
1660         filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1661     }
1663     public function process_config($data) {
1665         $data = (object)$data;
1667         if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1668             return;
1669         }
1670         filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1671     }
1675 /**
1676  * This structure steps restores the comments
1677  * Note: Cannot use the comments API because defaults to USER->id.
1678  * That should change allowing to pass $userid
1679  */
1680 class restore_comments_structure_step extends restore_structure_step {
1682     protected function define_structure() {
1684         $paths = array();
1686         $paths[] = new restore_path_element('comment', '/comments/comment');
1688         return $paths;
1689     }
1691     public function process_comment($data) {
1692         global $DB;
1694         $data = (object)$data;
1696         // First of all, if the comment has some itemid, ask to the task what to map
1697         $mapping = false;
1698         if ($data->itemid) {
1699             $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1700             $data->itemid = $this->get_mappingid($mapping, $data->itemid);
1701         }
1702         // Only restore the comment if has no mapping OR we have found the matching mapping
1703         if (!$mapping || $data->itemid) {
1704             // Only if user mapping and context
1705             $data->userid = $this->get_mappingid('user', $data->userid);
1706             if ($data->userid && $this->task->get_contextid()) {
1707                 $data->contextid = $this->task->get_contextid();
1708                 // Only if there is another comment with same context/user/timecreated
1709                 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1710                 if (!$DB->record_exists('comments', $params)) {
1711                     $DB->insert_record('comments', $data);
1712                 }
1713             }
1714         }
1715     }
1718 /**
1719  * This structure steps restores the calendar events
1720  */
1721 class restore_calendarevents_structure_step extends restore_structure_step {
1723     protected function define_structure() {
1725         $paths = array();
1727         $paths[] = new restore_path_element('calendarevents', '/events/event');
1729         return $paths;
1730     }
1732     public function process_calendarevents($data) {
1733         global $DB;
1735         $data = (object)$data;
1736         $oldid = $data->id;
1737         $restorefiles = true; // We'll restore the files
1738         // Find the userid and the groupid associated with the event. Return if not found.
1739         $data->userid = $this->get_mappingid('user', $data->userid);
1740         if ($data->userid === false) {
1741             return;
1742         }
1743         if (!empty($data->groupid)) {
1744             $data->groupid = $this->get_mappingid('group', $data->groupid);
1745             if ($data->groupid === false) {
1746                 return;
1747             }
1748         }
1750         $params = array(
1751                 'name'           => $data->name,
1752                 'description'    => $data->description,
1753                 'format'         => $data->format,
1754                 'courseid'       => $this->get_courseid(),
1755                 'groupid'        => $data->groupid,
1756                 'userid'         => $data->userid,
1757                 'repeatid'       => $data->repeatid,
1758                 'modulename'     => $data->modulename,
1759                 'eventtype'      => $data->eventtype,
1760                 'timestart'      => $this->apply_date_offset($data->timestart),
1761                 'timeduration'   => $data->timeduration,
1762                 'visible'        => $data->visible,
1763                 'uuid'           => $data->uuid,
1764                 'sequence'       => $data->sequence,
1765                 'timemodified'    => $this->apply_date_offset($data->timemodified));
1766         if ($this->name == 'activity_calendar') {
1767             $params['instance'] = $this->task->get_activityid();
1768         } else {
1769             $params['instance'] = 0;
1770         }
1771         $sql = 'SELECT id FROM {event} WHERE name = ? AND courseid = ? AND
1772                 repeatid = ? AND modulename = ? AND timestart = ? AND timeduration =?
1773                 AND ' . $DB->sql_compare_text('description', 255) . ' = ' . $DB->sql_compare_text('?', 255);
1774         $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
1775         $result = $DB->record_exists_sql($sql, $arg);
1776         if (empty($result)) {
1777             $newitemid = $DB->insert_record('event', $params);
1778             $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
1779         }
1781     }
1782     protected function after_execute() {
1783         // Add related files
1784         $this->add_related_files('calendar', 'event_description', 'event_description');
1785     }
1788 class restore_course_completion_structure_step extends restore_structure_step {
1790     /**
1791      * Conditionally decide if this step should be executed.
1792      *
1793      * This function checks parameters that are not immediate settings to ensure
1794      * that the enviroment is suitable for the restore of course completion info.
1795      *
1796      * This function checks the following four parameters:
1797      *
1798      *   1. Course completion is enabled on the site
1799      *   2. The backup includes course completion information
1800      *   3. All modules are restorable
1801      *   4. All modules are marked for restore.
1802      *
1803      * @return bool True is safe to execute, false otherwise
1804      */
1805     protected function execute_condition() {
1806         global $CFG;
1808         // First check course completion is enabled on this site
1809         if (empty($CFG->enablecompletion)) {
1810             // Disabled, don't restore course completion
1811             return false;
1812         }
1814         // Check it is included in the backup
1815         $fullpath = $this->task->get_taskbasepath();
1816         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1817         if (!file_exists($fullpath)) {
1818             // Not found, can't restore course completion
1819             return false;
1820         }
1822         // Check we are able to restore all backed up modules
1823         if ($this->task->is_missing_modules()) {
1824             return false;
1825         }
1827         // Finally check all modules within the backup are being restored.
1828         if ($this->task->is_excluding_activities()) {
1829             return false;
1830         }
1832         return true;
1833     }
1835     /**
1836      * Define the course completion structure
1837      *
1838      * @return array Array of restore_path_element
1839      */
1840     protected function define_structure() {
1842         // To know if we are including user completion info
1843         $userinfo = $this->get_setting_value('userscompletion');
1845         $paths = array();
1846         $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1847         $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1848         $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1850         if ($userinfo) {
1851             $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1852             $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1853         }
1855         return $paths;
1857     }
1859     /**
1860      * Process course completion criteria
1861      *
1862      * @global moodle_database $DB
1863      * @param stdClass $data
1864      */
1865     public function process_course_completion_criteria($data) {
1866         global $DB;
1868         $data = (object)$data;
1869         $data->course = $this->get_courseid();
1871         // Apply the date offset to the time end field
1872         $data->timeend = $this->apply_date_offset($data->timeend);
1874         // Map the role from the criteria
1875         if (!empty($data->role)) {
1876             $data->role = $this->get_mappingid('role', $data->role);
1877         }
1879         $skipcriteria = false;
1881         // If the completion criteria is for a module we need to map the module instance
1882         // to the new module id.
1883         if (!empty($data->moduleinstance) && !empty($data->module)) {
1884             $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
1885             if (empty($data->moduleinstance)) {
1886                 $skipcriteria = true;
1887             }
1888         } else {
1889             $data->module = null;
1890             $data->moduleinstance = null;
1891         }
1893         // We backup the course shortname rather than the ID so that we can match back to the course
1894         if (!empty($data->courseinstanceshortname)) {
1895             $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1896             if (!$courseinstanceid) {
1897                 $skipcriteria = true;
1898             }
1899         } else {
1900             $courseinstanceid = null;
1901         }
1902         $data->courseinstance = $courseinstanceid;
1904         if (!$skipcriteria) {
1905             $params = array(
1906                 'course'         => $data->course,
1907                 'criteriatype'   => $data->criteriatype,
1908                 'enrolperiod'    => $data->enrolperiod,
1909                 'courseinstance' => $data->courseinstance,
1910                 'module'         => $data->module,
1911                 'moduleinstance' => $data->moduleinstance,
1912                 'timeend'        => $data->timeend,
1913                 'gradepass'      => $data->gradepass,
1914                 'role'           => $data->role
1915             );
1916             $newid = $DB->insert_record('course_completion_criteria', $params);
1917             $this->set_mapping('course_completion_criteria', $data->id, $newid);
1918         }
1919     }
1921     /**
1922      * Processes course compltion criteria complete records
1923      *
1924      * @global moodle_database $DB
1925      * @param stdClass $data
1926      */
1927     public function process_course_completion_crit_compl($data) {
1928         global $DB;
1930         $data = (object)$data;
1932         // This may be empty if criteria could not be restored
1933         $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
1935         $data->course = $this->get_courseid();
1936         $data->userid = $this->get_mappingid('user', $data->userid);
1938         if (!empty($data->criteriaid) && !empty($data->userid)) {
1939             $params = array(
1940                 'userid' => $data->userid,
1941                 'course' => $data->course,
1942                 'criteriaid' => $data->criteriaid,
1943                 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1944             );
1945             if (isset($data->gradefinal)) {
1946                 $params['gradefinal'] = $data->gradefinal;
1947             }
1948             if (isset($data->unenroled)) {
1949                 $params['unenroled'] = $data->unenroled;
1950             }
1951             if (isset($data->deleted)) {
1952                 $params['deleted'] = $data->deleted;
1953             }
1954             $DB->insert_record('course_completion_crit_compl', $params);
1955         }
1956     }
1958     /**
1959      * Process course completions
1960      *
1961      * @global moodle_database $DB
1962      * @param stdClass $data
1963      */
1964     public function process_course_completions($data) {
1965         global $DB;
1967         $data = (object)$data;
1969         $data->course = $this->get_courseid();
1970         $data->userid = $this->get_mappingid('user', $data->userid);
1972         if (!empty($data->userid)) {
1973             $params = array(
1974                 'userid' => $data->userid,
1975                 'course' => $data->course,
1976                 'deleted' => $data->deleted,
1977                 'timenotified' => $this->apply_date_offset($data->timenotified),
1978                 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1979                 'timestarted' => $this->apply_date_offset($data->timestarted),
1980                 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1981                 'reaggregate' => $data->reaggregate
1982             );
1983             $DB->insert_record('course_completions', $params);
1984         }
1985     }
1987     /**
1988      * Process course completion notification records.
1989      *
1990      * Note: As of Moodle 2.0 this table is not being used however it has been
1991      * left in in the hopes that one day the functionality there will be completed
1992      *
1993      * @global moodle_database $DB
1994      * @param stdClass $data
1995      */
1996     public function process_course_completion_notify($data) {
1997         global $DB;
1999         $data = (object)$data;
2001         $data->course = $this->get_courseid();
2002         if (!empty($data->role)) {
2003             $data->role = $this->get_mappingid('role', $data->role);
2004         }
2006         $params = array(
2007             'course' => $data->course,
2008             'role' => $data->role,
2009             'message' => $data->message,
2010             'timesent' => $this->apply_date_offset($data->timesent),
2011         );
2012         $DB->insert_record('course_completion_notify', $params);
2013     }
2015     /**
2016      * Process course completion aggregate methods
2017      *
2018      * @global moodle_database $DB
2019      * @param stdClass $data
2020      */
2021     public function process_course_completion_aggr_methd($data) {
2022         global $DB;
2024         $data = (object)$data;
2026         $data->course = $this->get_courseid();
2028         // Only create the course_completion_aggr_methd records if
2029         // the target course has not them defined. MDL-28180
2030         if (!$DB->record_exists('course_completion_aggr_methd', array(
2031                     'course' => $data->course,
2032                     'criteriatype' => $data->criteriatype))) {
2033             $params = array(
2034                 'course' => $data->course,
2035                 'criteriatype' => $data->criteriatype,
2036                 'method' => $data->method,
2037                 'value' => $data->value,
2038             );
2039             $DB->insert_record('course_completion_aggr_methd', $params);
2040         }
2041     }
2045 /**
2046  * This structure step restores course logs (cmid = 0), delegating
2047  * the hard work to the corresponding {@link restore_logs_processor} passing the
2048  * collection of {@link restore_log_rule} rules to be observed as they are defined
2049  * by the task. Note this is only executed based in the 'logs' setting.
2050  *
2051  * NOTE: This is executed by final task, to have all the activities already restored
2052  *
2053  * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2054  * records are. There are others like 'calendar' and 'upload' that will be handled
2055  * later.
2056  *
2057  * NOTE: All the missing actions (not able to be restored) are sent to logs for
2058  * debugging purposes
2059  */
2060 class restore_course_logs_structure_step extends restore_structure_step {
2062     /**
2063      * Conditionally decide if this step should be executed.
2064      *
2065      * This function checks the following parameter:
2066      *
2067      *   1. the course/logs.xml file exists
2068      *
2069      * @return bool true is safe to execute, false otherwise
2070      */
2071     protected function execute_condition() {
2073         // Check it is included in the backup
2074         $fullpath = $this->task->get_taskbasepath();
2075         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2076         if (!file_exists($fullpath)) {
2077             // Not found, can't restore course logs
2078             return false;
2079         }
2081         return true;
2082     }
2084     protected function define_structure() {
2086         $paths = array();
2088         // Simple, one plain level of information contains them
2089         $paths[] = new restore_path_element('log', '/logs/log');
2091         return $paths;
2092     }
2094     protected function process_log($data) {
2095         global $DB;
2097         $data = (object)($data);
2099         $data->time = $this->apply_date_offset($data->time);
2100         $data->userid = $this->get_mappingid('user', $data->userid);
2101         $data->course = $this->get_courseid();
2102         $data->cmid = 0;
2104         // For any reason user wasn't remapped ok, stop processing this
2105         if (empty($data->userid)) {
2106             return;
2107         }
2109         // Everything ready, let's delegate to the restore_logs_processor
2111         // Set some fixed values that will save tons of DB requests
2112         $values = array(
2113             'course' => $this->get_courseid());
2114         // Get instance and process log record
2115         $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2117         // If we have data, insert it, else something went wrong in the restore_logs_processor
2118         if ($data) {
2119             $DB->insert_record('log', $data);
2120         }
2121     }
2124 /**
2125  * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2126  * sharing its same structure but modifying the way records are handled
2127  */
2128 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2130     protected function process_log($data) {
2131         global $DB;
2133         $data = (object)($data);
2135         $data->time = $this->apply_date_offset($data->time);
2136         $data->userid = $this->get_mappingid('user', $data->userid);
2137         $data->course = $this->get_courseid();
2138         $data->cmid = $this->task->get_moduleid();
2140         // For any reason user wasn't remapped ok, stop processing this
2141         if (empty($data->userid)) {
2142             return;
2143         }
2145         // Everything ready, let's delegate to the restore_logs_processor
2147         // Set some fixed values that will save tons of DB requests
2148         $values = array(
2149             'course' => $this->get_courseid(),
2150             'course_module' => $this->task->get_moduleid(),
2151             $this->task->get_modulename() => $this->task->get_activityid());
2152         // Get instance and process log record
2153         $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2155         // If we have data, insert it, else something went wrong in the restore_logs_processor
2156         if ($data) {
2157             $DB->insert_record('log', $data);
2158         }
2159     }
2163 /**
2164  * Defines the restore step for advanced grading methods attached to the activity module
2165  */
2166 class restore_activity_grading_structure_step extends restore_structure_step {
2168     /**
2169      * This step is executed only if the grading file is present
2170      */
2171      protected function execute_condition() {
2173         $fullpath = $this->task->get_taskbasepath();
2174         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2175         if (!file_exists($fullpath)) {
2176             return false;
2177         }
2179         return true;
2180     }
2183     /**
2184      * Declares paths in the grading.xml file we are interested in
2185      */
2186     protected function define_structure() {
2188         $paths = array();
2189         $userinfo = $this->get_setting_value('userinfo');
2191         $paths[] = new restore_path_element('grading_area', '/areas/area');
2193         $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
2194         $paths[] = $definition;
2195         $this->add_plugin_structure('gradingform', $definition);
2197         if ($userinfo) {
2198             $instance = new restore_path_element('grading_instance',
2199                 '/areas/area/definitions/definition/instances/instance');
2200             $paths[] = $instance;
2201             $this->add_plugin_structure('gradingform', $instance);
2202         }
2204         return $paths;
2205     }
2207     /**
2208      * Processes one grading area element
2209      *
2210      * @param array $data element data
2211      */
2212     protected function process_grading_area($data) {
2213         global $DB;
2215         $task = $this->get_task();
2216         $data = (object)$data;
2217         $oldid = $data->id;
2218         $data->component = 'mod_'.$task->get_modulename();
2219         $data->contextid = $task->get_contextid();
2221         $newid = $DB->insert_record('grading_areas', $data);
2222         $this->set_mapping('grading_area', $oldid, $newid);
2223     }
2225     /**
2226      * Processes one grading definition element
2227      *
2228      * @param array $data element data
2229      */
2230     protected function process_grading_definition($data) {
2231         global $DB;
2233         $task = $this->get_task();
2234         $data = (object)$data;
2235         $oldid = $data->id;
2236         $data->areaid = $this->get_new_parentid('grading_area');
2237         $data->copiedfromid = null;
2238         $data->timecreated = time();
2239         $data->usercreated = $task->get_userid();
2240         $data->timemodified = $data->timecreated;
2241         $data->usermodified = $data->usercreated;
2243         $newid = $DB->insert_record('grading_definitions', $data);
2244         $this->set_mapping('grading_definition', $oldid, $newid, true);
2245     }
2247     /**
2248      * Processes one grading form instance element
2249      *
2250      * @param array $data element data
2251      */
2252     protected function process_grading_instance($data) {
2253         global $DB;
2255         $data = (object)$data;
2257         // new form definition id
2258         $newformid = $this->get_new_parentid('grading_definition');
2260         // get the name of the area we are restoring to
2261         $sql = "SELECT ga.areaname
2262                   FROM {grading_definitions} gd
2263                   JOIN {grading_areas} ga ON gd.areaid = ga.id
2264                  WHERE gd.id = ?";
2265         $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
2267         // get the mapped itemid - the activity module is expected to define the mappings
2268         // for each gradable area
2269         $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
2271         $oldid = $data->id;
2272         $data->definitionid = $newformid;
2273         $data->raterid = $this->get_mappingid('user', $data->raterid);
2274         $data->itemid = $newitemid;
2276         $newid = $DB->insert_record('grading_instances', $data);
2277         $this->set_mapping('grading_instance', $oldid, $newid);
2278     }
2280     /**
2281      * Final operations when the database records are inserted
2282      */
2283     protected function after_execute() {
2284         // Add files embedded into the definition description
2285         $this->add_related_files('grading', 'description', 'grading_definition');
2286     }
2290 /**
2291  * This structure step restores the grade items associated with one activity
2292  * All the grade items are made child of the "course" grade item but the original
2293  * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
2294  * the complete gradebook (categories and calculations), that information is
2295  * available there
2296  */
2297 class restore_activity_grades_structure_step extends restore_structure_step {
2299     protected function define_structure() {
2301         $paths = array();
2302         $userinfo = $this->get_setting_value('userinfo');
2304         $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
2305         $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
2306         if ($userinfo) {
2307             $paths[] = new restore_path_element('grade_grade',
2308                            '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
2309         }
2310         return $paths;
2311     }
2313     protected function process_grade_item($data) {
2314         global $DB;
2316         $data = (object)($data);
2317         $oldid       = $data->id;        // We'll need these later
2318         $oldparentid = $data->categoryid;
2319         $courseid = $this->get_courseid();
2321         // make sure top course category exists, all grade items will be associated
2322         // to it. Later, if restoring the whole gradebook, categories will be introduced
2323         $coursecat = grade_category::fetch_course_category($courseid);
2324         $coursecatid = $coursecat->id; // Get the categoryid to be used
2326         $idnumber = null;
2327         if (!empty($data->idnumber)) {
2328             // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
2329             // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
2330             // so the best is to keep the ones already in the gradebook
2331             // Potential problem: duplicates if same items are restored more than once. :-(
2332             // This needs to be fixed in some way (outcomes & activities with multiple items)
2333             // $data->idnumber     = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
2334             // In any case, verify always for uniqueness
2335             $sql = "SELECT cm.id
2336                       FROM {course_modules} cm
2337                      WHERE cm.course = :courseid AND
2338                            cm.idnumber = :idnumber AND
2339                            cm.id <> :cmid";
2340             $params = array(
2341                 'courseid' => $courseid,
2342                 'idnumber' => $data->idnumber,
2343                 'cmid' => $this->task->get_moduleid()
2344             );
2345             if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
2346                 $idnumber = $data->idnumber;
2347             }
2348         }
2350         unset($data->id);
2351         $data->categoryid   = $coursecatid;
2352         $data->courseid     = $this->get_courseid();
2353         $data->iteminstance = $this->task->get_activityid();
2354         $data->idnumber     = $idnumber;
2355         $data->scaleid      = $this->get_mappingid('scale', $data->scaleid);
2356         $data->outcomeid    = $this->get_mappingid('outcome', $data->outcomeid);
2357         $data->timecreated  = $this->apply_date_offset($data->timecreated);
2358         $data->timemodified = $this->apply_date_offset($data->timemodified);
2360         $gradeitem = new grade_item($data, false);
2361         $gradeitem->insert('restore');
2363         //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
2364         $gradeitem->sortorder = $data->sortorder;
2365         $gradeitem->update('restore');
2367         // Set mapping, saving the original category id into parentitemid
2368         // gradebook restore (final task) will need it to reorganise items
2369         $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
2370     }
2372     protected function process_grade_grade($data) {
2373         $data = (object)($data);
2374         $olduserid = $data->userid;
2375         unset($data->id);
2377         $data->itemid = $this->get_new_parentid('grade_item');
2379         $data->userid = $this->get_mappingid('user', $data->userid, null);
2380         if (!empty($data->userid)) {
2381             $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
2382             $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
2383             // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
2384             $data->overridden = $this->apply_date_offset($data->overridden);
2386             $grade = new grade_grade($data, false);
2387             $grade->insert('restore');
2388             // no need to save any grade_grade mapping
2389         } else {
2390             debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
2391         }
2392     }
2394     /**
2395      * process activity grade_letters. Note that, while these are possible,
2396      * because grade_letters are contextid based, in proctice, only course
2397      * context letters can be defined. So we keep here this method knowing
2398      * it won't be executed ever. gradebook restore will restore course letters.
2399      */
2400     protected function process_grade_letter($data) {
2401         global $DB;
2403         $data = (object)$data;
2405         $data->contextid = $this->task->get_contextid();
2406         $newitemid = $DB->insert_record('grade_letters', $data);
2407         // no need to save any grade_letter mapping
2408     }
2412 /**
2413  * This structure steps restores one instance + positions of one block
2414  * Note: Positions corresponding to one existing context are restored
2415  * here, but all the ones having unknown contexts are sent to backup_ids
2416  * for a later chance to be restored at the end (final task)
2417  */
2418 class restore_block_instance_structure_step extends restore_structure_step {
2420     protected function define_structure() {
2422         $paths = array();
2424         $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
2425         $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
2427         return $paths;
2428     }
2430     public function process_block($data) {
2431         global $DB, $CFG;
2433         $data = (object)$data; // Handy
2434         $oldcontextid = $data->contextid;
2435         $oldid        = $data->id;
2436         $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
2438         // Look for the parent contextid
2439         if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
2440             throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
2441         }
2443         // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
2444         // If there is already one block of that type in the parent context
2445         // and the block is not multiple, stop processing
2446         // Use blockslib loader / method executor
2447         if (!$bi = block_instance($data->blockname)) {
2448             return false;
2449         }
2451         if (!$bi->instance_allow_multiple()) {
2452             if ($DB->record_exists_sql("SELECT bi.id
2453                                           FROM {block_instances} bi
2454                                           JOIN {block} b ON b.name = bi.blockname
2455                                          WHERE bi.parentcontextid = ?
2456                                            AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
2457                 return false;
2458             }
2459         }
2461         // If there is already one block of that type in the parent context
2462         // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
2463         // stop processing
2464         $params = array(
2465             'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
2466             'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
2467             'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
2468         if ($birecs = $DB->get_records('block_instances', $params)) {
2469             foreach($birecs as $birec) {
2470                 if ($birec->configdata == $data->configdata) {
2471                     return false;
2472                 }
2473             }
2474         }
2476         // Set task old contextid, blockid and blockname once we know them
2477         $this->task->set_old_contextid($oldcontextid);
2478         $this->task->set_old_blockid($oldid);
2479         $this->task->set_blockname($data->blockname);
2481         // Let's look for anything within configdata neededing processing
2482         // (nulls and uses of legacy file.php)
2483         if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
2484             $configdata = (array)unserialize(base64_decode($data->configdata));
2485             foreach ($configdata as $attribute => $value) {
2486                 if (in_array($attribute, $attrstotransform)) {
2487                     $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
2488                 }
2489             }
2490             $data->configdata = base64_encode(serialize((object)$configdata));
2491         }
2493         // Create the block instance
2494         $newitemid = $DB->insert_record('block_instances', $data);
2495         // Save the mapping (with restorefiles support)
2496         $this->set_mapping('block_instance', $oldid, $newitemid, true);
2497         // Create the block context
2498         $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
2499         // Save the block contexts mapping and sent it to task
2500         $this->set_mapping('context', $oldcontextid, $newcontextid);
2501         $this->task->set_contextid($newcontextid);
2502         $this->task->set_blockid($newitemid);
2504         // Restore block fileareas if declared
2505         $component = 'block_' . $this->task->get_blockname();
2506         foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
2507             $this->add_related_files($component, $filearea, null);
2508         }
2510         // Process block positions, creating them or accumulating for final step
2511         foreach($positions as $position) {
2512             $position = (object)$position;
2513             $position->blockinstanceid = $newitemid; // The instance is always the restored one
2514             // If position is for one already mapped (known) contextid
2515             // process it now, creating the position
2516             if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
2517                 $position->contextid = $newpositionctxid;
2518                 // Create the block position
2519                 $DB->insert_record('block_positions', $position);
2521             // The position belongs to an unknown context, send it to backup_ids
2522             // to process them as part of the final steps of restore. We send the
2523             // whole $position object there, hence use the low level method.
2524             } else {
2525                 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
2526             }
2527         }
2528     }
2531 /**
2532  * Structure step to restore common course_module information
2533  *
2534  * This step will process the module.xml file for one activity, in order to restore
2535  * the corresponding information to the course_modules table, skipping various bits
2536  * of information based on CFG settings (groupings, completion...) in order to fullfill
2537  * all the reqs to be able to create the context to be used by all the rest of steps
2538  * in the activity restore task
2539  */
2540 class restore_module_structure_step extends restore_structure_step {
2542     protected function define_structure() {
2543         global $CFG;
2545         $paths = array();
2547         $module = new restore_path_element('module', '/module');
2548         $paths[] = $module;
2549         if ($CFG->enableavailability) {
2550             $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
2551         }
2553         // Apply for 'format' plugins optional paths at module level
2554         $this->add_plugin_structure('format', $module);
2556         // Apply for 'plagiarism' plugins optional paths at module level
2557         $this->add_plugin_structure('plagiarism', $module);
2559         return $paths;
2560     }
2562     protected function process_module($data) {
2563         global $CFG, $DB;
2565         $data = (object)$data;
2566         $oldid = $data->id;
2567         $this->task->set_old_moduleversion($data->version);
2569         $data->course = $this->task->get_courseid();
2570         $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
2571         // Map section (first try by course_section mapping match. Useful in course and section restores)
2572         $data->section = $this->get_mappingid('course_section', $data->sectionid);
2573         if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
2574             $params = array(
2575                 'course' => $this->get_courseid(),
2576                 'section' => $data->sectionnumber);
2577             $data->section = $DB->get_field('course_sections', 'id', $params);
2578         }
2579         if (!$data->section) { // sectionnumber failed, try to get first section in course
2580             $params = array(
2581                 'course' => $this->get_courseid());
2582             $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
2583         }
2584         if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
2585             $sectionrec = array(
2586                 'course' => $this->get_courseid(),
2587                 'section' => 0);
2588             $DB->insert_record('course_sections', $sectionrec); // section 0
2589             $sectionrec = array(
2590                 'course' => $this->get_courseid(),
2591                 'section' => 1);
2592             $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
2593         }
2594         $data->groupingid= $this->get_mappingid('grouping', $data->groupingid);      // grouping
2595         if (!$CFG->enablegroupmembersonly) {                                         // observe groupsmemberonly
2596             $data->groupmembersonly = 0;
2597         }
2598         if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) {        // idnumber uniqueness
2599             $data->idnumber = '';
2600         }
2601         if (empty($CFG->enablecompletion)) { // completion
2602             $data->completion = 0;
2603             $data->completiongradeitemnumber = null;
2604             $data->completionview = 0;
2605             $data->completionexpected = 0;
2606         } else {
2607             $data->completionexpected = $this->apply_date_offset($data->completionexpected);
2608         }
2609         if (empty($CFG->enableavailability)) {
2610             $data->availablefrom = 0;
2611             $data->availableuntil = 0;
2612             $data->showavailability = 0;
2613         } else {
2614             $data->availablefrom = $this->apply_date_offset($data->availablefrom);
2615             $data->availableuntil= $this->apply_date_offset($data->availableuntil);
2616         }
2617         // Backups that did not include showdescription, set it to default 0
2618         // (this is not totally necessary as it has a db default, but just to
2619         // be explicit).
2620         if (!isset($data->showdescription)) {
2621             $data->showdescription = 0;
2622         }
2623         $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
2625         // course_module record ready, insert it
2626         $newitemid = $DB->insert_record('course_modules', $data);
2627         // save mapping
2628         $this->set_mapping('course_module', $oldid, $newitemid);
2629         // set the new course_module id in the task
2630         $this->task->set_moduleid($newitemid);
2631         // we can now create the context safely
2632         $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
2633         // set the new context id in the task
2634         $this->task->set_contextid($ctxid);
2635         // update sequence field in course_section
2636         if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
2637             $sequence .= ',' . $newitemid;
2638         } else {
2639             $sequence = $newitemid;
2640         }
2641         $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
2642     }
2645     protected function process_availability($data) {
2646         $data = (object)$data;
2647         // Simply going to store the whole availability record now, we'll process
2648         // all them later in the final task (once all actvivities have been restored)
2649         // Let's call the low level one to be able to store the whole object
2650         $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
2651         restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
2652     }
2655 /**
2656  * Structure step that will process the user activity completion
2657  * information if all these conditions are met:
2658  *  - Target site has completion enabled ($CFG->enablecompletion)
2659  *  - Activity includes completion info (file_exists)
2660  */
2661 class restore_userscompletion_structure_step extends restore_structure_step {
2662     /**
2663      * To conditionally decide if this step must be executed
2664      * Note the "settings" conditions are evaluated in the
2665      * corresponding task. Here we check for other conditions
2666      * not being restore settings (files, site settings...)
2667      */
2668      protected function execute_condition() {
2669          global $CFG;
2671          // Completion disabled in this site, don't execute
2672          if (empty($CFG->enablecompletion)) {
2673              return false;
2674          }
2676          // No user completion info found, don't execute
2677         $fullpath = $this->task->get_taskbasepath();
2678         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2679          if (!file_exists($fullpath)) {
2680              return false;
2681          }
2683          // Arrived here, execute the step
2684          return true;
2685      }
2687      protected function define_structure() {
2689         $paths = array();
2691         $paths[] = new restore_path_element('completion', '/completions/completion');
2693         return $paths;
2694     }
2696     protected function process_completion($data) {
2697         global $DB;
2699         $data = (object)$data;
2701         $data->coursemoduleid = $this->task->get_moduleid();
2702         $data->userid = $this->get_mappingid('user', $data->userid);
2703         $data->timemodified = $this->apply_date_offset($data->timemodified);
2705         // Find the existing record
2706         $existing = $DB->get_record('course_modules_completion', array(
2707                 'coursemoduleid' => $data->coursemoduleid,
2708                 'userid' => $data->userid), 'id, timemodified');
2709         // Check we didn't already insert one for this cmid and userid
2710         // (there aren't supposed to be duplicates in that field, but
2711         // it was possible until MDL-28021 was fixed).
2712         if ($existing) {
2713             // Update it to these new values, but only if the time is newer
2714             if ($existing->timemodified < $data->timemodified) {
2715                 $data->id = $existing->id;
2716                 $DB->update_record('course_modules_completion', $data);
2717             }
2718         } else {
2719             // Normal entry where it doesn't exist already
2720             $DB->insert_record('course_modules_completion', $data);
2721         }
2722     }
2725 /**
2726  * Abstract structure step, parent of all the activity structure steps. Used to suuport
2727  * the main <activity ...> tag and process it. Also provides subplugin support for
2728  * activities.
2729  */
2730 abstract class restore_activity_structure_step extends restore_structure_step {
2732     protected function add_subplugin_structure($subplugintype, $element) {
2734         global $CFG;
2736         // Check the requested subplugintype is a valid one
2737         $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
2738         if (!file_exists($subpluginsfile)) {
2739              throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
2740         }
2741         include($subpluginsfile);
2742         if (!array_key_exists($subplugintype, $subplugins)) {
2743              throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
2744         }
2745         // Get all the restore path elements, looking across all the subplugin dirs
2746         $subpluginsdirs = get_plugin_list($subplugintype);
2747         foreach ($subpluginsdirs as $name => $subpluginsdir) {
2748             $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
2749             $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
2750             if (file_exists($restorefile)) {
2751                 require_once($restorefile);
2752                 $restoresubplugin = new $classname($subplugintype, $name, $this);
2753                 // Add subplugin paths to the step
2754                 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
2755             }
2756         }
2757     }
2759     /**
2760      * As far as activity restore steps are implementing restore_subplugin stuff, they need to
2761      * have the parent task available for wrapping purposes (get course/context....)
2762      * @return restore_task
2763      */
2764     public function get_task() {
2765         return $this->task;
2766     }
2768     /**
2769      * Adds support for the 'activity' path that is common to all the activities
2770      * and will be processed globally here
2771      */
2772     protected function prepare_activity_structure($paths) {
2774         $paths[] = new restore_path_element('activity', '/activity');
2776         return $paths;
2777     }
2779     /**
2780      * Process the activity path, informing the task about various ids, needed later
2781      */
2782     protected function process_activity($data) {
2783         $data = (object)$data;
2784         $this->task->set_old_contextid($data->contextid); // Save old contextid in task
2785         $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
2786         $this->task->set_old_activityid($data->id); // Save old activityid in task
2787     }
2789     /**
2790      * This must be invoked immediately after creating the "module" activity record (forum, choice...)
2791      * and will adjust the new activity id (the instance) in various places
2792      */
2793     protected function apply_activity_instance($newitemid) {
2794         global $DB;
2796         $this->task->set_activityid($newitemid); // Save activity id in task
2797         // Apply the id to course_sections->instanceid
2798         $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
2799         // Do the mapping for modulename, preparing it for files by oldcontext
2800         $modulename = $this->task->get_modulename();
2801         $oldid = $this->task->get_old_activityid();
2802         $this->set_mapping($modulename, $oldid, $newitemid, true);
2803     }
2806 /**
2807  * Structure step in charge of creating/mapping all the qcats and qs
2808  * by parsing the questions.xml file and checking it against the
2809  * results calculated by {@link restore_process_categories_and_questions}
2810  * and stored in backup_ids_temp
2811  */
2812 class restore_create_categories_and_questions extends restore_structure_step {
2814     protected function define_structure() {
2816         $category = new restore_path_element('question_category', '/question_categories/question_category');
2817         $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
2818         $hint = new restore_path_element('question_hint',
2819                 '/question_categories/question_category/questions/question/question_hints/question_hint');
2821         // Apply for 'qtype' plugins optional paths at question level
2822         $this->add_plugin_structure('qtype', $question);
2824         return array($category, $question, $hint);
2825     }
2827     protected function process_question_category($data) {
2828         global $DB;
2830         $data = (object)$data;
2831         $oldid = $data->id;
2833         // Check we have one mapping for this category
2834         if (!$mapping = $this->get_mapping('question_category', $oldid)) {
2835             return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
2836         }
2838         // Check we have to create the category (newitemid = 0)
2839         if ($mapping->newitemid) {
2840             return; // newitemid != 0, this category is going to be mapped. Nothing to do
2841         }
2843         // Arrived here, newitemid = 0, we need to create the category
2844         // we'll do it at parentitemid context, but for CONTEXT_MODULE
2845         // categories, that will be created at CONTEXT_COURSE and moved
2846         // to module context later when the activity is created
2847         if ($mapping->info->contextlevel == CONTEXT_MODULE) {
2848             $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
2849         }
2850         $data->contextid = $mapping->parentitemid;
2852         // Let's create the question_category and save mapping
2853         $newitemid = $DB->insert_record('question_categories', $data);
2854         $this->set_mapping('question_category', $oldid, $newitemid);
2855         // Also annotate them as question_category_created, we need
2856         // that later when remapping parents
2857         $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
2858     }
2860     protected function process_question($data) {
2861         global $DB;
2863         $data = (object)$data;
2864         $oldid = $data->id;
2866         // Check we have one mapping for this question
2867         if (!$questionmapping = $this->get_mapping('question', $oldid)) {
2868             return; // No mapping = this question doesn't need to be created/mapped
2869         }
2871         // Get the mapped category (cannot use get_new_parentid() because not
2872         // all the categories have been created, so it is not always available
2873         // Instead we get the mapping for the question->parentitemid because
2874         // we have loaded qcatids there for all parsed questions
2875         $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
2877         // In the past, there were some very sloppy values of penalty. Fix them.
2878         if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
2879             $data->penalty = 0.3333333;
2880         }
2881         if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
2882             $data->penalty = 0.6666667;
2883         }
2884         if ($data->penalty >= 1) {
2885             $data->penalty = 1;
2886         }
2888         $data->timecreated  = $this->apply_date_offset($data->timecreated);
2889         $data->timemodified = $this->apply_date_offset($data->timemodified);
2891         $userid = $this->get_mappingid('user', $data->createdby);
2892         $data->createdby = $userid ? $userid : $this->task->get_userid();
2894         $userid = $this->get_mappingid('user', $data->modifiedby);
2895         $data->modifiedby = $userid ? $userid : $this->task->get_userid();
2897         // With newitemid = 0, let's create the question
2898         if (!$questionmapping->newitemid) {
2899             $newitemid = $DB->insert_record('question', $data);
2900             $this->set_mapping('question', $oldid, $newitemid);
2901             // Also annotate them as question_created, we need
2902             // that later when remapping parents (keeping the old categoryid as parentid)
2903             $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
2904         } else {
2905             // By performing this set_mapping() we make get_old/new_parentid() to work for all the
2906             // children elements of the 'question' one (so qtype plugins will know the question they belong to)
2907             $this->set_mapping('question', $oldid, $questionmapping->newitemid);
2908         }
2910         // Note, we don't restore any question files yet
2911         // as far as the CONTEXT_MODULE categories still
2912         // haven't their contexts to be restored to
2913         // The {@link restore_create_question_files}, executed in the final step
2914         // step will be in charge of restoring all the question files
2915     }
2917         protected function process_question_hint($data) {
2918         global $DB;
2920         $data = (object)$data;
2921         $oldid = $data->id;
2923         // Detect if the question is created or mapped
2924         $oldquestionid   = $this->get_old_parentid('question');
2925         $newquestionid   = $this->get_new_parentid('question');
2926         $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
2928         // If the question has been created by restore, we need to create its question_answers too
2929         if ($questioncreated) {
2930             // Adjust some columns
2931             $data->questionid = $newquestionid;
2932             // Insert record
2933             $newitemid = $DB->insert_record('question_hints', $data);
2935         // The question existed, we need to map the existing question_hints
2936         } else {
2937             // Look in question_hints by hint text matching
2938             $sql = 'SELECT id
2939                       FROM {question_hints}
2940                      WHERE questionid = ?
2941                        AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
2942             $params = array($newquestionid, $data->hint);
2943             $newitemid = $DB->get_field_sql($sql, $params);
2944             // If we haven't found the newitemid, something has gone really wrong, question in DB
2945             // is missing hints, exception
2946             if (!$newitemid) {
2947                 $info = new stdClass();
2948                 $info->filequestionid = $oldquestionid;
2949                 $info->dbquestionid   = $newquestionid;
2950                 $info->hint           = $data->hint;
2951                 throw new restore_step_exception('error_question_hint_missing_in_db', $info);
2952             }
2953         }
2954         // Create mapping (I'm not sure if this is really needed?)
2955         $this->set_mapping('question_hint', $oldid, $newitemid);
2956     }
2958     protected function after_execute() {
2959         global $DB;
2961         // First of all, recode all the created question_categories->parent fields
2962         $qcats = $DB->get_records('backup_ids_temp', array(
2963                      'backupid' => $this->get_restoreid(),
2964                      'itemname' => 'question_category_created'));
2965         foreach ($qcats as $qcat) {
2966             $newparent = 0;
2967             $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
2968             // Get new parent (mapped or created, so we look in quesiton_category mappings)
2969             if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2970                                  'backupid' => $this->get_restoreid(),
2971                                  'itemname' => 'question_category',
2972                                  'itemid'   => $dbcat->parent))) {
2973                 // contextids must match always, as far as we always include complete qbanks, just check it
2974                 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
2975                 if ($dbcat->contextid == $newparentctxid) {
2976                     $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
2977                 } else {
2978                     $newparent = 0; // No ctx match for both cats, no parent relationship
2979                 }
2980             }
2981             // Here with $newparent empty, problem with contexts or remapping, set it to top cat
2982             if (!$newparent) {
2983                 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
2984             }
2985         }
2987         // Now, recode all the created question->parent fields
2988         $qs = $DB->get_records('backup_ids_temp', array(
2989                   'backupid' => $this->get_restoreid(),
2990                   'itemname' => 'question_created'));
2991         foreach ($qs as $q) {
2992             $newparent = 0;
2993             $dbq = $DB->get_record('question', array('id' => $q->newitemid));
2994             // Get new parent (mapped or created, so we look in question mappings)
2995             if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2996                                  'backupid' => $this->get_restoreid(),
2997                                  'itemname' => 'question',
2998                                  'itemid'   => $dbq->parent))) {
2999                 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
3000             }
3001         }
3003         // Note, we don't restore any question files yet
3004         // as far as the CONTEXT_MODULE categories still
3005         // haven't their contexts to be restored to
3006         // The {@link restore_create_question_files}, executed in the final step
3007         // step will be in charge of restoring all the question files
3008     }
3011 /**
3012  * Execution step that will move all the CONTEXT_MODULE question categories
3013  * created at early stages of restore in course context (because modules weren't
3014  * created yet) to their target module (matching by old-new-contextid mapping)
3015  */
3016 class restore_move_module_questions_categories extends restore_execution_step {
3018     protected function define_execution() {
3019         global $DB;
3021         $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
3022         foreach ($contexts as $contextid => $contextlevel) {
3023             // Only if context mapping exists (i.e. the module has been restored)
3024             if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
3025                 // Update all the qcats having their parentitemid set to the original contextid
3026                 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
3027                                                       FROM {backup_ids_temp}
3028                                                      WHERE backupid = ?
3029                                                        AND itemname = 'question_category'
3030                                                        AND parentitemid = ?", array($this->get_restoreid(), $contextid));
3031                 foreach ($modulecats as $modulecat) {
3032                     $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
3033                     // And set new contextid also in question_category mapping (will be
3034                     // used by {@link restore_create_question_files} later
3035                     restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
3036                 }
3037             }
3038         }
3039     }
3042 /**
3043  * Execution step that will create all the question/answers/qtype-specific files for the restored
3044  * questions. It must be executed after {@link restore_move_module_questions_categories}
3045  * because only then each question is in its final category and only then the
3046  * context can be determined
3047  *
3048  * TODO: Improve this. Instead of looping over each question, it can be reduced to
3049  *       be done by contexts (this will save a huge ammount of queries)
3050  */
3051 class restore_create_question_files extends restore_execution_step {
3053     protected function define_execution() {
3054         global $DB;
3056         // Let's process only created questions
3057         $questionsrs = $DB->get_recordset_sql("SELECT bi.itemid, bi.newitemid, bi.parentitemid, q.qtype
3058                                                FROM {backup_ids_temp} bi
3059                                                JOIN {question} q ON q.id = bi.newitemid
3060                                               WHERE bi.backupid = ?
3061                                                 AND bi.itemname = 'question_created'", array($this->get_restoreid()));
3062         foreach ($questionsrs as $question) {
3063             // Get question_category mapping, it contains the target context for the question
3064             if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $question->parentitemid)) {
3065                 // Something went really wrong, cannot find the question_category for the question
3066                 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
3067                 continue;
3068             }
3069             // Calculate source and target contexts
3070             $oldctxid = $qcatmapping->info->contextid;
3071             $newctxid = $qcatmapping->parentitemid;
3073             // Add common question files (question and question_answer ones)
3074             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
3075                                               $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3076             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
3077                                               $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3078             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
3079                                               $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
3080             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
3081                                               $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
3082             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
3083                                               $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true);
3084             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
3085                                               $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3086             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
3087                                               $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3088             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
3089                                               $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
3090             // Add qtype dependent files
3091             $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
3092             foreach ($components as $component => $fileareas) {
3093                 foreach ($fileareas as $filearea => $mapping) {
3094                     // Use itemid only if mapping is question_created
3095                     $itemid = ($mapping == 'question_created') ? $question->itemid : null;
3096                     restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
3097                                                       $oldctxid, $this->task->get_userid(), $mapping, $itemid, $newctxid, true);
3098                 }
3099             }
3100         }
3101         $questionsrs->close();
3102     }
3105 /**
3106  * Abstract structure step, to be used by all the activities using core questions stuff
3107  * (like the quiz module), to support qtype plugins, states and sessions
3108  */
3109 abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
3110     /** @var array question_attempt->id to qtype. */
3111     protected $qtypes = array();
3112     /** @var array question_attempt->id to questionid. */
3113     protected $newquestionids = array();
3115     /**
3116      * Attach below $element (usually attempts) the needed restore_path_elements
3117      * to restore question_usages and all they contain.
3118      */
3119     protected function add_question_usages($element, &$paths) {
3120         // Check $element is restore_path_element
3121         if (! $element instanceof restore_path_element) {
3122             throw new restore_step_exception('element_must_be_restore_path_element', $element);
3123         }
3124         // Check $paths is one array
3125         if (!is_array($paths)) {
3126             throw new restore_step_exception('paths_must_be_array', $paths);
3127         }
3128         $paths[] = new restore_path_element('question_usage',
3129                 $element->get_path() . '/question_usage');
3130         $paths[] = new restore_path_element('question_attempt',
3131                 $element->get_path() . '/question_usage/question_attempts/question_attempt');
3132         $paths[] = new restore_path_element('question_attempt_step',
3133                 $element->get_path() . '/question_usage/question_attempts/question_attempt/steps/step',
3134                 true);
3135         $paths[] = new restore_path_element('question_attempt_step_data',
3136                 $element->get_path() . '/question_usage/question_attempts/question_attempt/steps/step/response/variable');
3137     }
3139     /**
3140      * Process question_usages
3141      */
3142     protected function process_question_usage($data) {
3143         global $DB;
3145         // Clear our caches.
3146         $this->qtypes = array();
3147         $this->newquestionids = array();
3149         $data = (object)$data;
3150         $oldid = $data->id;
3152         $oldcontextid = $this->get_task()->get_old_contextid();
3153         $data->contextid  = $this->get_mappingid('context', $this->task->get_old_contextid());
3155         // Everything ready, insert (no mapping needed)
3156         $newitemid = $DB->insert_record('question_usages', $data);
3158         $this->inform_new_usage_id($newitemid);
3160         $this->set_mapping('question_usage', $oldid, $newitemid, false);
3161     }
3163     /**
3164      * When process_question_usage creates the new usage, it calls this method
3165      * to let the activity link to the new usage. For example, the quiz uses
3166      * this method to set quiz_attempts.uniqueid to the new usage id.
3167      * @param integer $newusageid
3168      */
3169     abstract protected function inform_new_usage_id($newusageid);
3171     /**
3172      * Process question_attempts
3173      */
3174     protected function process_question_attempt($data) {
3175         global $DB;
3177         $data = (object)$data;
3178         $oldid = $data->id;
3179         $question = $this->get_mapping('question', $data->questionid);
3181         $data->questionusageid = $this->get_new_parentid('question_usage');
3182         $data->questionid      = $question->newitemid;
3183         $data->timemodified    = $this->apply_date_offset($data->timemodified);
3185         $newitemid = $DB->insert_record('question_attempts', $data);
3187         $this->set_mapping('question_attempt', $oldid, $newitemid);
3188         $this->qtypes[$newitemid] = $question->info->qtype;
3189         $this->newquestionids[$newitemid] = $data->questionid;
3190     }
3192     /**
3193      * Process question_attempt_steps
3194      */
3195     protected function process_question_attempt_step($data) {
3196         global $DB;
3198         $data = (object)$data;
3199         $oldid = $data->id;
3201         // Pull out the response data.
3202         $response = array();
3203         if (!empty($data->response['variable'])) {
3204             foreach ($data->response['variable'] as $variable) {
3205                 $response[$variable['name']] = $variable['value'];
3206             }
3207         }
3208         unset($data->response);
3210         $data->questionattemptid = $this->get_new_parentid('question_attempt');
3211         $data->timecreated = $this->apply_date_offset($data->timecreated);
3212         $data->userid      = $this->get_mappingid('user', $data->userid);
3214         // Everything ready, insert and create mapping (needed by question_sessions)
3215         $newitemid = $DB->insert_record('question_attempt_steps', $data);
3216         $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
3218         // Now process the response data.
3219         $response = $this->questions_recode_response_data(
3220                 $this->qtypes[$data->questionattemptid],
3221                 $this->newquestionids[$data->questionattemptid],
3222                 $data->sequencenumber, $response);
3223         foreach ($response as $name => $value) {
3224             $row = new stdClass();
3225             $row->attemptstepid = $newitemid;
3226             $row->name = $name;
3227             $row->value = $value;
3228             $DB->insert_record('question_attempt_step_data', $row, false);
3229         }
3230     }
3232     /**
3233      * Recode the respones data for a particular step of an attempt at at particular question.
3234      * @param string $qtype the question type.
3235      * @param int $newquestionid the question id.
3236      * @param int $sequencenumber the sequence number.
3237      * @param array $response the response data to recode.
3238      */
3239     public function questions_recode_response_data(
3240             $qtype, $newquestionid, $sequencenumber, array $response) {
3241         $qtyperestorer = $this->get_qtype_restorer($qtype);
3242         if ($qtyperestorer) {
3243             $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
3244         }
3245         return $response;
3246     }
3248     /**
3249      * Given a list of question->ids, separated by commas, returns the
3250      * recoded list, with all the restore question mappings applied.
3251      * Note: Used by quiz->questions and quiz_attempts->layout
3252      * Note: 0 = page break (unconverted)
3253      */
3254     protected function questions_recode_layout($layout) {
3255         // Extracts question id from sequence
3256         if ($questionids = explode(',', $layout)) {
3257             foreach ($questionids as $id => $questionid) {
3258                 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
3259                     $newquestionid = $this->get_mappingid('question', $questionid);
3260                     $questionids[$id] = $newquestionid;
3261                 }
3262             }
3263         }
3264         return implode(',', $questionids);
3265     }
3267     /**
3268      * Get the restore_qtype_plugin subclass for a specific question type.
3269      * @param string $qtype e.g. multichoice.
3270      * @return restore_qtype_plugin instance.
3271      */
3272     protected function get_qtype_restorer($qtype) {
3273         // Build one static cache to store {@link restore_qtype_plugin}
3274         // while we are needing them, just to save zillions of instantiations
3275         // or using static stuff that will break our nice API
3276         static $qtypeplugins = array();
3278         if (!isset($qtypeplugins[$qtype])) {
3279             $classname = 'restore_qtype_' . $qtype . '_plugin';
3280             if (class_exists($classname)) {
3281                 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
3282             } else {
3283                 $qtypeplugins[$qtype] = null;
3284             }
3285         }
3286         return $qtypeplugins[$qtype];
3287     }
3289     protected function after_execute() {
3290         parent::after_execute();
3292         // Restore any files belonging to responses.
3293         foreach (question_engine::get_all_response_file_areas() as $filearea) {
3294             $this->add_related_files('question', $filearea, 'question_attempt_step');
3295         }
3296     }
3298     /**
3299      * Attach below $element (usually attempts) the needed restore_path_elements
3300      * to restore question attempt data from Moodle 2.0.
3301      *
3302      * When using this method, the parent element ($element) must be defined with
3303      * $grouped = true. Then, in that elements process method, you must call
3304      * {@link process_legacy_attempt_data()} with the groupded data. See, for
3305      * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
3306      * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
3307      * @param array $paths the paths array that is being built to describe the
3308      *      structure.
3309      */
3310     protected function add_legacy_question_attempt_data($element, &$paths) {
3311         global $CFG;
3312         require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
3314         // Check $element is restore_path_element
3315         if (!($element instanceof restore_path_element)) {
3316             throw new restore_step_exception('element_must_be_restore_path_element', $element);
3317         }
3318         // Check $paths is one array
3319         if (!is_array($paths)) {
3320             throw new restore_step_exception('paths_must_be_array', $paths);
3321         }
3323         $paths[] = new restore_path_element('question_state',
3324                 $element->get_path() . '/states/state');
3325         $paths[] = new restore_path_element('question_session',
3326                 $element->get_path() . '/sessions/session');
3327     }
3329     protected function get_attempt_upgrader() {
3330         if (empty($this->attemptupgrader)) {
3331             $this->attemptupgrader = new question_engine_attempt_upgrader();
3332             $this->attemptupgrader->prepare_to_restore();
3333         }
3334         return $this->attemptupgrader;
3335     }
3337     /**
3338      * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
3339      * @param object $data contains all the grouped attempt data ot process.
3340      * @param pbject $quiz data about the activity the attempts belong to. Required
3341      * fields are (basically this only works for the quiz module):
3342      *      oldquestions => list of question ids in this activity - using old ids.
3343      *      preferredbehaviour => the behaviour to use for questionattempts.
3344      */
3345     protected function process_legacy_quiz_attempt_data($data, $quiz) {
3346         global $DB;
3347         $upgrader = $this->get_attempt_upgrader();
3349         $data = (object)$data;
3351         $layout = explode(',', $data->layout);
3352         $newlayout = $layout;
3354         // Convert each old question_session into a question_attempt.
3355         $qas = array();
3356         foreach (explode(',', $quiz->oldquestions) as $questionid) {
3357             if ($questionid == 0) {
3358                 continue;
3359             }
3361             $newquestionid = $this->get_mappingid('question', $questionid);
3362             if (!$newquestionid) {
3363                 throw new restore_step_exception('questionattemptreferstomissingquestion',
3364                         $questionid, $questionid);
3365             }
3367             $question = $upgrader->load_question($newquestionid, $quiz->id);
3369             foreach ($layout as $key => $qid) {
3370                 if ($qid == $questionid) {
3371                     $newlayout[$key] = $newquestionid;
3372                 }
3373             }
3375             list($qsession, $qstates) = $this->find_question_session_and_states(
3376                     $data, $questionid);
3378             if (empty($qsession) || empty($qstates)) {
3379                 throw new restore_step_exception('questionattemptdatamissing',
3380                         $questionid, $questionid);
3381             }
3383             list($qsession, $qstates) = $this->recode_legacy_response_data(
3384                     $question, $qsession, $qstates);
3386             $data->layout = implode(',', $newlayout);
3387             $qas[$newquestionid] = $upgrader->convert_question_attempt(
3388                     $quiz, $data, $question, $qsession, $qstates);
3389         }
3391         // Now create a new question_usage.
3392         $usage = new stdClass();
3393         $usage->component = 'mod_quiz';
3394         $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
3395         $usage->preferredbehaviour = $quiz->preferredbehaviour;
3396         $usage->id = $DB->insert_record('question_usages', $usage);
3398         $this->inform_new_usage_id($usage->id);
3400         $data->uniqueid = $usage->id;
3401         $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas, $quiz->questions);
3402     }
3404     protected function find_question_session_and_states($data, $questionid) {
3405         $qsession = null;
3406         foreach ($data->sessions['session'] as $session) {
3407             if ($session['questionid'] == $questionid) {
3408                 $qsession = (object) $session;
3409                 break;
3410             }
3411         }
3413         $qstates = array();
3414         foreach ($data->states['state'] as $state) {
3415             if ($state['question'] == $questionid) {
3416                 // It would be natural to use $state['seq_number'] as the array-key
3417                 // here, but it seems that buggy behaviour in 2.0 and early can
3418                 // mean that that is not unique, so we use id, which is guaranteed
3419                 // to be unique.
3420                 $qstates[$state['id']] = (object) $state;
3421             }
3422         }
3423         ksort($qstates);
3424         $qstates = array_values($qstates);
3426         return array($qsession, $qstates);
3427     }
3429     /**
3430      * Recode any ids in the response data
3431      * @param object $question the question data
3432      * @param object $qsession the question sessions.
3433      * @param array $qstates the question states.
3434      */
3435     protected function recode_legacy_response_data($question, $qsession, $qstates) {
3436         $qsession->questionid = $question->id;
3438         foreach ($qstates as &$state) {
3439             $state->question = $question->id;
3440             $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
3441         }
3443         return array($qsession, $qstates);
3444     }
3446     /**
3447      * Recode the legacy answer field.
3448      * @param object $state the state to recode the answer of.
3449      * @param string $qtype the question type.
3450      */
3451     public function restore_recode_legacy_answer($state, $qtype) {
3452         $restorer = $this->get_qtype_restorer($qtype);
3453         if ($restorer) {
3454             return $restorer->recode_legacy_state_answer($state);
3455         } else {
3456             return $state->answer;
3457         }
3458     }