MDL-41380 backup: Fix incorrect function name from MDL-40618.
[moodle.git] / backup / moodle2 / restore_stepslib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Defines various restore steps that will be used by common tasks in restore
20  *
21  * @package     core_backup
22  * @subpackage  moodle2
23  * @category    backup
24  * @copyright   2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
25  * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 defined('MOODLE_INTERNAL') || die();
30 /**
31  * delete old directories and conditionally create backup_temp_ids table
32  */
33 class restore_create_and_clean_temp_stuff extends restore_execution_step {
35     protected function define_execution() {
36         $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
37         // If the table already exists, it's because restore_prechecks have been executed in the same
38         // request (without problems) and it already contains a bunch of preloaded information (users...)
39         // that we aren't going to execute again
40         if ($exists) { // Inform plan about preloaded information
41             $this->task->set_preloaded_information();
42         }
43         // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
44         $itemid = $this->task->get_old_contextid();
45         $newitemid = context_course::instance($this->get_courseid())->id;
46         restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
47         // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
48         $itemid = $this->task->get_old_system_contextid();
49         $newitemid = context_system::instance()->id;
50         restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
51         // Create the old-course-id to new-course-id mapping, we need that available since the beginning
52         $itemid = $this->task->get_old_courseid();
53         $newitemid = $this->get_courseid();
54         restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
56     }
57 }
59 /**
60  * delete the temp dir used by backup/restore (conditionally),
61  * delete old directories and drop temp ids table
62  */
63 class restore_drop_and_clean_temp_stuff extends restore_execution_step {
65     protected function define_execution() {
66         global $CFG;
67         restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
68         backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60));              // Delete > 4 hours temp dirs
69         if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
70             backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
71         }
72     }
73 }
75 /**
76  * Restore calculated grade items, grade categories etc
77  */
78 class restore_gradebook_structure_step extends restore_structure_step {
80     /**
81      * To conditionally decide if this step must be executed
82      * Note the "settings" conditions are evaluated in the
83      * corresponding task. Here we check for other conditions
84      * not being restore settings (files, site settings...)
85      */
86      protected function execute_condition() {
87         global $CFG, $DB;
89         // No gradebook info found, don't execute
90         $fullpath = $this->task->get_taskbasepath();
91         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
92         if (!file_exists($fullpath)) {
93             return false;
94         }
96         // Some module present in backup file isn't available to restore
97         // in this site, don't execute
98         if ($this->task->is_missing_modules()) {
99             return false;
100         }
102         // Some activity has been excluded to be restored, don't execute
103         if ($this->task->is_excluding_activities()) {
104             return false;
105         }
107         // There should only be one grade category (the 1 associated with the course itself)
108         // If other categories already exist we're restoring into an existing course.
109         // Restoring categories into a course with an existing category structure is unlikely to go well
110         $category = new stdclass();
111         $category->courseid  = $this->get_courseid();
112         $catcount = $DB->count_records('grade_categories', (array)$category);
113         if ($catcount>1) {
114             return false;
115         }
117         // Arrived here, execute the step
118         return true;
119      }
121     protected function define_structure() {
122         $paths = array();
123         $userinfo = $this->task->get_setting_value('users');
125         $paths[] = new restore_path_element('gradebook', '/gradebook');
126         $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
127         $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
128         if ($userinfo) {
129             $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
130         }
131         $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
132         $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
134         return $paths;
135     }
137     protected function process_gradebook($data) {
138     }
140     protected function process_grade_item($data) {
141         global $DB;
143         $data = (object)$data;
145         $oldid = $data->id;
146         $data->course = $this->get_courseid();
148         $data->courseid = $this->get_courseid();
150         if ($data->itemtype=='manual') {
151             // manual grade items store category id in categoryid
152             $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
153             // if mapping failed put in course's grade category
154             if (NULL == $data->categoryid) {
155                 $coursecat = grade_category::fetch_course_category($this->get_courseid());
156                 $data->categoryid = $coursecat->id;
157             }
158         } else if ($data->itemtype=='course') {
159             // course grade item stores their category id in iteminstance
160             $coursecat = grade_category::fetch_course_category($this->get_courseid());
161             $data->iteminstance = $coursecat->id;
162         } else if ($data->itemtype=='category') {
163             // category grade items store their category id in iteminstance
164             $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
165         } else {
166             throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
167         }
169         $data->scaleid   = $this->get_mappingid('scale', $data->scaleid, NULL);
170         $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
172         $data->locktime     = $this->apply_date_offset($data->locktime);
173         $data->timecreated  = $this->apply_date_offset($data->timecreated);
174         $data->timemodified = $this->apply_date_offset($data->timemodified);
176         $coursecategory = $newitemid = null;
177         //course grade item should already exist so updating instead of inserting
178         if($data->itemtype=='course') {
179             //get the ID of the already created grade item
180             $gi = new stdclass();
181             $gi->courseid  = $this->get_courseid();
182             $gi->itemtype  = $data->itemtype;
184             //need to get the id of the grade_category that was automatically created for the course
185             $category = new stdclass();
186             $category->courseid  = $this->get_courseid();
187             $category->parent  = null;
188             //course category fullname starts out as ? but may be edited
189             //$category->fullname  = '?';
190             $coursecategory = $DB->get_record('grade_categories', (array)$category);
191             $gi->iteminstance = $coursecategory->id;
193             $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
194             if (!empty($existinggradeitem)) {
195                 $data->id = $newitemid = $existinggradeitem->id;
196                 $DB->update_record('grade_items', $data);
197             }
198         } else if ($data->itemtype == 'manual') {
199             // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
200             $gi = array(
201                 'itemtype' => $data->itemtype,
202                 'courseid' => $data->courseid,
203                 'itemname' => $data->itemname,
204                 'categoryid' => $data->categoryid,
205             );
206             $newitemid = $DB->get_field('grade_items', 'id', $gi);
207         }
209         if (empty($newitemid)) {
210             //in case we found the course category but still need to insert the course grade item
211             if ($data->itemtype=='course' && !empty($coursecategory)) {
212                 $data->iteminstance = $coursecategory->id;
213             }
215             $newitemid = $DB->insert_record('grade_items', $data);
216         }
217         $this->set_mapping('grade_item', $oldid, $newitemid);
218     }
220     protected function process_grade_grade($data) {
221         global $DB;
223         $data = (object)$data;
224         $olduserid = $data->userid;
226         $data->itemid = $this->get_new_parentid('grade_item');
228         $data->userid = $this->get_mappingid('user', $data->userid, null);
229         if (!empty($data->userid)) {
230             $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
231             $data->locktime     = $this->apply_date_offset($data->locktime);
232             // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
233             $data->overridden = $this->apply_date_offset($data->overridden);
234             $data->timecreated  = $this->apply_date_offset($data->timecreated);
235             $data->timemodified = $this->apply_date_offset($data->timemodified);
237             $newitemid = $DB->insert_record('grade_grades', $data);
238         } else {
239             debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
240         }
241     }
243     protected function process_grade_category($data) {
244         global $DB;
246         $data = (object)$data;
247         $oldid = $data->id;
249         $data->course = $this->get_courseid();
250         $data->courseid = $data->course;
252         $data->timecreated  = $this->apply_date_offset($data->timecreated);
253         $data->timemodified = $this->apply_date_offset($data->timemodified);
255         $newitemid = null;
256         //no parent means a course level grade category. That may have been created when the course was created
257         if(empty($data->parent)) {
258             //parent was being saved as 0 when it should be null
259             $data->parent = null;
261             //get the already created course level grade category
262             $category = new stdclass();
263             $category->courseid = $this->get_courseid();
264             $category->parent = null;
266             $coursecategory = $DB->get_record('grade_categories', (array)$category);
267             if (!empty($coursecategory)) {
268                 $data->id = $newitemid = $coursecategory->id;
269                 $DB->update_record('grade_categories', $data);
270             }
271         }
273         //need to insert a course category
274         if (empty($newitemid)) {
275             $newitemid = $DB->insert_record('grade_categories', $data);
276         }
277         $this->set_mapping('grade_category', $oldid, $newitemid);
278     }
279     protected function process_grade_letter($data) {
280         global $DB;
282         $data = (object)$data;
283         $oldid = $data->id;
285         $data->contextid = context_course::instance($this->get_courseid())->id;
287         $gradeletter = (array)$data;
288         unset($gradeletter['id']);
289         if (!$DB->record_exists('grade_letters', $gradeletter)) {
290             $newitemid = $DB->insert_record('grade_letters', $data);
291         } else {
292             $newitemid = $data->id;
293         }
295         $this->set_mapping('grade_letter', $oldid, $newitemid);
296     }
297     protected function process_grade_setting($data) {
298         global $DB;
300         $data = (object)$data;
301         $oldid = $data->id;
303         $data->courseid = $this->get_courseid();
305         if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
306             $newitemid = $DB->insert_record('grade_settings', $data);
307         } else {
308             $newitemid = $data->id;
309         }
311         $this->set_mapping('grade_setting', $oldid, $newitemid);
312     }
314     /**
315      * put all activity grade items in the correct grade category and mark all for recalculation
316      */
317     protected function after_execute() {
318         global $DB;
320         $conditions = array(
321             'backupid' => $this->get_restoreid(),
322             'itemname' => 'grade_item'//,
323             //'itemid'   => $itemid
324         );
325         $rs = $DB->get_recordset('backup_ids_temp', $conditions);
327         // We need this for calculation magic later on.
328         $mappings = array();
330         if (!empty($rs)) {
331             foreach($rs as $grade_item_backup) {
333                 // Store the oldid with the new id.
334                 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
336                 $updateobj = new stdclass();
337                 $updateobj->id = $grade_item_backup->newitemid;
339                 //if this is an activity grade item that needs to be put back in its correct category
340                 if (!empty($grade_item_backup->parentitemid)) {
341                     $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
342                     if (!is_null($oldcategoryid)) {
343                         $updateobj->categoryid = $oldcategoryid;
344                         $DB->update_record('grade_items', $updateobj);
345                     }
346                 } else {
347                     //mark course and category items as needing to be recalculated
348                     $updateobj->needsupdate=1;
349                     $DB->update_record('grade_items', $updateobj);
350                 }
351             }
352         }
353         $rs->close();
355         // We need to update the calculations for calculated grade items that may reference old
356         // grade item ids using ##gi\d+##.
357         // $mappings can be empty, use 0 if so (won't match ever)
358         list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
359         $sql = "SELECT gi.id, gi.calculation
360                   FROM {grade_items} gi
361                  WHERE gi.id {$sql} AND
362                        calculation IS NOT NULL";
363         $rs = $DB->get_recordset_sql($sql, $params);
364         foreach ($rs as $gradeitem) {
365             // Collect all of the used grade item id references
366             if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
367                 // This calculation doesn't reference any other grade items... EASY!
368                 continue;
369             }
370             // For this next bit we are going to do the replacement of id's in two steps:
371             // 1. We will replace all old id references with a special mapping reference.
372             // 2. We will replace all mapping references with id's
373             // Why do we do this?
374             // Because there potentially there will be an overlap of ids within the query and we
375             // we substitute the wrong id.. safest way around this is the two step system
376             $calculationmap = array();
377             $mapcount = 0;
378             foreach ($matches[1] as $match) {
379                 // Check that the old id is known to us, if not it was broken to begin with and will
380                 // continue to be broken.
381                 if (!array_key_exists($match, $mappings)) {
382                     continue;
383                 }
384                 // Our special mapping key
385                 $mapping = '##MAPPING'.$mapcount.'##';
386                 // The old id that exists within the calculation now
387                 $oldid = '##gi'.$match.'##';
388                 // The new id that we want to replace the old one with.
389                 $newid = '##gi'.$mappings[$match].'##';
390                 // Replace in the special mapping key
391                 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
392                 // And record the mapping
393                 $calculationmap[$mapping] = $newid;
394                 $mapcount++;
395             }
396             // Iterate all special mappings for this calculation and replace in the new id's
397             foreach ($calculationmap as $mapping => $newid) {
398                 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
399             }
400             // Update the calculation now that its being remapped
401             $DB->update_record('grade_items', $gradeitem);
402         }
403         $rs->close();
405         // Need to correct the grade category path and parent
406         $conditions = array(
407             'courseid' => $this->get_courseid()
408         );
410         $rs = $DB->get_recordset('grade_categories', $conditions);
411         // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
412         foreach ($rs as $gc) {
413             if (!empty($gc->parent)) {
414                 $grade_category = new stdClass();
415                 $grade_category->id = $gc->id;
416                 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
417                 $DB->update_record('grade_categories', $grade_category);
418             }
419         }
420         $rs->close();
422         // Now we can rebuild all the paths
423         $rs = $DB->get_recordset('grade_categories', $conditions);
424         foreach ($rs as $gc) {
425             $grade_category = new stdClass();
426             $grade_category->id = $gc->id;
427             $grade_category->path = grade_category::build_path($gc);
428             $grade_category->depth = substr_count($grade_category->path, '/') - 1;
429             $DB->update_record('grade_categories', $grade_category);
430         }
431         $rs->close();
433         // Restore marks items as needing update. Update everything now.
434         grade_regrade_final_grades($this->get_courseid());
435     }
438 /**
439  * decode all the interlinks present in restored content
440  * relying 100% in the restore_decode_processor that handles
441  * both the contents to modify and the rules to be applied
442  */
443 class restore_decode_interlinks extends restore_execution_step {
445     protected function define_execution() {
446         // Get the decoder (from the plan)
447         $decoder = $this->task->get_decoder();
448         restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
449         // And launch it, everything will be processed
450         $decoder->execute();
451     }
454 /**
455  * first, ensure that we have no gaps in section numbers
456  * and then, rebuid the course cache
457  */
458 class restore_rebuild_course_cache extends restore_execution_step {
460     protected function define_execution() {
461         global $DB;
463         // Although there is some sort of auto-recovery of missing sections
464         // present in course/formats... here we check that all the sections
465         // from 0 to MAX(section->section) exist, creating them if necessary
466         $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
467         // Iterate over all sections
468         for ($i = 0; $i <= $maxsection; $i++) {
469             // If the section $i doesn't exist, create it
470             if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
471                 $sectionrec = array(
472                     'course' => $this->get_courseid(),
473                     'section' => $i);
474                 $DB->insert_record('course_sections', $sectionrec); // missing section created
475             }
476         }
478         // Rebuild cache now that all sections are in place
479         rebuild_course_cache($this->get_courseid());
480         cache_helper::purge_by_event('changesincourse');
481         cache_helper::purge_by_event('changesincoursecat');
482     }
485 /**
486  * Review all the tasks having one after_restore method
487  * executing it to perform some final adjustments of information
488  * not available when the task was executed.
489  */
490 class restore_execute_after_restore extends restore_execution_step {
492     protected function define_execution() {
494         // Simply call to the execute_after_restore() method of the task
495         // that always is the restore_final_task
496         $this->task->launch_execute_after_restore();
497     }
501 /**
502  * Review all the (pending) block positions in backup_ids, matching by
503  * contextid, creating positions as needed. This is executed by the
504  * final task, once all the contexts have been created
505  */
506 class restore_review_pending_block_positions extends restore_execution_step {
508     protected function define_execution() {
509         global $DB;
511         // Get all the block_position objects pending to match
512         $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
513         $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
514         // Process block positions, creating them or accumulating for final step
515         foreach($rs as $posrec) {
516             // Get the complete position object out of the info field.
517             $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
518             // If position is for one already mapped (known) contextid
519             // process it now, creating the position, else nothing to
520             // do, position finally discarded
521             if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
522                 $position->contextid = $newctx->newitemid;
523                 // Create the block position
524                 $DB->insert_record('block_positions', $position);
525             }
526         }
527         $rs->close();
528     }
531 /**
532  * Process all the saved module availability records in backup_ids, matching
533  * course modules and grade item id once all them have been already restored.
534  * only if all matchings are satisfied the availability condition will be created.
535  * At the same time, it is required for the site to have that functionality enabled.
536  */
537 class restore_process_course_modules_availability extends restore_execution_step {
539     protected function define_execution() {
540         global $CFG, $DB;
542         // Site hasn't availability enabled
543         if (empty($CFG->enableavailability)) {
544             return;
545         }
547         // Get all the module_availability objects to process
548         $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
549         $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
550         // Process availabilities, creating them if everything matches ok
551         foreach($rs as $availrec) {
552             $allmatchesok = true;
553             // Get the complete availabilityobject
554             $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
555             // Map the sourcecmid if needed and possible
556             if (!empty($availability->sourcecmid)) {
557                 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
558                 if ($newcm) {
559                     $availability->sourcecmid = $newcm->newitemid;
560                 } else {
561                     $allmatchesok = false; // Failed matching, we won't create this availability rule
562                 }
563             }
564             // Map the gradeitemid if needed and possible
565             if (!empty($availability->gradeitemid)) {
566                 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
567                 if ($newgi) {
568                     $availability->gradeitemid = $newgi->newitemid;
569                 } else {
570                     $allmatchesok = false; // Failed matching, we won't create this availability rule
571                 }
572             }
573             if ($allmatchesok) { // Everything ok, create the availability rule
574                 $DB->insert_record('course_modules_availability', $availability);
575             }
576         }
577         $rs->close();
578     }
582 /*
583  * Execution step that, *conditionally* (if there isn't preloaded information)
584  * will load the inforef files for all the included course/section/activity tasks
585  * to backup_temp_ids. They will be stored with "xxxxref" as itemname
586  */
587 class restore_load_included_inforef_records extends restore_execution_step {
589     protected function define_execution() {
591         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
592             return;
593         }
595         // Get all the included tasks
596         $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
597         foreach ($tasks as $task) {
598             // Load the inforef.xml file if exists
599             $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
600             if (file_exists($inforefpath)) {
601                 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath); // Load each inforef file to temp_ids
602             }
603         }
604     }
607 /*
608  * Execution step that will load all the needed files into backup_files_temp
609  *   - info: contains the whole original object (times, names...)
610  * (all them being original ids as loaded from xml)
611  */
612 class restore_load_included_files extends restore_structure_step {
614     protected function define_structure() {
616         $file = new restore_path_element('file', '/files/file');
618         return array($file);
619     }
621     /**
622      * Process one <file> element from files.xml
623      *
624      * @param array $data the element data
625      */
626     public function process_file($data) {
628         $data = (object)$data; // handy
630         // load it if needed:
631         //   - it it is one of the annotated inforef files (course/section/activity/block)
632         //   - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
633         // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
634         //       but then we'll need to change it to load plugins itself (because this is executed too early in restore)
635         $isfileref   = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
636         $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
637                         $data->component == 'grouping' || $data->component == 'grade' ||
638                         $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
639         if ($isfileref || $iscomponent) {
640             restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
641         }
642     }
645 /**
646  * Execution step that, *conditionally* (if there isn't preloaded information),
647  * will load all the needed roles to backup_temp_ids. They will be stored with
648  * "role" itemname. Also it will perform one automatic mapping to roles existing
649  * in the target site, based in permissions of the user performing the restore,
650  * archetypes and other bits. At the end, each original role will have its associated
651  * target role or 0 if it's going to be skipped. Note we wrap everything over one
652  * restore_dbops method, as far as the same stuff is going to be also executed
653  * by restore prechecks
654  */
655 class restore_load_and_map_roles extends restore_execution_step {
657     protected function define_execution() {
658         if ($this->task->get_preloaded_information()) { // if info is already preloaded
659             return;
660         }
662         $file = $this->get_basepath() . '/roles.xml';
663         // Load needed toles to temp_ids
664         restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
666         // Process roles, mapping/skipping. Any error throws exception
667         // Note we pass controller's info because it can contain role mapping information
668         // about manual mappings performed by UI
669         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);
670     }
673 /**
674  * Execution step that, *conditionally* (if there isn't preloaded information
675  * and users have been selected in settings, will load all the needed users
676  * to backup_temp_ids. They will be stored with "user" itemname and with
677  * their original contextid as paremitemid
678  */
679 class restore_load_included_users extends restore_execution_step {
681     protected function define_execution() {
683         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
684             return;
685         }
686         if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
687             return;
688         }
689         $file = $this->get_basepath() . '/users.xml';
690         restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
691     }
694 /**
695  * Execution step that, *conditionally* (if there isn't preloaded information
696  * and users have been selected in settings, will process all the needed users
697  * in order to decide and perform any action with them (create / map / error)
698  * Note: Any error will cause exception, as far as this is the same processing
699  * than the one into restore prechecks (that should have stopped process earlier)
700  */
701 class restore_process_included_users extends restore_execution_step {
703     protected function define_execution() {
705         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
706             return;
707         }
708         if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
709             return;
710         }
711         restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
712     }
715 /**
716  * Execution step that will create all the needed users as calculated
717  * by @restore_process_included_users (those having newiteind = 0)
718  */
719 class restore_create_included_users extends restore_execution_step {
721     protected function define_execution() {
723         restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->task->get_userid());
724     }
727 /**
728  * Structure step that will create all the needed groups and groupings
729  * by loading them from the groups.xml file performing the required matches.
730  * Note group members only will be added if restoring user info
731  */
732 class restore_groups_structure_step extends restore_structure_step {
734     protected function define_structure() {
736         $paths = array(); // Add paths here
738         $paths[] = new restore_path_element('group', '/groups/group');
739         $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
740         $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
742         return $paths;
743     }
745     // Processing functions go here
746     public function process_group($data) {
747         global $DB;
749         $data = (object)$data; // handy
750         $data->courseid = $this->get_courseid();
752         // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
753         // another a group in the same course
754         $context = context_course::instance($data->courseid);
755         if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
756             if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
757                 unset($data->idnumber);
758             }
759         } else {
760             unset($data->idnumber);
761         }
763         $oldid = $data->id;    // need this saved for later
765         $restorefiles = false; // Only if we end creating the group
767         // Search if the group already exists (by name & description) in the target course
768         $description_clause = '';
769         $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
770         if (!empty($data->description)) {
771             $description_clause = ' AND ' .
772                                   $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
773            $params['description'] = $data->description;
774         }
775         if (!$groupdb = $DB->get_record_sql("SELECT *
776                                                FROM {groups}
777                                               WHERE courseid = :courseid
778                                                 AND name = :grname $description_clause", $params)) {
779             // group doesn't exist, create
780             $newitemid = $DB->insert_record('groups', $data);
781             $restorefiles = true; // We'll restore the files
782         } else {
783             // group exists, use it
784             $newitemid = $groupdb->id;
785         }
786         // Save the id mapping
787         $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
788         // Invalidate the course group data cache just in case.
789         cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
790     }
792     public function process_grouping($data) {
793         global $DB;
795         $data = (object)$data; // handy
796         $data->courseid = $this->get_courseid();
798         // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
799         // another a grouping in the same course
800         $context = context_course::instance($data->courseid);
801         if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
802             if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
803                 unset($data->idnumber);
804             }
805         } else {
806             unset($data->idnumber);
807         }
809         $oldid = $data->id;    // need this saved for later
810         $restorefiles = false; // Only if we end creating the grouping
812         // Search if the grouping already exists (by name & description) in the target course
813         $description_clause = '';
814         $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
815         if (!empty($data->description)) {
816             $description_clause = ' AND ' .
817                                   $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
818            $params['description'] = $data->description;
819         }
820         if (!$groupingdb = $DB->get_record_sql("SELECT *
821                                                   FROM {groupings}
822                                                  WHERE courseid = :courseid
823                                                    AND name = :grname $description_clause", $params)) {
824             // grouping doesn't exist, create
825             $newitemid = $DB->insert_record('groupings', $data);
826             $restorefiles = true; // We'll restore the files
827         } else {
828             // grouping exists, use it
829             $newitemid = $groupingdb->id;
830         }
831         // Save the id mapping
832         $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
833         // Invalidate the course group data cache just in case.
834         cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
835     }
837     public function process_grouping_group($data) {
838         global $CFG;
840         require_once($CFG->dirroot.'/group/lib.php');
842         $data = (object)$data;
843         groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
844     }
846     protected function after_execute() {
847         // Add group related files, matching with "group" mappings
848         $this->add_related_files('group', 'icon', 'group');
849         $this->add_related_files('group', 'description', 'group');
850         // Add grouping related files, matching with "grouping" mappings
851         $this->add_related_files('grouping', 'description', 'grouping');
852         // Invalidate the course group data.
853         cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
854     }
858 /**
859  * Structure step that will create all the needed group memberships
860  * by loading them from the groups.xml file performing the required matches.
861  */
862 class restore_groups_members_structure_step extends restore_structure_step {
864     protected $plugins = null;
866     protected function define_structure() {
868         $paths = array(); // Add paths here
870         if ($this->get_setting_value('users')) {
871             $paths[] = new restore_path_element('group', '/groups/group');
872             $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
873         }
875         return $paths;
876     }
878     public function process_group($data) {
879         $data = (object)$data; // handy
881         // HACK ALERT!
882         // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
883         // Let's fake internal state to make $this->get_new_parentid('group') work.
885         $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
886     }
888     public function process_member($data) {
889         global $DB, $CFG;
890         require_once("$CFG->dirroot/group/lib.php");
892         // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
894         $data = (object)$data; // handy
896         // get parent group->id
897         $data->groupid = $this->get_new_parentid('group');
899         // map user newitemid and insert if not member already
900         if ($data->userid = $this->get_mappingid('user', $data->userid)) {
901             if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
902                 // Check the component, if any, exists.
903                 if (empty($data->component)) {
904                     groups_add_member($data->groupid, $data->userid);
906                 } else if ((strpos($data->component, 'enrol_') === 0)) {
907                     // Deal with enrolment groups - ignore the component and just find out the instance via new id,
908                     // it is possible that enrolment was restored using different plugin type.
909                     if (!isset($this->plugins)) {
910                         $this->plugins = enrol_get_plugins(true);
911                     }
912                     if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
913                         if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
914                             if (isset($this->plugins[$instance->enrol])) {
915                                 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
916                             }
917                         }
918                     }
920                 } else {
921                     $dir = core_component::get_component_directory($data->component);
922                     if ($dir and is_dir($dir)) {
923                         if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
924                             return;
925                         }
926                     }
927                     // Bad luck, plugin could not restore the data, let's add normal membership.
928                     groups_add_member($data->groupid, $data->userid);
929                     $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
930                     debugging($message);
931                     $this->log($message, backup::LOG_WARNING);
932                 }
933             }
934         }
935     }
938 /**
939  * Structure step that will create all the needed scales
940  * by loading them from the scales.xml
941  */
942 class restore_scales_structure_step extends restore_structure_step {
944     protected function define_structure() {
946         $paths = array(); // Add paths here
947         $paths[] = new restore_path_element('scale', '/scales_definition/scale');
948         return $paths;
949     }
951     protected function process_scale($data) {
952         global $DB;
954         $data = (object)$data;
956         $restorefiles = false; // Only if we end creating the group
958         $oldid = $data->id;    // need this saved for later
960         // Look for scale (by 'scale' both in standard (course=0) and current course
961         // with priority to standard scales (ORDER clause)
962         // scale is not course unique, use get_record_sql to suppress warning
963         // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
964         $compare_scale_clause = $DB->sql_compare_text('scale')  . ' = ' . $DB->sql_compare_text(':scaledesc');
965         $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
966         if (!$scadb = $DB->get_record_sql("SELECT *
967                                             FROM {scale}
968                                            WHERE courseid IN (0, :courseid)
969                                              AND $compare_scale_clause
970                                         ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
971             // Remap the user if possible, defaut to user performing the restore if not
972             $userid = $this->get_mappingid('user', $data->userid);
973             $data->userid = $userid ? $userid : $this->task->get_userid();
974             // Remap the course if course scale
975             $data->courseid = $data->courseid ? $this->get_courseid() : 0;
976             // If global scale (course=0), check the user has perms to create it
977             // falling to course scale if not
978             $systemctx = context_system::instance();
979             if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
980                 $data->courseid = $this->get_courseid();
981             }
982             // scale doesn't exist, create
983             $newitemid = $DB->insert_record('scale', $data);
984             $restorefiles = true; // We'll restore the files
985         } else {
986             // scale exists, use it
987             $newitemid = $scadb->id;
988         }
989         // Save the id mapping (with files support at system context)
990         $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
991     }
993     protected function after_execute() {
994         // Add scales related files, matching with "scale" mappings
995         $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
996     }
1000 /**
1001  * Structure step that will create all the needed outocomes
1002  * by loading them from the outcomes.xml
1003  */
1004 class restore_outcomes_structure_step extends restore_structure_step {
1006     protected function define_structure() {
1008         $paths = array(); // Add paths here
1009         $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1010         return $paths;
1011     }
1013     protected function process_outcome($data) {
1014         global $DB;
1016         $data = (object)$data;
1018         $restorefiles = false; // Only if we end creating the group
1020         $oldid = $data->id;    // need this saved for later
1022         // Look for outcome (by shortname both in standard (courseid=null) and current course
1023         // with priority to standard outcomes (ORDER clause)
1024         // outcome is not course unique, use get_record_sql to suppress warning
1025         $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1026         if (!$outdb = $DB->get_record_sql('SELECT *
1027                                              FROM {grade_outcomes}
1028                                             WHERE shortname = :shortname
1029                                               AND (courseid = :courseid OR courseid IS NULL)
1030                                          ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1031             // Remap the user
1032             $userid = $this->get_mappingid('user', $data->usermodified);
1033             $data->usermodified = $userid ? $userid : $this->task->get_userid();
1034             // Remap the scale
1035             $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1036             // Remap the course if course outcome
1037             $data->courseid = $data->courseid ? $this->get_courseid() : null;
1038             // If global outcome (course=null), check the user has perms to create it
1039             // falling to course outcome if not
1040             $systemctx = context_system::instance();
1041             if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1042                 $data->courseid = $this->get_courseid();
1043             }
1044             // outcome doesn't exist, create
1045             $newitemid = $DB->insert_record('grade_outcomes', $data);
1046             $restorefiles = true; // We'll restore the files
1047         } else {
1048             // scale exists, use it
1049             $newitemid = $outdb->id;
1050         }
1051         // Set the corresponding grade_outcomes_courses record
1052         $outcourserec = new stdclass();
1053         $outcourserec->courseid  = $this->get_courseid();
1054         $outcourserec->outcomeid = $newitemid;
1055         if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1056             $DB->insert_record('grade_outcomes_courses', $outcourserec);
1057         }
1058         // Save the id mapping (with files support at system context)
1059         $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1060     }
1062     protected function after_execute() {
1063         // Add outcomes related files, matching with "outcome" mappings
1064         $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1065     }
1068 /**
1069  * Execution step that, *conditionally* (if there isn't preloaded information
1070  * will load all the question categories and questions (header info only)
1071  * to backup_temp_ids. They will be stored with "question_category" and
1072  * "question" itemnames and with their original contextid and question category
1073  * id as paremitemids
1074  */
1075 class restore_load_categories_and_questions extends restore_execution_step {
1077     protected function define_execution() {
1079         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1080             return;
1081         }
1082         $file = $this->get_basepath() . '/questions.xml';
1083         restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1084     }
1087 /**
1088  * Execution step that, *conditionally* (if there isn't preloaded information)
1089  * will process all the needed categories and questions
1090  * in order to decide and perform any action with them (create / map / error)
1091  * Note: Any error will cause exception, as far as this is the same processing
1092  * than the one into restore prechecks (that should have stopped process earlier)
1093  */
1094 class restore_process_categories_and_questions extends restore_execution_step {
1096     protected function define_execution() {
1098         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1099             return;
1100         }
1101         restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1102     }
1105 /**
1106  * Structure step that will read the section.xml creating/updating sections
1107  * as needed, rebuilding course cache and other friends
1108  */
1109 class restore_section_structure_step extends restore_structure_step {
1111     protected function define_structure() {
1112         global $CFG;
1114         $paths = array();
1116         $section = new restore_path_element('section', '/section');
1117         $paths[] = $section;
1118         if ($CFG->enableavailability) {
1119             $paths[] = new restore_path_element('availability', '/section/availability');
1120             $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1121         }
1122         $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1124         // Apply for 'format' plugins optional paths at section level
1125         $this->add_plugin_structure('format', $section);
1127         // Apply for 'local' plugins optional paths at section level
1128         $this->add_plugin_structure('local', $section);
1130         return $paths;
1131     }
1133     public function process_section($data) {
1134         global $CFG, $DB;
1135         $data = (object)$data;
1136         $oldid = $data->id; // We'll need this later
1138         $restorefiles = false;
1140         // Look for the section
1141         $section = new stdclass();
1142         $section->course  = $this->get_courseid();
1143         $section->section = $data->number;
1144         // Section doesn't exist, create it with all the info from backup
1145         if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1146             $section->name = $data->name;
1147             $section->summary = $data->summary;
1148             $section->summaryformat = $data->summaryformat;
1149             $section->sequence = '';
1150             $section->visible = $data->visible;
1151             if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1152                 $section->availablefrom = 0;
1153                 $section->availableuntil = 0;
1154                 $section->showavailability = 0;
1155             } else {
1156                 $section->availablefrom = isset($data->availablefrom) ? $this->apply_date_offset($data->availablefrom) : 0;
1157                 $section->availableuntil = isset($data->availableuntil) ? $this->apply_date_offset($data->availableuntil) : 0;
1158                 $section->showavailability = isset($data->showavailability) ? $data->showavailability : 0;
1159             }
1160             if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
1161                 $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
1162             }
1163             $newitemid = $DB->insert_record('course_sections', $section);
1164             $restorefiles = true;
1166         // Section exists, update non-empty information
1167         } else {
1168             $section->id = $secrec->id;
1169             if ((string)$secrec->name === '') {
1170                 $section->name = $data->name;
1171             }
1172             if (empty($secrec->summary)) {
1173                 $section->summary = $data->summary;
1174                 $section->summaryformat = $data->summaryformat;
1175                 $restorefiles = true;
1176             }
1177             if (empty($secrec->groupingid)) {
1178                 if (!empty($CFG->enablegroupmembersonly)) { // Only if enablegroupmembersonly is enabled
1179                     $section->groupingid = isset($data->groupingid) ? $this->get_mappingid('grouping', $data->groupingid) : 0;
1180                 }
1181             }
1183             // Don't update available from, available until, or show availability
1184             // (I didn't see a useful way to define whether existing or new one should
1185             // take precedence).
1187             $DB->update_record('course_sections', $section);
1188             $newitemid = $secrec->id;
1189         }
1191         // Annotate the section mapping, with restorefiles option if needed
1192         $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1194         // set the new course_section id in the task
1195         $this->task->set_sectionid($newitemid);
1198         // Commented out. We never modify course->numsections as far as that is used
1199         // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1200         // Note: We keep the code here, to know about and because of the possibility of making this
1201         // optional based on some setting/attribute in the future
1202         // If needed, adjust course->numsections
1203         //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1204         //    if ($numsections < $section->section) {
1205         //        $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1206         //    }
1207         //}
1208     }
1210     public function process_availability($data) {
1211         global $DB;
1212         $data = (object)$data;
1214         $data->coursesectionid = $this->task->get_sectionid();
1216         // NOTE: Other values in $data need updating, but these (cm,
1217         // grade items) have not yet been restored, so are done later.
1219         $newid = $DB->insert_record('course_sections_availability', $data);
1221         // We do not need to map between old and new id but storing a mapping
1222         // means it gets added to the backup_ids table to record which ones
1223         // need updating. The mapping is stored with $newid => $newid for
1224         // convenience.
1225         $this->set_mapping('course_sections_availability', $newid, $newid);
1226     }
1228     public function process_availability_field($data) {
1229         global $DB;
1230         $data = (object)$data;
1231         // Mark it is as passed by default
1232         $passed = true;
1233         $customfieldid = null;
1235         // If a customfield has been used in order to pass we must be able to match an existing
1236         // customfield by name (data->customfield) and type (data->customfieldtype)
1237         if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1238             // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1239             // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1240             $passed = false;
1241         } else if (!is_null($data->customfield)) {
1242             $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1243             $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1244             $passed = ($customfieldid !== false);
1245         }
1247         if ($passed) {
1248             // Create the object to insert into the database
1249             $availfield = new stdClass();
1250             $availfield->coursesectionid = $this->task->get_sectionid();
1251             $availfield->userfield = $data->userfield;
1252             $availfield->customfieldid = $customfieldid;
1253             $availfield->operator = $data->operator;
1254             $availfield->value = $data->value;
1255             $DB->insert_record('course_sections_avail_fields', $availfield);
1256         }
1257     }
1259     public function process_course_format_options($data) {
1260         global $DB;
1261         $data = (object)$data;
1262         $oldid = $data->id;
1263         unset($data->id);
1264         $data->sectionid = $this->task->get_sectionid();
1265         $data->courseid = $this->get_courseid();
1266         $newid = $DB->insert_record('course_format_options', $data);
1267         $this->set_mapping('course_format_options', $oldid, $newid);
1268     }
1270     protected function after_execute() {
1271         // Add section related files, with 'course_section' itemid to match
1272         $this->add_related_files('course', 'section', 'course_section');
1273     }
1275     public function after_restore() {
1276         global $DB;
1278         $sectionid = $this->get_task()->get_sectionid();
1280         // Get data object for current section availability (if any).
1281         $records = $DB->get_records('course_sections_availability',
1282                 array('coursesectionid' => $sectionid), 'id, sourcecmid, gradeitemid');
1284         // If it exists, update mappings.
1285         foreach ($records as $data) {
1286             // Only update mappings for entries which are created by this restore.
1287             // Otherwise, when you restore to an existing course, it will mess up
1288             // existing section availability entries.
1289             if (!$this->get_mappingid('course_sections_availability', $data->id, false)) {
1290                 continue;
1291             }
1293             // Update source cmid / grade id to new value.
1294             $data->sourcecmid = $this->get_mappingid('course_module', $data->sourcecmid);
1295             if (!$data->sourcecmid) {
1296                 $data->sourcecmid = null;
1297             }
1298             $data->gradeitemid = $this->get_mappingid('grade_item', $data->gradeitemid);
1299             if (!$data->gradeitemid) {
1300                 $data->gradeitemid = null;
1301             }
1303             // Delete the record if the condition wasn't found, otherwise update it.
1304             if ($data->sourcecmid === null && $data->gradeitemid === null) {
1305                 $DB->delete_records('course_sections_availability', array('id' => $data->id));
1306             } else {
1307                 $DB->update_record('course_sections_availability', $data);
1308             }
1309         }
1310     }
1314 /**
1315  * Structure step that will read the course.xml file, loading it and performing
1316  * various actions depending of the site/restore settings. Note that target
1317  * course always exist before arriving here so this step will be updating
1318  * the course record (never inserting)
1319  */
1320 class restore_course_structure_step extends restore_structure_step {
1321     /**
1322      * @var bool this gets set to true by {@link process_course()} if we are
1323      * restoring an old coures that used the legacy 'module security' feature.
1324      * If so, we have to do more work in {@link after_execute()}.
1325      */
1326     protected $legacyrestrictmodules = false;
1328     /**
1329      * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1330      * array with array keys the module names ('forum', 'quiz', etc.). These are
1331      * the modules that are allowed according to the data in the backup file.
1332      * In {@link after_execute()} we then have to prevent adding of all the other
1333      * types of activity.
1334      */
1335     protected $legacyallowedmodules = array();
1337     protected function define_structure() {
1339         $course = new restore_path_element('course', '/course');
1340         $category = new restore_path_element('category', '/course/category');
1341         $tag = new restore_path_element('tag', '/course/tags/tag');
1342         $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1344         // Apply for 'format' plugins optional paths at course level
1345         $this->add_plugin_structure('format', $course);
1347         // Apply for 'theme' plugins optional paths at course level
1348         $this->add_plugin_structure('theme', $course);
1350         // Apply for 'report' plugins optional paths at course level
1351         $this->add_plugin_structure('report', $course);
1353         // Apply for 'course report' plugins optional paths at course level
1354         $this->add_plugin_structure('coursereport', $course);
1356         // Apply for plagiarism plugins optional paths at course level
1357         $this->add_plugin_structure('plagiarism', $course);
1359         // Apply for local plugins optional paths at course level
1360         $this->add_plugin_structure('local', $course);
1362         return array($course, $category, $tag, $allowed_module);
1363     }
1365     /**
1366      * Processing functions go here
1367      *
1368      * @global moodledatabase $DB
1369      * @param stdClass $data
1370      */
1371     public function process_course($data) {
1372         global $CFG, $DB;
1374         $data = (object)$data;
1376         $fullname  = $this->get_setting_value('course_fullname');
1377         $shortname = $this->get_setting_value('course_shortname');
1378         $startdate = $this->get_setting_value('course_startdate');
1380         // Calculate final course names, to avoid dupes
1381         list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1383         // Need to change some fields before updating the course record
1384         $data->id = $this->get_courseid();
1385         $data->fullname = $fullname;
1386         $data->shortname= $shortname;
1388         $context = context::instance_by_id($this->task->get_contextid());
1389         if (has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1390             $data->idnumber = '';
1391         } else {
1392             unset($data->idnumber);
1393         }
1395         // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1396         // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1397         if (empty($data->hiddensections)) {
1398             $data->hiddensections = 0;
1399         }
1401         // Set legacyrestrictmodules to true if the course was resticting modules. If so
1402         // then we will need to process restricted modules after execution.
1403         $this->legacyrestrictmodules = !empty($data->restrictmodules);
1405         $data->startdate= $this->apply_date_offset($data->startdate);
1406         if ($data->defaultgroupingid) {
1407             $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1408         }
1409         if (empty($CFG->enablecompletion)) {
1410             $data->enablecompletion = 0;
1411             $data->completionstartonenrol = 0;
1412             $data->completionnotify = 0;
1413         }
1414         $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1415         if (!array_key_exists($data->lang, $languages)) {
1416             $data->lang = '';
1417         }
1419         $themes = get_list_of_themes(); // Get themes for quick search later
1420         if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1421             $data->theme = '';
1422         }
1424         // Course record ready, update it
1425         $DB->update_record('course', $data);
1427         course_get_format($data)->update_course_format_options($data);
1429         // Role name aliases
1430         restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1431     }
1433     public function process_category($data) {
1434         // Nothing to do with the category. UI sets it before restore starts
1435     }
1437     public function process_tag($data) {
1438         global $CFG, $DB;
1440         $data = (object)$data;
1442         if (!empty($CFG->usetags)) { // if enabled in server
1443             // TODO: This is highly inneficient. Each time we add one tag
1444             // we fetch all the existing because tag_set() deletes them
1445             // so everything must be reinserted on each call
1446             $tags = array();
1447             $existingtags = tag_get_tags('course', $this->get_courseid());
1448             // Re-add all the existitng tags
1449             foreach ($existingtags as $existingtag) {
1450                 $tags[] = $existingtag->rawname;
1451             }
1452             // Add the one being restored
1453             $tags[] = $data->rawname;
1454             // Send all the tags back to the course
1455             tag_set('course', $this->get_courseid(), $tags);
1456         }
1457     }
1459     public function process_allowed_module($data) {
1460         $data = (object)$data;
1462         // Backwards compatiblity support for the data that used to be in the
1463         // course_allowed_modules table.
1464         if ($this->legacyrestrictmodules) {
1465             $this->legacyallowedmodules[$data->modulename] = 1;
1466         }
1467     }
1469     protected function after_execute() {
1470         global $DB;
1472         // Add course related files, without itemid to match
1473         $this->add_related_files('course', 'summary', null);
1474         $this->add_related_files('course', 'overviewfiles', null);
1476         // Deal with legacy allowed modules.
1477         if ($this->legacyrestrictmodules) {
1478             $context = context_course::instance($this->get_courseid());
1480             list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1481             list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1482             foreach ($managerroleids as $roleid) {
1483                 unset($roleids[$roleid]);
1484             }
1486             foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1487                 if (isset($this->legacyallowedmodules[$modname])) {
1488                     // Module is allowed, no worries.
1489                     continue;
1490                 }
1492                 $capability = 'mod/' . $modname . ':addinstance';
1493                 foreach ($roleids as $roleid) {
1494                     assign_capability($capability, CAP_PREVENT, $roleid, $context);
1495                 }
1496             }
1497         }
1498     }
1501 /**
1502  * Execution step that will migrate legacy files if present.
1503  */
1504 class restore_course_legacy_files_step extends restore_execution_step {
1505     public function define_execution() {
1506         global $DB;
1508         // Do a check for legacy files and skip if there are none.
1509         $sql = 'SELECT count(*)
1510                   FROM {backup_files_temp}
1511                  WHERE backupid = ?
1512                    AND contextid = ?
1513                    AND component = ?
1514                    AND filearea  = ?';
1515         $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
1517         if ($DB->count_records_sql($sql, $params)) {
1518             $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
1519             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
1520                 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
1521         }
1522     }
1525 /*
1526  * Structure step that will read the roles.xml file (at course/activity/block levels)
1527  * containing all the role_assignments and overrides for that context. If corresponding to
1528  * one mapped role, they will be applied to target context. Will observe the role_assignments
1529  * setting to decide if ras are restored.
1530  *
1531  * Note: this needs to be executed after all users are enrolled.
1532  */
1533 class restore_ras_and_caps_structure_step extends restore_structure_step {
1534     protected $plugins = null;
1536     protected function define_structure() {
1538         $paths = array();
1540         // Observe the role_assignments setting
1541         if ($this->get_setting_value('role_assignments')) {
1542             $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1543         }
1544         $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1546         return $paths;
1547     }
1549     /**
1550      * Assign roles
1551      *
1552      * This has to be called after enrolments processing.
1553      *
1554      * @param mixed $data
1555      * @return void
1556      */
1557     public function process_assignment($data) {
1558         global $DB;
1560         $data = (object)$data;
1562         // Check roleid, userid are one of the mapped ones
1563         if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1564             return;
1565         }
1566         if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1567             return;
1568         }
1569         if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1570             // Only assign roles to not deleted users
1571             return;
1572         }
1573         if (!$contextid = $this->task->get_contextid()) {
1574             return;
1575         }
1577         if (empty($data->component)) {
1578             // assign standard manual roles
1579             // TODO: role_assign() needs one userid param to be able to specify our restore userid
1580             role_assign($newroleid, $newuserid, $contextid);
1582         } else if ((strpos($data->component, 'enrol_') === 0)) {
1583             // Deal with enrolment roles - ignore the component and just find out the instance via new id,
1584             // it is possible that enrolment was restored using different plugin type.
1585             if (!isset($this->plugins)) {
1586                 $this->plugins = enrol_get_plugins(true);
1587             }
1588             if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1589                 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1590                     if (isset($this->plugins[$instance->enrol])) {
1591                         $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
1592                     }
1593                 }
1594             }
1596         } else {
1597             $data->roleid    = $newroleid;
1598             $data->userid    = $newuserid;
1599             $data->contextid = $contextid;
1600             $dir = core_component::get_component_directory($data->component);
1601             if ($dir and is_dir($dir)) {
1602                 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
1603                     return;
1604                 }
1605             }
1606             // Bad luck, plugin could not restore the data, let's add normal membership.
1607             role_assign($data->roleid, $data->userid, $data->contextid);
1608             $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
1609             debugging($message);
1610             $this->log($message, backup::LOG_WARNING);
1611         }
1612     }
1614     public function process_override($data) {
1615         $data = (object)$data;
1617         // Check roleid is one of the mapped ones
1618         $newroleid = $this->get_mappingid('role', $data->roleid);
1619         // If newroleid and context are valid assign it via API (it handles dupes and so on)
1620         if ($newroleid && $this->task->get_contextid()) {
1621             // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1622             // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1623             assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1624         }
1625     }
1628 /**
1629  * If no instances yet add default enrol methods the same way as when creating new course in UI.
1630  */
1631 class restore_default_enrolments_step extends restore_execution_step {
1632     public function define_execution() {
1633         global $DB;
1635         $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
1637         if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
1638             // Something already added instances, do not add default instances.
1639             $plugins = enrol_get_plugins(true);
1640             foreach ($plugins as $plugin) {
1641                 $plugin->restore_sync_course($course);
1642             }
1644         } else {
1645             // Looks like a newly created course.
1646             enrol_course_updated(true, $course, null);
1647         }
1648     }
1651 /**
1652  * This structure steps restores the enrol plugins and their underlying
1653  * enrolments, performing all the mappings and/or movements required
1654  */
1655 class restore_enrolments_structure_step extends restore_structure_step {
1656     protected $enrolsynced = false;
1657     protected $plugins = null;
1658     protected $originalstatus = array();
1660     /**
1661      * Conditionally decide if this step should be executed.
1662      *
1663      * This function checks the following parameter:
1664      *
1665      *   1. the course/enrolments.xml file exists
1666      *
1667      * @return bool true is safe to execute, false otherwise
1668      */
1669     protected function execute_condition() {
1671         // Check it is included in the backup
1672         $fullpath = $this->task->get_taskbasepath();
1673         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1674         if (!file_exists($fullpath)) {
1675             // Not found, can't restore enrolments info
1676             return false;
1677         }
1679         return true;
1680     }
1682     protected function define_structure() {
1684         $paths = array();
1686         $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1687         $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1689         return $paths;
1690     }
1692     /**
1693      * Create enrolment instances.
1694      *
1695      * This has to be called after creation of roles
1696      * and before adding of role assignments.
1697      *
1698      * @param mixed $data
1699      * @return void
1700      */
1701     public function process_enrol($data) {
1702         global $DB;
1704         $data = (object)$data;
1705         $oldid = $data->id; // We'll need this later.
1706         unset($data->id);
1708         $this->originalstatus[$oldid] = $data->status;
1710         if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
1711             $this->set_mapping('enrol', $oldid, 0);
1712             return;
1713         }
1715         if (!isset($this->plugins)) {
1716             $this->plugins = enrol_get_plugins(true);
1717         }
1719         if (!$this->enrolsynced) {
1720             // Make sure that all plugin may create instances and enrolments automatically
1721             // before the first instance restore - this is suitable especially for plugins
1722             // that synchronise data automatically using course->idnumber or by course categories.
1723             foreach ($this->plugins as $plugin) {
1724                 $plugin->restore_sync_course($courserec);
1725             }
1726             $this->enrolsynced = true;
1727         }
1729         // Map standard fields - plugin has to process custom fields manually.
1730         $data->roleid   = $this->get_mappingid('role', $data->roleid);
1731         $data->courseid = $courserec->id;
1733         if ($this->get_setting_value('enrol_migratetomanual')) {
1734             unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
1735             if (!enrol_is_enabled('manual')) {
1736                 $this->set_mapping('enrol', $oldid, 0);
1737                 return;
1738             }
1739             if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
1740                 $instance = reset($instances);
1741                 $this->set_mapping('enrol', $oldid, $instance->id);
1742             } else {
1743                 if ($data->enrol === 'manual') {
1744                     $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
1745                 } else {
1746                     $instanceid = $this->plugins['manual']->add_default_instance($courserec);
1747                 }
1748                 $this->set_mapping('enrol', $oldid, $instanceid);
1749             }
1751         } else {
1752             if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
1753                 $this->set_mapping('enrol', $oldid, 0);
1754                 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments";
1755                 debugging($message);
1756                 $this->log($message, backup::LOG_WARNING);
1757                 return;
1758             }
1759             if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
1760                 // Let's keep the sortorder in old backups.
1761             } else {
1762                 // Prevent problems with colliding sortorders in old backups,
1763                 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
1764                 unset($data->sortorder);
1765             }
1766             // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
1767             $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
1768         }
1769     }
1771     /**
1772      * Create user enrolments.
1773      *
1774      * This has to be called after creation of enrolment instances
1775      * and before adding of role assignments.
1776      *
1777      * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
1778      *
1779      * @param mixed $data
1780      * @return void
1781      */
1782     public function process_enrolment($data) {
1783         global $DB;
1785         if (!isset($this->plugins)) {
1786             $this->plugins = enrol_get_plugins(true);
1787         }
1789         $data = (object)$data;
1791         // Process only if parent instance have been mapped.
1792         if ($enrolid = $this->get_new_parentid('enrol')) {
1793             $oldinstancestatus = ENROL_INSTANCE_ENABLED;
1794             $oldenrolid = $this->get_old_parentid('enrol');
1795             if (isset($this->originalstatus[$oldenrolid])) {
1796                 $oldinstancestatus = $this->originalstatus[$oldenrolid];
1797             }
1798             if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1799                 // And only if user is a mapped one.
1800                 if ($userid = $this->get_mappingid('user', $data->userid)) {
1801                     if (isset($this->plugins[$instance->enrol])) {
1802                         $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
1803                     }
1804                 }
1805             }
1806         }
1807     }
1811 /**
1812  * Make sure the user restoring the course can actually access it.
1813  */
1814 class restore_fix_restorer_access_step extends restore_execution_step {
1815     protected function define_execution() {
1816         global $CFG, $DB;
1818         if (!$userid = $this->task->get_userid()) {
1819             return;
1820         }
1822         if (empty($CFG->restorernewroleid)) {
1823             // Bad luck, no fallback role for restorers specified
1824             return;
1825         }
1827         $courseid = $this->get_courseid();
1828         $context = context_course::instance($courseid);
1830         if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1831             // Current user may access the course (admin, category manager or restored teacher enrolment usually)
1832             return;
1833         }
1835         // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
1836         role_assign($CFG->restorernewroleid, $userid, $context);
1838         if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
1839             // Extra role is enough, yay!
1840             return;
1841         }
1843         // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
1844         // hopefully admin selected suitable $CFG->restorernewroleid ...
1845         if (!enrol_is_enabled('manual')) {
1846             return;
1847         }
1848         if (!$enrol = enrol_get_plugin('manual')) {
1849             return;
1850         }
1851         if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
1852             $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
1853             $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
1854             $enrol->add_instance($course, $fields);
1855         }
1857         enrol_try_internal_enrol($courseid, $userid);
1858     }
1862 /**
1863  * This structure steps restores the filters and their configs
1864  */
1865 class restore_filters_structure_step extends restore_structure_step {
1867     protected function define_structure() {
1869         $paths = array();
1871         $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1872         $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1874         return $paths;
1875     }
1877     public function process_active($data) {
1879         $data = (object)$data;
1881         if (strpos($data->filter, 'filter/') === 0) {
1882             $data->filter = substr($data->filter, 7);
1884         } else if (strpos($data->filter, '/') !== false) {
1885             // Unsupported old filter.
1886             return;
1887         }
1889         if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1890             return;
1891         }
1892         filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1893     }
1895     public function process_config($data) {
1897         $data = (object)$data;
1899         if (strpos($data->filter, 'filter/') === 0) {
1900             $data->filter = substr($data->filter, 7);
1902         } else if (strpos($data->filter, '/') !== false) {
1903             // Unsupported old filter.
1904             return;
1905         }
1907         if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1908             return;
1909         }
1910         filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1911     }
1915 /**
1916  * This structure steps restores the comments
1917  * Note: Cannot use the comments API because defaults to USER->id.
1918  * That should change allowing to pass $userid
1919  */
1920 class restore_comments_structure_step extends restore_structure_step {
1922     protected function define_structure() {
1924         $paths = array();
1926         $paths[] = new restore_path_element('comment', '/comments/comment');
1928         return $paths;
1929     }
1931     public function process_comment($data) {
1932         global $DB;
1934         $data = (object)$data;
1936         // First of all, if the comment has some itemid, ask to the task what to map
1937         $mapping = false;
1938         if ($data->itemid) {
1939             $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1940             $data->itemid = $this->get_mappingid($mapping, $data->itemid);
1941         }
1942         // Only restore the comment if has no mapping OR we have found the matching mapping
1943         if (!$mapping || $data->itemid) {
1944             // Only if user mapping and context
1945             $data->userid = $this->get_mappingid('user', $data->userid);
1946             if ($data->userid && $this->task->get_contextid()) {
1947                 $data->contextid = $this->task->get_contextid();
1948                 // Only if there is another comment with same context/user/timecreated
1949                 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1950                 if (!$DB->record_exists('comments', $params)) {
1951                     $DB->insert_record('comments', $data);
1952                 }
1953             }
1954         }
1955     }
1958 /**
1959  * This structure steps restores the badges and their configs
1960  */
1961 class restore_badges_structure_step extends restore_structure_step {
1963     /**
1964      * Conditionally decide if this step should be executed.
1965      *
1966      * This function checks the following parameters:
1967      *
1968      *   1. Badges and course badges are enabled on the site.
1969      *   2. The course/badges.xml file exists.
1970      *   3. All modules are restorable.
1971      *   4. All modules are marked for restore.
1972      *
1973      * @return bool True is safe to execute, false otherwise
1974      */
1975     protected function execute_condition() {
1976         global $CFG;
1978         // First check is badges and course level badges are enabled on this site.
1979         if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
1980             // Disabled, don't restore course badges.
1981             return false;
1982         }
1984         // Check if badges.xml is included in the backup.
1985         $fullpath = $this->task->get_taskbasepath();
1986         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1987         if (!file_exists($fullpath)) {
1988             // Not found, can't restore course badges.
1989             return false;
1990         }
1992         // Check we are able to restore all backed up modules.
1993         if ($this->task->is_missing_modules()) {
1994             return false;
1995         }
1997         // Finally check all modules within the backup are being restored.
1998         if ($this->task->is_excluding_activities()) {
1999             return false;
2000         }
2002         return true;
2003     }
2005     protected function define_structure() {
2006         $paths = array();
2007         $paths[] = new restore_path_element('badge', '/badges/badge');
2008         $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2009         $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2010         $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2012         return $paths;
2013     }
2015     public function process_badge($data) {
2016         global $DB, $CFG;
2018         require_once($CFG->libdir . '/badgeslib.php');
2020         $data = (object)$data;
2021         $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2022         $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2024         // We'll restore the badge image.
2025         $restorefiles = true;
2027         $courseid = $this->get_courseid();
2029         $params = array(
2030                 'name'           => $data->name,
2031                 'description'    => $data->description,
2032                 'timecreated'    => $this->apply_date_offset($data->timecreated),
2033                 'timemodified'   => $this->apply_date_offset($data->timemodified),
2034                 'usercreated'    => $data->usercreated,
2035                 'usermodified'   => $data->usermodified,
2036                 'issuername'     => $data->issuername,
2037                 'issuerurl'      => $data->issuerurl,
2038                 'issuercontact'  => $data->issuercontact,
2039                 'expiredate'     => $this->apply_date_offset($data->expiredate),
2040                 'expireperiod'   => $data->expireperiod,
2041                 'type'           => BADGE_TYPE_COURSE,
2042                 'courseid'       => $courseid,
2043                 'message'        => $data->message,
2044                 'messagesubject' => $data->messagesubject,
2045                 'attachment'     => $data->attachment,
2046                 'notification'   => $data->notification,
2047                 'status'         => BADGE_STATUS_INACTIVE,
2048                 'nextcron'       => $this->apply_date_offset($data->nextcron)
2049         );
2051         $newid = $DB->insert_record('badge', $params);
2052         $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2053     }
2055     public function process_criterion($data) {
2056         global $DB;
2058         $data = (object)$data;
2060         $params = array(
2061                 'badgeid'      => $this->get_new_parentid('badge'),
2062                 'criteriatype' => $data->criteriatype,
2063                 'method'       => $data->method
2064         );
2065         $newid = $DB->insert_record('badge_criteria', $params);
2066         $this->set_mapping('criterion', $data->id, $newid);
2067     }
2069     public function process_parameter($data) {
2070         global $DB, $CFG;
2072         require_once($CFG->libdir . '/badgeslib.php');
2074         $data = (object)$data;
2075         $criteriaid = $this->get_new_parentid('criterion');
2077         // Parameter array that will go to database.
2078         $params = array();
2079         $params['critid'] = $criteriaid;
2081         $oldparam = explode('_', $data->name);
2083         if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2084             $module = $this->get_mappingid('course_module', $oldparam[1]);
2085             $params['name'] = $oldparam[0] . '_' . $module;
2086             $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2087         } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2088             $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2089             $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2090         } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2091             $role = $this->get_mappingid('role', $data->value);
2092             if (!empty($role)) {
2093                 $params['name'] = 'role_' . $role;
2094                 $params['value'] = $role;
2095             } else {
2096                 return;
2097             }
2098         }
2100         if (!$DB->record_exists('badge_criteria_param', $params)) {
2101             $DB->insert_record('badge_criteria_param', $params);
2102         }
2103     }
2105     public function process_manual_award($data) {
2106         global $DB;
2108         $data = (object)$data;
2109         $role = $this->get_mappingid('role', $data->issuerrole);
2111         if (!empty($role)) {
2112             $award = array(
2113                 'badgeid'     => $this->get_new_parentid('badge'),
2114                 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2115                 'issuerid'    => $this->get_mappingid('user', $data->issuerid),
2116                 'issuerrole'  => $role,
2117                 'datemet'     => $this->apply_date_offset($data->datemet)
2118             );
2119             $DB->insert_record('badge_manual_award', $award);
2120         }
2121     }
2123     protected function after_execute() {
2124         // Add related files.
2125         $this->add_related_files('badges', 'badgeimage', 'badge');
2126     }
2129 /**
2130  * This structure steps restores the calendar events
2131  */
2132 class restore_calendarevents_structure_step extends restore_structure_step {
2134     protected function define_structure() {
2136         $paths = array();
2138         $paths[] = new restore_path_element('calendarevents', '/events/event');
2140         return $paths;
2141     }
2143     public function process_calendarevents($data) {
2144         global $DB, $SITE;
2146         $data = (object)$data;
2147         $oldid = $data->id;
2148         $restorefiles = true; // We'll restore the files
2149         // Find the userid and the groupid associated with the event. Return if not found.
2150         $data->userid = $this->get_mappingid('user', $data->userid);
2151         if ($data->userid === false) {
2152             return;
2153         }
2154         if (!empty($data->groupid)) {
2155             $data->groupid = $this->get_mappingid('group', $data->groupid);
2156             if ($data->groupid === false) {
2157                 return;
2158             }
2159         }
2160         // Handle events with empty eventtype //MDL-32827
2161         if(empty($data->eventtype)) {
2162             if ($data->courseid == $SITE->id) {                                // Site event
2163                 $data->eventtype = "site";
2164             } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2165                 // Course assingment event
2166                 $data->eventtype = "due";
2167             } else if ($data->courseid != 0 && $data->groupid == 0) {      // Course event
2168                 $data->eventtype = "course";
2169             } else if ($data->groupid) {                                      // Group event
2170                 $data->eventtype = "group";
2171             } else if ($data->userid) {                                       // User event
2172                 $data->eventtype = "user";
2173             } else {
2174                 return;
2175             }
2176         }
2178         $params = array(
2179                 'name'           => $data->name,
2180                 'description'    => $data->description,
2181                 'format'         => $data->format,
2182                 'courseid'       => $this->get_courseid(),
2183                 'groupid'        => $data->groupid,
2184                 'userid'         => $data->userid,
2185                 'repeatid'       => $data->repeatid,
2186                 'modulename'     => $data->modulename,
2187                 'eventtype'      => $data->eventtype,
2188                 'timestart'      => $this->apply_date_offset($data->timestart),
2189                 'timeduration'   => $data->timeduration,
2190                 'visible'        => $data->visible,
2191                 'uuid'           => $data->uuid,
2192                 'sequence'       => $data->sequence,
2193                 'timemodified'    => $this->apply_date_offset($data->timemodified));
2194         if ($this->name == 'activity_calendar') {
2195             $params['instance'] = $this->task->get_activityid();
2196         } else {
2197             $params['instance'] = 0;
2198         }
2199         $sql = 'SELECT id FROM {event} WHERE name = ? AND courseid = ? AND
2200                 repeatid = ? AND modulename = ? AND timestart = ? AND timeduration =?
2201                 AND ' . $DB->sql_compare_text('description', 255) . ' = ' . $DB->sql_compare_text('?', 255);
2202         $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
2203         $result = $DB->record_exists_sql($sql, $arg);
2204         if (empty($result)) {
2205             $newitemid = $DB->insert_record('event', $params);
2206             $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2207         }
2209     }
2210     protected function after_execute() {
2211         // Add related files
2212         $this->add_related_files('calendar', 'event_description', 'event_description');
2213     }
2216 class restore_course_completion_structure_step extends restore_structure_step {
2218     /**
2219      * Conditionally decide if this step should be executed.
2220      *
2221      * This function checks parameters that are not immediate settings to ensure
2222      * that the enviroment is suitable for the restore of course completion info.
2223      *
2224      * This function checks the following four parameters:
2225      *
2226      *   1. Course completion is enabled on the site
2227      *   2. The backup includes course completion information
2228      *   3. All modules are restorable
2229      *   4. All modules are marked for restore.
2230      *
2231      * @return bool True is safe to execute, false otherwise
2232      */
2233     protected function execute_condition() {
2234         global $CFG;
2236         // First check course completion is enabled on this site
2237         if (empty($CFG->enablecompletion)) {
2238             // Disabled, don't restore course completion
2239             return false;
2240         }
2242         // Check it is included in the backup
2243         $fullpath = $this->task->get_taskbasepath();
2244         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2245         if (!file_exists($fullpath)) {
2246             // Not found, can't restore course completion
2247             return false;
2248         }
2250         // Check we are able to restore all backed up modules
2251         if ($this->task->is_missing_modules()) {
2252             return false;
2253         }
2255         // Finally check all modules within the backup are being restored.
2256         if ($this->task->is_excluding_activities()) {
2257             return false;
2258         }
2260         return true;
2261     }
2263     /**
2264      * Define the course completion structure
2265      *
2266      * @return array Array of restore_path_element
2267      */
2268     protected function define_structure() {
2270         // To know if we are including user completion info
2271         $userinfo = $this->get_setting_value('userscompletion');
2273         $paths = array();
2274         $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2275         $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2277         if ($userinfo) {
2278             $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2279             $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2280         }
2282         return $paths;
2284     }
2286     /**
2287      * Process course completion criteria
2288      *
2289      * @global moodle_database $DB
2290      * @param stdClass $data
2291      */
2292     public function process_course_completion_criteria($data) {
2293         global $DB;
2295         $data = (object)$data;
2296         $data->course = $this->get_courseid();
2298         // Apply the date offset to the time end field
2299         $data->timeend = $this->apply_date_offset($data->timeend);
2301         // Map the role from the criteria
2302         if (!empty($data->role)) {
2303             $data->role = $this->get_mappingid('role', $data->role);
2304         }
2306         $skipcriteria = false;
2308         // If the completion criteria is for a module we need to map the module instance
2309         // to the new module id.
2310         if (!empty($data->moduleinstance) && !empty($data->module)) {
2311             $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
2312             if (empty($data->moduleinstance)) {
2313                 $skipcriteria = true;
2314             }
2315         } else {
2316             $data->module = null;
2317             $data->moduleinstance = null;
2318         }
2320         // We backup the course shortname rather than the ID so that we can match back to the course
2321         if (!empty($data->courseinstanceshortname)) {
2322             $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
2323             if (!$courseinstanceid) {
2324                 $skipcriteria = true;
2325             }
2326         } else {
2327             $courseinstanceid = null;
2328         }
2329         $data->courseinstance = $courseinstanceid;
2331         if (!$skipcriteria) {
2332             $params = array(
2333                 'course'         => $data->course,
2334                 'criteriatype'   => $data->criteriatype,
2335                 'enrolperiod'    => $data->enrolperiod,
2336                 'courseinstance' => $data->courseinstance,
2337                 'module'         => $data->module,
2338                 'moduleinstance' => $data->moduleinstance,
2339                 'timeend'        => $data->timeend,
2340                 'gradepass'      => $data->gradepass,
2341                 'role'           => $data->role
2342             );
2343             $newid = $DB->insert_record('course_completion_criteria', $params);
2344             $this->set_mapping('course_completion_criteria', $data->id, $newid);
2345         }
2346     }
2348     /**
2349      * Processes course compltion criteria complete records
2350      *
2351      * @global moodle_database $DB
2352      * @param stdClass $data
2353      */
2354     public function process_course_completion_crit_compl($data) {
2355         global $DB;
2357         $data = (object)$data;
2359         // This may be empty if criteria could not be restored
2360         $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
2362         $data->course = $this->get_courseid();
2363         $data->userid = $this->get_mappingid('user', $data->userid);
2365         if (!empty($data->criteriaid) && !empty($data->userid)) {
2366             $params = array(
2367                 'userid' => $data->userid,
2368                 'course' => $data->course,
2369                 'criteriaid' => $data->criteriaid,
2370                 'timecompleted' => $this->apply_date_offset($data->timecompleted)
2371             );
2372             if (isset($data->gradefinal)) {
2373                 $params['gradefinal'] = $data->gradefinal;
2374             }
2375             if (isset($data->unenroled)) {
2376                 $params['unenroled'] = $data->unenroled;
2377             }
2378             $DB->insert_record('course_completion_crit_compl', $params);
2379         }
2380     }
2382     /**
2383      * Process course completions
2384      *
2385      * @global moodle_database $DB
2386      * @param stdClass $data
2387      */
2388     public function process_course_completions($data) {
2389         global $DB;
2391         $data = (object)$data;
2393         $data->course = $this->get_courseid();
2394         $data->userid = $this->get_mappingid('user', $data->userid);
2396         if (!empty($data->userid)) {
2397             $params = array(
2398                 'userid' => $data->userid,
2399                 'course' => $data->course,
2400                 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
2401                 'timestarted' => $this->apply_date_offset($data->timestarted),
2402                 'timecompleted' => $this->apply_date_offset($data->timecompleted),
2403                 'reaggregate' => $data->reaggregate
2404             );
2405             $DB->insert_record('course_completions', $params);
2406         }
2407     }
2409     /**
2410      * Process course completion aggregate methods
2411      *
2412      * @global moodle_database $DB
2413      * @param stdClass $data
2414      */
2415     public function process_course_completion_aggr_methd($data) {
2416         global $DB;
2418         $data = (object)$data;
2420         $data->course = $this->get_courseid();
2422         // Only create the course_completion_aggr_methd records if
2423         // the target course has not them defined. MDL-28180
2424         if (!$DB->record_exists('course_completion_aggr_methd', array(
2425                     'course' => $data->course,
2426                     'criteriatype' => $data->criteriatype))) {
2427             $params = array(
2428                 'course' => $data->course,
2429                 'criteriatype' => $data->criteriatype,
2430                 'method' => $data->method,
2431                 'value' => $data->value,
2432             );
2433             $DB->insert_record('course_completion_aggr_methd', $params);
2434         }
2435     }
2439 /**
2440  * This structure step restores course logs (cmid = 0), delegating
2441  * the hard work to the corresponding {@link restore_logs_processor} passing the
2442  * collection of {@link restore_log_rule} rules to be observed as they are defined
2443  * by the task. Note this is only executed based in the 'logs' setting.
2444  *
2445  * NOTE: This is executed by final task, to have all the activities already restored
2446  *
2447  * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2448  * records are. There are others like 'calendar' and 'upload' that will be handled
2449  * later.
2450  *
2451  * NOTE: All the missing actions (not able to be restored) are sent to logs for
2452  * debugging purposes
2453  */
2454 class restore_course_logs_structure_step extends restore_structure_step {
2456     /**
2457      * Conditionally decide if this step should be executed.
2458      *
2459      * This function checks the following parameter:
2460      *
2461      *   1. the course/logs.xml file exists
2462      *
2463      * @return bool true is safe to execute, false otherwise
2464      */
2465     protected function execute_condition() {
2467         // Check it is included in the backup
2468         $fullpath = $this->task->get_taskbasepath();
2469         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2470         if (!file_exists($fullpath)) {
2471             // Not found, can't restore course logs
2472             return false;
2473         }
2475         return true;
2476     }
2478     protected function define_structure() {
2480         $paths = array();
2482         // Simple, one plain level of information contains them
2483         $paths[] = new restore_path_element('log', '/logs/log');
2485         return $paths;
2486     }
2488     protected function process_log($data) {
2489         global $DB;
2491         $data = (object)($data);
2493         $data->time = $this->apply_date_offset($data->time);
2494         $data->userid = $this->get_mappingid('user', $data->userid);
2495         $data->course = $this->get_courseid();
2496         $data->cmid = 0;
2498         // For any reason user wasn't remapped ok, stop processing this
2499         if (empty($data->userid)) {
2500             return;
2501         }
2503         // Everything ready, let's delegate to the restore_logs_processor
2505         // Set some fixed values that will save tons of DB requests
2506         $values = array(
2507             'course' => $this->get_courseid());
2508         // Get instance and process log record
2509         $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2511         // If we have data, insert it, else something went wrong in the restore_logs_processor
2512         if ($data) {
2513             $DB->insert_record('log', $data);
2514         }
2515     }
2518 /**
2519  * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2520  * sharing its same structure but modifying the way records are handled
2521  */
2522 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2524     protected function process_log($data) {
2525         global $DB;
2527         $data = (object)($data);
2529         $data->time = $this->apply_date_offset($data->time);
2530         $data->userid = $this->get_mappingid('user', $data->userid);
2531         $data->course = $this->get_courseid();
2532         $data->cmid = $this->task->get_moduleid();
2534         // For any reason user wasn't remapped ok, stop processing this
2535         if (empty($data->userid)) {
2536             return;
2537         }
2539         // Everything ready, let's delegate to the restore_logs_processor
2541         // Set some fixed values that will save tons of DB requests
2542         $values = array(
2543             'course' => $this->get_courseid(),
2544             'course_module' => $this->task->get_moduleid(),
2545             $this->task->get_modulename() => $this->task->get_activityid());
2546         // Get instance and process log record
2547         $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2549         // If we have data, insert it, else something went wrong in the restore_logs_processor
2550         if ($data) {
2551             $DB->insert_record('log', $data);
2552         }
2553     }
2557 /**
2558  * Defines the restore step for advanced grading methods attached to the activity module
2559  */
2560 class restore_activity_grading_structure_step extends restore_structure_step {
2562     /**
2563      * This step is executed only if the grading file is present
2564      */
2565      protected function execute_condition() {
2567         $fullpath = $this->task->get_taskbasepath();
2568         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2569         if (!file_exists($fullpath)) {
2570             return false;
2571         }
2573         return true;
2574     }
2577     /**
2578      * Declares paths in the grading.xml file we are interested in
2579      */
2580     protected function define_structure() {
2582         $paths = array();
2583         $userinfo = $this->get_setting_value('userinfo');
2585         $area = new restore_path_element('grading_area', '/areas/area');
2586         $paths[] = $area;
2587         // attach local plugin stucture to $area element
2588         $this->add_plugin_structure('local', $area);
2590         $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
2591         $paths[] = $definition;
2592         $this->add_plugin_structure('gradingform', $definition);
2593         // attach local plugin stucture to $definition element
2594         $this->add_plugin_structure('local', $definition);
2597         if ($userinfo) {
2598             $instance = new restore_path_element('grading_instance',
2599                 '/areas/area/definitions/definition/instances/instance');
2600             $paths[] = $instance;
2601             $this->add_plugin_structure('gradingform', $instance);
2602             // attach local plugin stucture to $intance element
2603             $this->add_plugin_structure('local', $instance);
2604         }
2606         return $paths;
2607     }
2609     /**
2610      * Processes one grading area element
2611      *
2612      * @param array $data element data
2613      */
2614     protected function process_grading_area($data) {
2615         global $DB;
2617         $task = $this->get_task();
2618         $data = (object)$data;
2619         $oldid = $data->id;
2620         $data->component = 'mod_'.$task->get_modulename();
2621         $data->contextid = $task->get_contextid();
2623         $newid = $DB->insert_record('grading_areas', $data);
2624         $this->set_mapping('grading_area', $oldid, $newid);
2625     }
2627     /**
2628      * Processes one grading definition element
2629      *
2630      * @param array $data element data
2631      */
2632     protected function process_grading_definition($data) {
2633         global $DB;
2635         $task = $this->get_task();
2636         $data = (object)$data;
2637         $oldid = $data->id;
2638         $data->areaid = $this->get_new_parentid('grading_area');
2639         $data->copiedfromid = null;
2640         $data->timecreated = time();
2641         $data->usercreated = $task->get_userid();
2642         $data->timemodified = $data->timecreated;
2643         $data->usermodified = $data->usercreated;
2645         $newid = $DB->insert_record('grading_definitions', $data);
2646         $this->set_mapping('grading_definition', $oldid, $newid, true);
2647     }
2649     /**
2650      * Processes one grading form instance element
2651      *
2652      * @param array $data element data
2653      */
2654     protected function process_grading_instance($data) {
2655         global $DB;
2657         $data = (object)$data;
2659         // new form definition id
2660         $newformid = $this->get_new_parentid('grading_definition');
2662         // get the name of the area we are restoring to
2663         $sql = "SELECT ga.areaname
2664                   FROM {grading_definitions} gd
2665                   JOIN {grading_areas} ga ON gd.areaid = ga.id
2666                  WHERE gd.id = ?";
2667         $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
2669         // get the mapped itemid - the activity module is expected to define the mappings
2670         // for each gradable area
2671         $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
2673         $oldid = $data->id;
2674         $data->definitionid = $newformid;
2675         $data->raterid = $this->get_mappingid('user', $data->raterid);
2676         $data->itemid = $newitemid;
2678         $newid = $DB->insert_record('grading_instances', $data);
2679         $this->set_mapping('grading_instance', $oldid, $newid);
2680     }
2682     /**
2683      * Final operations when the database records are inserted
2684      */
2685     protected function after_execute() {
2686         // Add files embedded into the definition description
2687         $this->add_related_files('grading', 'description', 'grading_definition');
2688     }
2692 /**
2693  * This structure step restores the grade items associated with one activity
2694  * All the grade items are made child of the "course" grade item but the original
2695  * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
2696  * the complete gradebook (categories and calculations), that information is
2697  * available there
2698  */
2699 class restore_activity_grades_structure_step extends restore_structure_step {
2701     protected function define_structure() {
2703         $paths = array();
2704         $userinfo = $this->get_setting_value('userinfo');
2706         $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
2707         $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
2708         if ($userinfo) {
2709             $paths[] = new restore_path_element('grade_grade',
2710                            '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
2711         }
2712         return $paths;
2713     }
2715     protected function process_grade_item($data) {
2716         global $DB;
2718         $data = (object)($data);
2719         $oldid       = $data->id;        // We'll need these later
2720         $oldparentid = $data->categoryid;
2721         $courseid = $this->get_courseid();
2723         // make sure top course category exists, all grade items will be associated
2724         // to it. Later, if restoring the whole gradebook, categories will be introduced
2725         $coursecat = grade_category::fetch_course_category($courseid);
2726         $coursecatid = $coursecat->id; // Get the categoryid to be used
2728         $idnumber = null;
2729         if (!empty($data->idnumber)) {
2730             // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
2731             // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
2732             // so the best is to keep the ones already in the gradebook
2733             // Potential problem: duplicates if same items are restored more than once. :-(
2734             // This needs to be fixed in some way (outcomes & activities with multiple items)
2735             // $data->idnumber     = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
2736             // In any case, verify always for uniqueness
2737             $sql = "SELECT cm.id
2738                       FROM {course_modules} cm
2739                      WHERE cm.course = :courseid AND
2740                            cm.idnumber = :idnumber AND
2741                            cm.id <> :cmid";
2742             $params = array(
2743                 'courseid' => $courseid,
2744                 'idnumber' => $data->idnumber,
2745                 'cmid' => $this->task->get_moduleid()
2746             );
2747             if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
2748                 $idnumber = $data->idnumber;
2749             }
2750         }
2752         unset($data->id);
2753         $data->categoryid   = $coursecatid;
2754         $data->courseid     = $this->get_courseid();
2755         $data->iteminstance = $this->task->get_activityid();
2756         $data->idnumber     = $idnumber;
2757         $data->scaleid      = $this->get_mappingid('scale', $data->scaleid);
2758         $data->outcomeid    = $this->get_mappingid('outcome', $data->outcomeid);
2759         $data->timecreated  = $this->apply_date_offset($data->timecreated);
2760         $data->timemodified = $this->apply_date_offset($data->timemodified);
2762         $gradeitem = new grade_item($data, false);
2763         $gradeitem->insert('restore');
2765         //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
2766         $gradeitem->sortorder = $data->sortorder;
2767         $gradeitem->update('restore');
2769         // Set mapping, saving the original category id into parentitemid
2770         // gradebook restore (final task) will need it to reorganise items
2771         $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
2772     }
2774     protected function process_grade_grade($data) {
2775         $data = (object)($data);
2776         $olduserid = $data->userid;
2777         unset($data->id);
2779         $data->itemid = $this->get_new_parentid('grade_item');
2781         $data->userid = $this->get_mappingid('user', $data->userid, null);
2782         if (!empty($data->userid)) {
2783             $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
2784             $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
2785             // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
2786             $data->overridden = $this->apply_date_offset($data->overridden);
2788             $grade = new grade_grade($data, false);
2789             $grade->insert('restore');
2790             // no need to save any grade_grade mapping
2791         } else {
2792             debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
2793         }
2794     }
2796     /**
2797      * process activity grade_letters. Note that, while these are possible,
2798      * because grade_letters are contextid based, in practice, only course
2799      * context letters can be defined. So we keep here this method knowing
2800      * it won't be executed ever. gradebook restore will restore course letters.
2801      */
2802     protected function process_grade_letter($data) {
2803         global $DB;
2805         $data['contextid'] = $this->task->get_contextid();
2806         $gradeletter = (object)$data;
2808         // Check if it exists before adding it
2809         unset($data['id']);
2810         if (!$DB->record_exists('grade_letters', $data)) {
2811             $newitemid = $DB->insert_record('grade_letters', $gradeletter);
2812         }
2813         // no need to save any grade_letter mapping
2814     }
2818 /**
2819  * This structure steps restores one instance + positions of one block
2820  * Note: Positions corresponding to one existing context are restored
2821  * here, but all the ones having unknown contexts are sent to backup_ids
2822  * for a later chance to be restored at the end (final task)
2823  */
2824 class restore_block_instance_structure_step extends restore_structure_step {
2826     protected function define_structure() {
2828         $paths = array();
2830         $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
2831         $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
2833         return $paths;
2834     }
2836     public function process_block($data) {
2837         global $DB, $CFG;
2839         $data = (object)$data; // Handy
2840         $oldcontextid = $data->contextid;
2841         $oldid        = $data->id;
2842         $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
2844         // Look for the parent contextid
2845         if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
2846             throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
2847         }
2849         // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
2850         // If there is already one block of that type in the parent context
2851         // and the block is not multiple, stop processing
2852         // Use blockslib loader / method executor
2853         if (!$bi = block_instance($data->blockname)) {
2854             return false;
2855         }
2857         if (!$bi->instance_allow_multiple()) {
2858             if ($DB->record_exists_sql("SELECT bi.id
2859                                           FROM {block_instances} bi
2860                                           JOIN {block} b ON b.name = bi.blockname
2861                                          WHERE bi.parentcontextid = ?
2862                                            AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
2863                 return false;
2864             }
2865         }
2867         // If there is already one block of that type in the parent context
2868         // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
2869         // stop processing
2870         $params = array(
2871             'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
2872             'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
2873             'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
2874         if ($birecs = $DB->get_records('block_instances', $params)) {
2875             foreach($birecs as $birec) {
2876                 if ($birec->configdata == $data->configdata) {
2877                     return false;
2878                 }
2879             }
2880         }
2882         // Set task old contextid, blockid and blockname once we know them
2883         $this->task->set_old_contextid($oldcontextid);
2884         $this->task->set_old_blockid($oldid);
2885         $this->task->set_blockname($data->blockname);
2887         // Let's look for anything within configdata neededing processing
2888         // (nulls and uses of legacy file.php)
2889         if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
2890             $configdata = (array)unserialize(base64_decode($data->configdata));
2891             foreach ($configdata as $attribute => $value) {
2892                 if (in_array($attribute, $attrstotransform)) {
2893                     $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
2894                 }
2895             }
2896             $data->configdata = base64_encode(serialize((object)$configdata));
2897         }
2899         // Create the block instance
2900         $newitemid = $DB->insert_record('block_instances', $data);
2901         // Save the mapping (with restorefiles support)
2902         $this->set_mapping('block_instance', $oldid, $newitemid, true);
2903         // Create the block context
2904         $newcontextid = context_block::instance($newitemid)->id;
2905         // Save the block contexts mapping and sent it to task
2906         $this->set_mapping('context', $oldcontextid, $newcontextid);
2907         $this->task->set_contextid($newcontextid);
2908         $this->task->set_blockid($newitemid);
2910         // Restore block fileareas if declared
2911         $component = 'block_' . $this->task->get_blockname();
2912         foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
2913             $this->add_related_files($component, $filearea, null);
2914         }
2916         // Process block positions, creating them or accumulating for final step
2917         foreach($positions as $position) {
2918             $position = (object)$position;
2919             $position->blockinstanceid = $newitemid; // The instance is always the restored one
2920             // If position is for one already mapped (known) contextid
2921             // process it now, creating the position
2922             if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
2923                 $position->contextid = $newpositionctxid;
2924                 // Create the block position
2925                 $DB->insert_record('block_positions', $position);
2927             // The position belongs to an unknown context, send it to backup_ids
2928             // to process them as part of the final steps of restore. We send the
2929             // whole $position object there, hence use the low level method.
2930             } else {
2931                 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
2932             }
2933         }
2934     }
2937 /**
2938  * Structure step to restore common course_module information
2939  *
2940  * This step will process the module.xml file for one activity, in order to restore
2941  * the corresponding information to the course_modules table, skipping various bits
2942  * of information based on CFG settings (groupings, completion...) in order to fullfill
2943  * all the reqs to be able to create the context to be used by all the rest of steps
2944  * in the activity restore task
2945  */
2946 class restore_module_structure_step extends restore_structure_step {
2948     protected function define_structure() {
2949         global $CFG;
2951         $paths = array();
2953         $module = new restore_path_element('module', '/module');
2954         $paths[] = $module;
2955         if ($CFG->enableavailability) {
2956             $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
2957             $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
2958         }
2960         // Apply for 'format' plugins optional paths at module level
2961         $this->add_plugin_structure('format', $module);
2963         // Apply for 'plagiarism' plugins optional paths at module level
2964         $this->add_plugin_structure('plagiarism', $module);
2966         // Apply for 'local' plugins optional paths at module level
2967         $this->add_plugin_structure('local', $module);
2969         return $paths;
2970     }
2972     protected function process_module($data) {
2973         global $CFG, $DB;
2975         $data = (object)$data;
2976         $oldid = $data->id;
2977         $this->task->set_old_moduleversion($data->version);
2979         $data->course = $this->task->get_courseid();
2980         $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
2981         // Map section (first try by course_section mapping match. Useful in course and section restores)
2982         $data->section = $this->get_mappingid('course_section', $data->sectionid);
2983         if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
2984             $params = array(
2985                 'course' => $this->get_courseid(),
2986                 'section' => $data->sectionnumber);
2987             $data->section = $DB->get_field('course_sections', 'id', $params);
2988         }
2989         if (!$data->section) { // sectionnumber failed, try to get first section in course
2990             $params = array(
2991                 'course' => $this->get_courseid());
2992             $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
2993         }
2994         if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
2995             $sectionrec = array(
2996                 'course' => $this->get_courseid(),
2997                 'section' => 0);
2998             $DB->insert_record('course_sections', $sectionrec); // section 0
2999             $sectionrec = array(
3000                 'course' => $this->get_courseid(),
3001                 'section' => 1);
3002             $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
3003         }
3004         $data->groupingid= $this->get_mappingid('grouping', $data->groupingid);      // grouping
3005         if (!$CFG->enablegroupmembersonly) {                                         // observe groupsmemberonly
3006             $data->groupmembersonly = 0;
3007         }
3008         if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) {        // idnumber uniqueness
3009             $data->idnumber = '';
3010         }
3011         if (empty($CFG->enablecompletion)) { // completion
3012             $data->completion = 0;
3013             $data->completiongradeitemnumber = null;
3014             $data->completionview = 0;
3015             $data->completionexpected = 0;
3016         } else {
3017             $data->completionexpected = $this->apply_date_offset($data->completionexpected);
3018         }
3019         if (empty($CFG->enableavailability)) {
3020             $data->availablefrom = 0;
3021             $data->availableuntil = 0;
3022             $data->showavailability = 0;
3023         } else {
3024             $data->availablefrom = $this->apply_date_offset($data->availablefrom);
3025             $data->availableuntil= $this->apply_date_offset($data->availableuntil);
3026         }
3027         // Backups that did not include showdescription, set it to default 0
3028         // (this is not totally necessary as it has a db default, but just to
3029         // be explicit).
3030         if (!isset($data->showdescription)) {
3031             $data->showdescription = 0;
3032         }
3033         $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
3035         // course_module record ready, insert it
3036         $newitemid = $DB->insert_record('course_modules', $data);
3037         // save mapping
3038         $this->set_mapping('course_module', $oldid, $newitemid);
3039         // set the new course_module id in the task
3040         $this->task->set_moduleid($newitemid);
3041         // we can now create the context safely
3042         $ctxid = context_module::instance($newitemid)->id;
3043         // set the new context id in the task
3044         $this->task->set_contextid($ctxid);
3045         // update sequence field in course_section
3046         if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
3047             $sequence .= ',' . $newitemid;
3048         } else {
3049             $sequence = $newitemid;
3050         }
3051         $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
3052     }
3054     protected function process_availability($data) {
3055         $data = (object)$data;
3056         // Simply going to store the whole availability record now, we'll process
3057         // all them later in the final task (once all activities have been restored)
3058         // Let's call the low level one to be able to store the whole object
3059         $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
3060         restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
3061     }
3063     protected function process_availability_field($data) {
3064         global $DB;
3065         $data = (object)$data;
3066         // Mark it is as passed by default
3067         $passed = true;
3068         $customfieldid = null;
3070         // If a customfield has been used in order to pass we must be able to match an existing
3071         // customfield by name (data->customfield) and type (data->customfieldtype)
3072         if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
3073             // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
3074             // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
3075             $passed = false;
3076         } else if (!empty($data->customfield)) {
3077             $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
3078             $customfieldid = $DB->get_field('user_info_field', 'id', $params);
3079             $passed = ($customfieldid !== false);
3080         }
3082         if ($passed) {
3083             // Create the object to insert into the database
3084             $availfield = new stdClass();
3085             $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
3086             $availfield->userfield = $data->userfield;
3087             $availfield->customfieldid = $customfieldid;
3088             $availfield->operator = $data->operator;
3089             $availfield->value = $data->value;
3090             // Insert into the database
3091             $DB->insert_record('course_modules_avail_fields', $availfield);
3092         }
3093     }
3096 /**
3097  * Structure step that will process the user activity completion
3098  * information if all these conditions are met:
3099  *  - Target site has completion enabled ($CFG->enablecompletion)
3100  *  - Activity includes completion info (file_exists)
3101  */
3102 class restore_userscompletion_structure_step extends restore_structure_step {
3103     /**
3104      * To conditionally decide if this step must be executed
3105      * Note the "settings" conditions are evaluated in the
3106      * corresponding task. Here we check for other conditions
3107      * not being restore settings (files, site settings...)
3108      */
3109      protected function execute_condition() {
3110          global $CFG;
3112          // Completion disabled in this site, don't execute
3113          if (empty($CFG->enablecompletion)) {
3114              return false;
3115          }
3117          // No user completion info found, don't execute
3118         $fullpath = $this->task->get_taskbasepath();
3119         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3120          if (!file_exists($fullpath)) {
3121              return false;
3122          }
3124          // Arrived here, execute the step
3125          return true;
3126      }
3128      protected function define_structure() {
3130         $paths = array();
3132         $paths[] = new restore_path_element('completion', '/completions/completion');
3134         return $paths;
3135     }
3137     protected function process_completion($data) {
3138         global $DB;
3140         $data = (object)$data;
3142         $data->coursemoduleid = $this->task->get_moduleid();
3143         $data->userid = $this->get_mappingid('user', $data->userid);
3144         $data->timemodified = $this->apply_date_offset($data->timemodified);
3146         // Find the existing record
3147         $existing = $DB->get_record('course_modules_completion', array(
3148                 'coursemoduleid' => $data->coursemoduleid,
3149                 'userid' => $data->userid), 'id, timemodified');
3150         // Check we didn't already insert one for this cmid and userid
3151         // (there aren't supposed to be duplicates in that field, but
3152         // it was possible until MDL-28021 was fixed).
3153         if ($existing) {
3154             // Update it to these new values, but only if the time is newer
3155             if ($existing->timemodified < $data->timemodified) {
3156                 $data->id = $existing->id;
3157                 $DB->update_record('course_modules_completion', $data);
3158             }
3159         } else {
3160             // Normal entry where it doesn't exist already
3161             $DB->insert_record('course_modules_completion', $data);
3162         }
3163     }
3166 /**
3167  * Abstract structure step, parent of all the activity structure steps. Used to suuport
3168  * the main <activity ...> tag and process it. Also provides subplugin support for
3169  * activities.
3170  */
3171 abstract class restore_activity_structure_step extends restore_structure_step {
3173     protected function add_subplugin_structure($subplugintype, $element) {
3175         global $CFG;
3177         // Check the requested subplugintype is a valid one
3178         $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
3179         if (!file_exists($subpluginsfile)) {
3180              throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
3181         }
3182         include($subpluginsfile);
3183         if (!array_key_exists($subplugintype, $subplugins)) {
3184              throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
3185         }
3186         // Get all the restore path elements, looking across all the subplugin dirs
3187         $subpluginsdirs = core_component::get_plugin_list($subplugintype);
3188         foreach ($subpluginsdirs as $name => $subpluginsdir) {
3189             $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
3190             $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
3191             if (file_exists($restorefile)) {
3192                 require_once($restorefile);
3193                 $restoresubplugin = new $classname($subplugintype, $name, $this);
3194                 // Add subplugin paths to the step
3195                 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
3196             }
3197         }
3198     }
3200     /**
3201      * As far as activity restore steps are implementing restore_subplugin stuff, they need to
3202      * have the parent task available for wrapping purposes (get course/context....)
3203      * @return restore_task
3204      */
3205     public function get_task() {
3206         return $this->task;
3207     }
3209     /**
3210      * Adds support for the 'activity' path that is common to all the activities
3211      * and will be processed globally here
3212      */
3213     protected function prepare_activity_structure($paths) {
3215         $paths[] = new restore_path_element('activity', '/activity');
3217         return $paths;
3218     }
3220     /**
3221      * Process the activity path, informing the task about various ids, needed later
3222      */
3223     protected function process_activity($data) {
3224         $data = (object)$data;
3225         $this->task->set_old_contextid($data->contextid); // Save old contextid in task
3226         $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
3227         $this->task->set_old_activityid($data->id); // Save old activityid in task
3228     }
3230     /**
3231      * This must be invoked immediately after creating the "module" activity record (forum, choice...)
3232      * and will adjust the new activity id (the instance) in various places
3233      */
3234     protected function apply_activity_instance($newitemid) {
3235         global $DB;
3237         $this->task->set_activityid($newitemid); // Save activity id in task
3238         // Apply the id to course_sections->instanceid
3239         $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
3240         // Do the mapping for modulename, preparing it for files by oldcontext
3241         $modulename = $this->task->get_modulename();
3242         $oldid = $this->task->get_old_activityid();
3243         $this->set_mapping($modulename, $oldid, $newitemid, true);
3244     }
3247 /**
3248  * Structure step in charge of creating/mapping all the qcats and qs
3249  * by parsing the questions.xml file and checking it against the
3250  * results calculated by {@link restore_process_categories_and_questions}
3251  * and stored in backup_ids_temp
3252  */
3253 class restore_create_categories_and_questions extends restore_structure_step {
3255     protected function define_structure() {
3257         $category = new restore_path_element('question_category', '/question_categories/question_category');
3258         $question = new restore_path_element('question', '/question_categories/question_category/questions/question');