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