163ccf92c35f356b670639aaf4c76fb054369ac9
[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         $progress = $this->task->get_progress();
69         $progress->start_progress('Deleting backup dir');
70         backup_helper::delete_old_backup_dirs(strtotime('-1 week'), $progress);      // Delete > 1 week old temp dirs.
71         if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
72             backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir
73         }
74         $progress->end_progress();
75     }
76 }
78 /**
79  * Restore calculated grade items, grade categories etc
80  */
81 class restore_gradebook_structure_step extends restore_structure_step {
83     /**
84      * To conditionally decide if this step must be executed
85      * Note the "settings" conditions are evaluated in the
86      * corresponding task. Here we check for other conditions
87      * not being restore settings (files, site settings...)
88      */
89      protected function execute_condition() {
90         global $CFG, $DB;
92         if ($this->get_courseid() == SITEID) {
93             return false;
94         }
96         // No gradebook info found, don't execute
97         $fullpath = $this->task->get_taskbasepath();
98         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
99         if (!file_exists($fullpath)) {
100             return false;
101         }
103         // Some module present in backup file isn't available to restore
104         // in this site, don't execute
105         if ($this->task->is_missing_modules()) {
106             return false;
107         }
109         // Some activity has been excluded to be restored, don't execute
110         if ($this->task->is_excluding_activities()) {
111             return false;
112         }
114         // There should only be one grade category (the 1 associated with the course itself)
115         // If other categories already exist we're restoring into an existing course.
116         // Restoring categories into a course with an existing category structure is unlikely to go well
117         $category = new stdclass();
118         $category->courseid  = $this->get_courseid();
119         $catcount = $DB->count_records('grade_categories', (array)$category);
120         if ($catcount>1) {
121             return false;
122         }
124         // Arrived here, execute the step
125         return true;
126      }
128     protected function define_structure() {
129         $paths = array();
130         $userinfo = $this->task->get_setting_value('users');
132         $paths[] = new restore_path_element('gradebook', '/gradebook');
133         $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
134         $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
135         if ($userinfo) {
136             $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
137         }
138         $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
139         $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
141         return $paths;
142     }
144     protected function process_gradebook($data) {
145         // For non-merge restore types:
146         // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
147         $target = $this->get_task()->get_target();
148         if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) {
149             set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
150         }
151         if (!empty($data['calculations_freeze'])) {
152             if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING ||
153                     $target == backup::TARGET_EXISTING_DELETING) {
154                 set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
155             }
156         }
157     }
159     protected function process_grade_item($data) {
160         global $DB;
162         $data = (object)$data;
164         $oldid = $data->id;
165         $data->course = $this->get_courseid();
167         $data->courseid = $this->get_courseid();
169         if ($data->itemtype=='manual') {
170             // manual grade items store category id in categoryid
171             $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
172             // if mapping failed put in course's grade category
173             if (NULL == $data->categoryid) {
174                 $coursecat = grade_category::fetch_course_category($this->get_courseid());
175                 $data->categoryid = $coursecat->id;
176             }
177         } else if ($data->itemtype=='course') {
178             // course grade item stores their category id in iteminstance
179             $coursecat = grade_category::fetch_course_category($this->get_courseid());
180             $data->iteminstance = $coursecat->id;
181         } else if ($data->itemtype=='category') {
182             // category grade items store their category id in iteminstance
183             $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
184         } else {
185             throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
186         }
188         $data->scaleid   = $this->get_mappingid('scale', $data->scaleid, NULL);
189         $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
191         $data->locktime     = $this->apply_date_offset($data->locktime);
192         $data->timecreated  = $this->apply_date_offset($data->timecreated);
193         $data->timemodified = $this->apply_date_offset($data->timemodified);
195         $coursecategory = $newitemid = null;
196         //course grade item should already exist so updating instead of inserting
197         if($data->itemtype=='course') {
198             //get the ID of the already created grade item
199             $gi = new stdclass();
200             $gi->courseid  = $this->get_courseid();
201             $gi->itemtype  = $data->itemtype;
203             //need to get the id of the grade_category that was automatically created for the course
204             $category = new stdclass();
205             $category->courseid  = $this->get_courseid();
206             $category->parent  = null;
207             //course category fullname starts out as ? but may be edited
208             //$category->fullname  = '?';
209             $coursecategory = $DB->get_record('grade_categories', (array)$category);
210             $gi->iteminstance = $coursecategory->id;
212             $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
213             if (!empty($existinggradeitem)) {
214                 $data->id = $newitemid = $existinggradeitem->id;
215                 $DB->update_record('grade_items', $data);
216             }
217         } else if ($data->itemtype == 'manual') {
218             // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
219             $gi = array(
220                 'itemtype' => $data->itemtype,
221                 'courseid' => $data->courseid,
222                 'itemname' => $data->itemname,
223                 'categoryid' => $data->categoryid,
224             );
225             $newitemid = $DB->get_field('grade_items', 'id', $gi);
226         }
228         if (empty($newitemid)) {
229             //in case we found the course category but still need to insert the course grade item
230             if ($data->itemtype=='course' && !empty($coursecategory)) {
231                 $data->iteminstance = $coursecategory->id;
232             }
234             $newitemid = $DB->insert_record('grade_items', $data);
235         }
236         $this->set_mapping('grade_item', $oldid, $newitemid);
237     }
239     protected function process_grade_grade($data) {
240         global $DB;
242         $data = (object)$data;
243         $oldid = $data->id;
244         $olduserid = $data->userid;
246         $data->itemid = $this->get_new_parentid('grade_item');
248         $data->userid = $this->get_mappingid('user', $data->userid, null);
249         if (!empty($data->userid)) {
250             $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
251             $data->locktime     = $this->apply_date_offset($data->locktime);
252             // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
253             $data->overridden = $this->apply_date_offset($data->overridden);
254             $data->timecreated  = $this->apply_date_offset($data->timecreated);
255             $data->timemodified = $this->apply_date_offset($data->timemodified);
257             $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
258             if ($gradeexists) {
259                 $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
260                 $this->log($message, backup::LOG_DEBUG);
261             } else {
262                 $newitemid = $DB->insert_record('grade_grades', $data);
263                 $this->set_mapping('grade_grades', $oldid, $newitemid);
264             }
265         } else {
266             $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
267             $this->log($message, backup::LOG_DEBUG);
268         }
269     }
271     protected function process_grade_category($data) {
272         global $DB;
274         $data = (object)$data;
275         $oldid = $data->id;
277         $data->course = $this->get_courseid();
278         $data->courseid = $data->course;
280         $data->timecreated  = $this->apply_date_offset($data->timecreated);
281         $data->timemodified = $this->apply_date_offset($data->timemodified);
283         $newitemid = null;
284         //no parent means a course level grade category. That may have been created when the course was created
285         if(empty($data->parent)) {
286             //parent was being saved as 0 when it should be null
287             $data->parent = null;
289             //get the already created course level grade category
290             $category = new stdclass();
291             $category->courseid = $this->get_courseid();
292             $category->parent = null;
294             $coursecategory = $DB->get_record('grade_categories', (array)$category);
295             if (!empty($coursecategory)) {
296                 $data->id = $newitemid = $coursecategory->id;
297                 $DB->update_record('grade_categories', $data);
298             }
299         }
301         // Add a warning about a removed setting.
302         if (!empty($data->aggregatesubcats)) {
303             set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
304         }
306         //need to insert a course category
307         if (empty($newitemid)) {
308             $newitemid = $DB->insert_record('grade_categories', $data);
309         }
310         $this->set_mapping('grade_category', $oldid, $newitemid);
311     }
312     protected function process_grade_letter($data) {
313         global $DB;
315         $data = (object)$data;
316         $oldid = $data->id;
318         $data->contextid = context_course::instance($this->get_courseid())->id;
320         $gradeletter = (array)$data;
321         unset($gradeletter['id']);
322         if (!$DB->record_exists('grade_letters', $gradeletter)) {
323             $newitemid = $DB->insert_record('grade_letters', $data);
324         } else {
325             $newitemid = $data->id;
326         }
328         $this->set_mapping('grade_letter', $oldid, $newitemid);
329     }
330     protected function process_grade_setting($data) {
331         global $DB;
333         $data = (object)$data;
334         $oldid = $data->id;
336         $data->courseid = $this->get_courseid();
338         $target = $this->get_task()->get_target();
339         if ($data->name == 'minmaxtouse' &&
340                 ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) {
341             // We never restore minmaxtouse during merge.
342             return;
343         }
345         if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
346             $newitemid = $DB->insert_record('grade_settings', $data);
347         } else {
348             $newitemid = $data->id;
349         }
351         if (!empty($oldid)) {
352             // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
353             $this->set_mapping('grade_setting', $oldid, $newitemid);
354         }
355     }
357     /**
358      * put all activity grade items in the correct grade category and mark all for recalculation
359      */
360     protected function after_execute() {
361         global $DB;
363         $conditions = array(
364             'backupid' => $this->get_restoreid(),
365             'itemname' => 'grade_item'//,
366             //'itemid'   => $itemid
367         );
368         $rs = $DB->get_recordset('backup_ids_temp', $conditions);
370         // We need this for calculation magic later on.
371         $mappings = array();
373         if (!empty($rs)) {
374             foreach($rs as $grade_item_backup) {
376                 // Store the oldid with the new id.
377                 $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
379                 $updateobj = new stdclass();
380                 $updateobj->id = $grade_item_backup->newitemid;
382                 //if this is an activity grade item that needs to be put back in its correct category
383                 if (!empty($grade_item_backup->parentitemid)) {
384                     $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
385                     if (!is_null($oldcategoryid)) {
386                         $updateobj->categoryid = $oldcategoryid;
387                         $DB->update_record('grade_items', $updateobj);
388                     }
389                 } else {
390                     //mark course and category items as needing to be recalculated
391                     $updateobj->needsupdate=1;
392                     $DB->update_record('grade_items', $updateobj);
393                 }
394             }
395         }
396         $rs->close();
398         // We need to update the calculations for calculated grade items that may reference old
399         // grade item ids using ##gi\d+##.
400         // $mappings can be empty, use 0 if so (won't match ever)
401         list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
402         $sql = "SELECT gi.id, gi.calculation
403                   FROM {grade_items} gi
404                  WHERE gi.id {$sql} AND
405                        calculation IS NOT NULL";
406         $rs = $DB->get_recordset_sql($sql, $params);
407         foreach ($rs as $gradeitem) {
408             // Collect all of the used grade item id references
409             if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
410                 // This calculation doesn't reference any other grade items... EASY!
411                 continue;
412             }
413             // For this next bit we are going to do the replacement of id's in two steps:
414             // 1. We will replace all old id references with a special mapping reference.
415             // 2. We will replace all mapping references with id's
416             // Why do we do this?
417             // Because there potentially there will be an overlap of ids within the query and we
418             // we substitute the wrong id.. safest way around this is the two step system
419             $calculationmap = array();
420             $mapcount = 0;
421             foreach ($matches[1] as $match) {
422                 // Check that the old id is known to us, if not it was broken to begin with and will
423                 // continue to be broken.
424                 if (!array_key_exists($match, $mappings)) {
425                     continue;
426                 }
427                 // Our special mapping key
428                 $mapping = '##MAPPING'.$mapcount.'##';
429                 // The old id that exists within the calculation now
430                 $oldid = '##gi'.$match.'##';
431                 // The new id that we want to replace the old one with.
432                 $newid = '##gi'.$mappings[$match].'##';
433                 // Replace in the special mapping key
434                 $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
435                 // And record the mapping
436                 $calculationmap[$mapping] = $newid;
437                 $mapcount++;
438             }
439             // Iterate all special mappings for this calculation and replace in the new id's
440             foreach ($calculationmap as $mapping => $newid) {
441                 $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
442             }
443             // Update the calculation now that its being remapped
444             $DB->update_record('grade_items', $gradeitem);
445         }
446         $rs->close();
448         // Need to correct the grade category path and parent
449         $conditions = array(
450             'courseid' => $this->get_courseid()
451         );
453         $rs = $DB->get_recordset('grade_categories', $conditions);
454         // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
455         foreach ($rs as $gc) {
456             if (!empty($gc->parent)) {
457                 $grade_category = new stdClass();
458                 $grade_category->id = $gc->id;
459                 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
460                 $DB->update_record('grade_categories', $grade_category);
461             }
462         }
463         $rs->close();
465         // Now we can rebuild all the paths
466         $rs = $DB->get_recordset('grade_categories', $conditions);
467         foreach ($rs as $gc) {
468             $grade_category = new stdClass();
469             $grade_category->id = $gc->id;
470             $grade_category->path = grade_category::build_path($gc);
471             $grade_category->depth = substr_count($grade_category->path, '/') - 1;
472             $DB->update_record('grade_categories', $grade_category);
473         }
474         $rs->close();
476         // Check what to do with the minmaxtouse setting.
477         $this->check_minmaxtouse();
479         // Freeze gradebook calculations if needed.
480         $this->gradebook_calculation_freeze();
482         // Restore marks items as needing update. Update everything now.
483         grade_regrade_final_grades($this->get_courseid());
484     }
486     /**
487      * Freeze gradebook calculation if needed.
488      *
489      * This is similar to various upgrade scripts that check if the freeze is needed.
490      */
491     protected function gradebook_calculation_freeze() {
492         global $CFG;
493         $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
494         preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
495         $backupbuild = (int)$matches[1];
496         // The function floatval will return a float even if there is text mixed with the release number.
497         $backuprelease = floatval($this->get_task()->get_info()->backup_release);
499         // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
500         if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) {
501             require_once($CFG->libdir . '/db/upgradelib.php');
502             upgrade_extra_credit_weightoverride($this->get_courseid());
503         }
504         // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
505         if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) {
506             require_once($CFG->libdir . '/db/upgradelib.php');
507             upgrade_calculated_grade_items($this->get_courseid());
508         }
509         // Courses from before 3.1 (20160511) may have a letter boundary problem and should be checked for this issue.
510         // Backups from before and including 2.9 could have a build number that is greater than 20160511 and should
511         // be checked for this problem.
512         if (!$gradebookcalculationsfreeze && ($backupbuild < 20160511 || $backuprelease <= 2.9)) {
513             require_once($CFG->libdir . '/db/upgradelib.php');
514             upgrade_course_letter_boundary($this->get_courseid());
515         }
517     }
519     /**
520      * Checks what should happen with the course grade setting minmaxtouse.
521      *
522      * This is related to the upgrade step at the time the setting was added.
523      *
524      * @see MDL-48618
525      * @return void
526      */
527     protected function check_minmaxtouse() {
528         global $CFG, $DB;
529         require_once($CFG->libdir . '/gradelib.php');
531         $userinfo = $this->task->get_setting_value('users');
532         $settingname = 'minmaxtouse';
533         $courseid = $this->get_courseid();
534         $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
535         $version28start = 2014111000.00;
536         $version28last = 2014111006.05;
537         $version29start = 2015051100.00;
538         $version29last = 2015060400.02;
540         $target = $this->get_task()->get_target();
541         if ($minmaxtouse === false &&
542                 ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
543             // The setting was not found because this setting did not exist at the time the backup was made.
544             // And we are not restoring as merge, in which case we leave the course as it was.
545             $version = $this->get_task()->get_info()->moodle_version;
547             if ($version < $version28start) {
548                 // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
549                 if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
550                     grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
551                 }
553             } else if (($version >= $version28start && $version < $version28last) ||
554                     ($version >= $version29start && $version < $version29last)) {
555                 // They should be using grade_grade when the course has inconsistencies.
557                 $sql = "SELECT gi.id
558                           FROM {grade_items} gi
559                           JOIN {grade_grades} gg
560                             ON gg.itemid = gi.id
561                          WHERE gi.courseid = ?
562                            AND (gi.itemtype != ? AND gi.itemtype != ?)
563                            AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
565                 // The course can only have inconsistencies when we restore the user info,
566                 // we do not need to act on existing grades that were not restored as part of this backup.
567                 if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
569                     // Display the notice as we do during upgrade.
570                     set_config('show_min_max_grades_changed_' . $courseid, 1);
572                     if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
573                         // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
574                         // If they are using the site-wide grade_grade setting, we only want to notice them.
575                         grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
576                     }
577                 }
579             } else {
580                 // This should never happen because from now on minmaxtouse is always saved in backups.
581             }
582         }
583     }
586 /**
587  * Step in charge of restoring the grade history of a course.
588  *
589  * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
590  * we do not want to restore the history if the gradebook and its content has not been
591  * restored. At least for now.
592  */
593 class restore_grade_history_structure_step extends restore_structure_step {
595      protected function execute_condition() {
596         global $CFG, $DB;
598         if ($this->get_courseid() == SITEID) {
599             return false;
600         }
602         // No gradebook info found, don't execute.
603         $fullpath = $this->task->get_taskbasepath();
604         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
605         if (!file_exists($fullpath)) {
606             return false;
607         }
609         // Some module present in backup file isn't available to restore in this site, don't execute.
610         if ($this->task->is_missing_modules()) {
611             return false;
612         }
614         // Some activity has been excluded to be restored, don't execute.
615         if ($this->task->is_excluding_activities()) {
616             return false;
617         }
619         // There should only be one grade category (the 1 associated with the course itself).
620         $category = new stdclass();
621         $category->courseid  = $this->get_courseid();
622         $catcount = $DB->count_records('grade_categories', (array)$category);
623         if ($catcount > 1) {
624             return false;
625         }
627         // Arrived here, execute the step.
628         return true;
629      }
631     protected function define_structure() {
632         $paths = array();
634         // Settings to use.
635         $userinfo = $this->get_setting_value('users');
636         $history = $this->get_setting_value('grade_histories');
638         if ($userinfo && $history) {
639             $paths[] = new restore_path_element('grade_grade',
640                '/grade_history/grade_grades/grade_grade');
641         }
643         return $paths;
644     }
646     protected function process_grade_grade($data) {
647         global $DB;
649         $data = (object)($data);
650         $olduserid = $data->userid;
651         unset($data->id);
653         $data->userid = $this->get_mappingid('user', $data->userid, null);
654         if (!empty($data->userid)) {
655             // Do not apply the date offsets as this is history.
656             $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
657             $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
658             $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
659             $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
660             $DB->insert_record('grade_grades_history', $data);
661         } else {
662             $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
663             $this->log($message, backup::LOG_DEBUG);
664         }
665     }
669 /**
670  * decode all the interlinks present in restored content
671  * relying 100% in the restore_decode_processor that handles
672  * both the contents to modify and the rules to be applied
673  */
674 class restore_decode_interlinks extends restore_execution_step {
676     protected function define_execution() {
677         // Get the decoder (from the plan)
678         $decoder = $this->task->get_decoder();
679         restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
680         // And launch it, everything will be processed
681         $decoder->execute();
682     }
685 /**
686  * first, ensure that we have no gaps in section numbers
687  * and then, rebuid the course cache
688  */
689 class restore_rebuild_course_cache extends restore_execution_step {
691     protected function define_execution() {
692         global $DB;
694         // Although there is some sort of auto-recovery of missing sections
695         // present in course/formats... here we check that all the sections
696         // from 0 to MAX(section->section) exist, creating them if necessary
697         $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
698         // Iterate over all sections
699         for ($i = 0; $i <= $maxsection; $i++) {
700             // If the section $i doesn't exist, create it
701             if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
702                 $sectionrec = array(
703                     'course' => $this->get_courseid(),
704                     'section' => $i);
705                 $DB->insert_record('course_sections', $sectionrec); // missing section created
706             }
707         }
709         // Rebuild cache now that all sections are in place
710         rebuild_course_cache($this->get_courseid());
711         cache_helper::purge_by_event('changesincourse');
712         cache_helper::purge_by_event('changesincoursecat');
713     }
716 /**
717  * Review all the tasks having one after_restore method
718  * executing it to perform some final adjustments of information
719  * not available when the task was executed.
720  */
721 class restore_execute_after_restore extends restore_execution_step {
723     protected function define_execution() {
725         // Simply call to the execute_after_restore() method of the task
726         // that always is the restore_final_task
727         $this->task->launch_execute_after_restore();
728     }
732 /**
733  * Review all the (pending) block positions in backup_ids, matching by
734  * contextid, creating positions as needed. This is executed by the
735  * final task, once all the contexts have been created
736  */
737 class restore_review_pending_block_positions extends restore_execution_step {
739     protected function define_execution() {
740         global $DB;
742         // Get all the block_position objects pending to match
743         $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
744         $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
745         // Process block positions, creating them or accumulating for final step
746         foreach($rs as $posrec) {
747             // Get the complete position object out of the info field.
748             $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
749             // If position is for one already mapped (known) contextid
750             // process it now, creating the position, else nothing to
751             // do, position finally discarded
752             if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
753                 $position->contextid = $newctx->newitemid;
754                 // Create the block position
755                 $DB->insert_record('block_positions', $position);
756             }
757         }
758         $rs->close();
759     }
763 /**
764  * Updates the availability data for course modules and sections.
765  *
766  * Runs after the restore of all course modules, sections, and grade items has
767  * completed. This is necessary in order to update IDs that have changed during
768  * restore.
769  *
770  * @package core_backup
771  * @copyright 2014 The Open University
772  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
773  */
774 class restore_update_availability extends restore_execution_step {
776     protected function define_execution() {
777         global $CFG, $DB;
779         // Note: This code runs even if availability is disabled when restoring.
780         // That will ensure that if you later turn availability on for the site,
781         // there will be no incorrect IDs. (It doesn't take long if the restored
782         // data does not contain any availability information.)
784         // Get modinfo with all data after resetting cache.
785         rebuild_course_cache($this->get_courseid(), true);
786         $modinfo = get_fast_modinfo($this->get_courseid());
788         // Get the date offset for this restore.
789         $dateoffset = $this->apply_date_offset(1) - 1;
791         // Update all sections that were restored.
792         $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
793         $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
794         $sectionsbyid = null;
795         foreach ($rs as $rec) {
796             if (is_null($sectionsbyid)) {
797                 $sectionsbyid = array();
798                 foreach ($modinfo->get_section_info_all() as $section) {
799                     $sectionsbyid[$section->id] = $section;
800                 }
801             }
802             if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
803                 // If the section was not fully restored for some reason
804                 // (e.g. due to an earlier error), skip it.
805                 $this->get_logger()->process('Section not fully restored: id ' .
806                         $rec->newitemid, backup::LOG_WARNING);
807                 continue;
808             }
809             $section = $sectionsbyid[$rec->newitemid];
810             if (!is_null($section->availability)) {
811                 $info = new \core_availability\info_section($section);
812                 $info->update_after_restore($this->get_restoreid(),
813                         $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
814             }
815         }
816         $rs->close();
818         // Update all modules that were restored.
819         $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
820         $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
821         foreach ($rs as $rec) {
822             if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
823                 // If the module was not fully restored for some reason
824                 // (e.g. due to an earlier error), skip it.
825                 $this->get_logger()->process('Module not fully restored: id ' .
826                         $rec->newitemid, backup::LOG_WARNING);
827                 continue;
828             }
829             $cm = $modinfo->get_cm($rec->newitemid);
830             if (!is_null($cm->availability)) {
831                 $info = new \core_availability\info_module($cm);
832                 $info->update_after_restore($this->get_restoreid(),
833                         $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
834             }
835         }
836         $rs->close();
837     }
841 /**
842  * Process legacy module availability records in backup_ids.
843  *
844  * Matches course modules and grade item id once all them have been already restored.
845  * Only if all matchings are satisfied the availability condition will be created.
846  * At the same time, it is required for the site to have that functionality enabled.
847  *
848  * This step is included only to handle legacy backups (2.6 and before). It does not
849  * do anything for newer backups.
850  *
851  * @copyright 2014 The Open University
852  * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
853  */
854 class restore_process_course_modules_availability extends restore_execution_step {
856     protected function define_execution() {
857         global $CFG, $DB;
859         // Site hasn't availability enabled
860         if (empty($CFG->enableavailability)) {
861             return;
862         }
864         // Do both modules and sections.
865         foreach (array('module', 'section') as $table) {
866             // Get all the availability objects to process.
867             $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
868             $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
869             // Process availabilities, creating them if everything matches ok.
870             foreach ($rs as $availrec) {
871                 $allmatchesok = true;
872                 // Get the complete legacy availability object.
873                 $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
875                 // Note: This code used to update IDs, but that is now handled by the
876                 // current code (after restore) instead of this legacy code.
878                 // Get showavailability option.
879                 $thingid = ($table === 'module') ? $availability->coursemoduleid :
880                         $availability->coursesectionid;
881                 $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
882                         $table . '_showavailability', $thingid);
883                 if (!$showrec) {
884                     // Should not happen.
885                     throw new coding_exception('No matching showavailability record');
886                 }
887                 $show = $showrec->info->showavailability;
889                 // The $availability object is now in the format used in the old
890                 // system. Interpret this and convert to new system.
891                 $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
892                         array('id' => $thingid), MUST_EXIST);
893                 $newvalue = \core_availability\info::add_legacy_availability_condition(
894                         $currentvalue, $availability, $show);
895                 $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
896                         array('id' => $thingid));
897             }
898         }
899         $rs->close();
900     }
904 /*
905  * Execution step that, *conditionally* (if there isn't preloaded information)
906  * will load the inforef files for all the included course/section/activity tasks
907  * to backup_temp_ids. They will be stored with "xxxxref" as itemname
908  */
909 class restore_load_included_inforef_records extends restore_execution_step {
911     protected function define_execution() {
913         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
914             return;
915         }
917         // Get all the included tasks
918         $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
919         $progress = $this->task->get_progress();
920         $progress->start_progress($this->get_name(), count($tasks));
921         foreach ($tasks as $task) {
922             // Load the inforef.xml file if exists
923             $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
924             if (file_exists($inforefpath)) {
925                 // Load each inforef file to temp_ids.
926                 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
927             }
928         }
929         $progress->end_progress();
930     }
933 /*
934  * Execution step that will load all the needed files into backup_files_temp
935  *   - info: contains the whole original object (times, names...)
936  * (all them being original ids as loaded from xml)
937  */
938 class restore_load_included_files extends restore_structure_step {
940     protected function define_structure() {
942         $file = new restore_path_element('file', '/files/file');
944         return array($file);
945     }
947     /**
948      * Process one <file> element from files.xml
949      *
950      * @param array $data the element data
951      */
952     public function process_file($data) {
954         $data = (object)$data; // handy
956         // load it if needed:
957         //   - it it is one of the annotated inforef files (course/section/activity/block)
958         //   - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
959         // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
960         //       but then we'll need to change it to load plugins itself (because this is executed too early in restore)
961         $isfileref   = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
962         $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
963                         $data->component == 'grouping' || $data->component == 'grade' ||
964                         $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
965         if ($isfileref || $iscomponent) {
966             restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
967         }
968     }
971 /**
972  * Execution step that, *conditionally* (if there isn't preloaded information),
973  * will load all the needed roles to backup_temp_ids. They will be stored with
974  * "role" itemname. Also it will perform one automatic mapping to roles existing
975  * in the target site, based in permissions of the user performing the restore,
976  * archetypes and other bits. At the end, each original role will have its associated
977  * target role or 0 if it's going to be skipped. Note we wrap everything over one
978  * restore_dbops method, as far as the same stuff is going to be also executed
979  * by restore prechecks
980  */
981 class restore_load_and_map_roles extends restore_execution_step {
983     protected function define_execution() {
984         if ($this->task->get_preloaded_information()) { // if info is already preloaded
985             return;
986         }
988         $file = $this->get_basepath() . '/roles.xml';
989         // Load needed toles to temp_ids
990         restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
992         // Process roles, mapping/skipping. Any error throws exception
993         // Note we pass controller's info because it can contain role mapping information
994         // about manual mappings performed by UI
995         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);
996     }
999 /**
1000  * Execution step that, *conditionally* (if there isn't preloaded information
1001  * and users have been selected in settings, will load all the needed users
1002  * to backup_temp_ids. They will be stored with "user" itemname and with
1003  * their original contextid as paremitemid
1004  */
1005 class restore_load_included_users extends restore_execution_step {
1007     protected function define_execution() {
1009         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1010             return;
1011         }
1012         if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1013             return;
1014         }
1015         $file = $this->get_basepath() . '/users.xml';
1016         // Load needed users to temp_ids.
1017         restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
1018     }
1021 /**
1022  * Execution step that, *conditionally* (if there isn't preloaded information
1023  * and users have been selected in settings, will process all the needed users
1024  * in order to decide and perform any action with them (create / map / error)
1025  * Note: Any error will cause exception, as far as this is the same processing
1026  * than the one into restore prechecks (that should have stopped process earlier)
1027  */
1028 class restore_process_included_users extends restore_execution_step {
1030     protected function define_execution() {
1032         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1033             return;
1034         }
1035         if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1036             return;
1037         }
1038         restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
1039                 $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
1040     }
1043 /**
1044  * Execution step that will create all the needed users as calculated
1045  * by @restore_process_included_users (those having newiteind = 0)
1046  */
1047 class restore_create_included_users extends restore_execution_step {
1049     protected function define_execution() {
1051         restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
1052                 $this->task->get_userid(), $this->task->get_progress());
1053     }
1056 /**
1057  * Structure step that will create all the needed groups and groupings
1058  * by loading them from the groups.xml file performing the required matches.
1059  * Note group members only will be added if restoring user info
1060  */
1061 class restore_groups_structure_step extends restore_structure_step {
1063     protected function define_structure() {
1065         $paths = array(); // Add paths here
1067         // Do not include group/groupings information if not requested.
1068         $groupinfo = $this->get_setting_value('groups');
1069         if ($groupinfo) {
1070             $paths[] = new restore_path_element('group', '/groups/group');
1071             $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
1072             $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
1073         }
1074         return $paths;
1075     }
1077     // Processing functions go here
1078     public function process_group($data) {
1079         global $DB;
1081         $data = (object)$data; // handy
1082         $data->courseid = $this->get_courseid();
1084         // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1085         // another a group in the same course
1086         $context = context_course::instance($data->courseid);
1087         if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1088             if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
1089                 unset($data->idnumber);
1090             }
1091         } else {
1092             unset($data->idnumber);
1093         }
1095         $oldid = $data->id;    // need this saved for later
1097         $restorefiles = false; // Only if we end creating the group
1099         // Search if the group already exists (by name & description) in the target course
1100         $description_clause = '';
1101         $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1102         if (!empty($data->description)) {
1103             $description_clause = ' AND ' .
1104                                   $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1105            $params['description'] = $data->description;
1106         }
1107         if (!$groupdb = $DB->get_record_sql("SELECT *
1108                                                FROM {groups}
1109                                               WHERE courseid = :courseid
1110                                                 AND name = :grname $description_clause", $params)) {
1111             // group doesn't exist, create
1112             $newitemid = $DB->insert_record('groups', $data);
1113             $restorefiles = true; // We'll restore the files
1114         } else {
1115             // group exists, use it
1116             $newitemid = $groupdb->id;
1117         }
1118         // Save the id mapping
1119         $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
1120         // Invalidate the course group data cache just in case.
1121         cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1122     }
1124     public function process_grouping($data) {
1125         global $DB;
1127         $data = (object)$data; // handy
1128         $data->courseid = $this->get_courseid();
1130         // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1131         // another a grouping in the same course
1132         $context = context_course::instance($data->courseid);
1133         if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1134             if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
1135                 unset($data->idnumber);
1136             }
1137         } else {
1138             unset($data->idnumber);
1139         }
1141         $oldid = $data->id;    // need this saved for later
1142         $restorefiles = false; // Only if we end creating the grouping
1144         // Search if the grouping already exists (by name & description) in the target course
1145         $description_clause = '';
1146         $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1147         if (!empty($data->description)) {
1148             $description_clause = ' AND ' .
1149                                   $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1150            $params['description'] = $data->description;
1151         }
1152         if (!$groupingdb = $DB->get_record_sql("SELECT *
1153                                                   FROM {groupings}
1154                                                  WHERE courseid = :courseid
1155                                                    AND name = :grname $description_clause", $params)) {
1156             // grouping doesn't exist, create
1157             $newitemid = $DB->insert_record('groupings', $data);
1158             $restorefiles = true; // We'll restore the files
1159         } else {
1160             // grouping exists, use it
1161             $newitemid = $groupingdb->id;
1162         }
1163         // Save the id mapping
1164         $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1165         // Invalidate the course group data cache just in case.
1166         cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1167     }
1169     public function process_grouping_group($data) {
1170         global $CFG;
1172         require_once($CFG->dirroot.'/group/lib.php');
1174         $data = (object)$data;
1175         groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
1176     }
1178     protected function after_execute() {
1179         // Add group related files, matching with "group" mappings
1180         $this->add_related_files('group', 'icon', 'group');
1181         $this->add_related_files('group', 'description', 'group');
1182         // Add grouping related files, matching with "grouping" mappings
1183         $this->add_related_files('grouping', 'description', 'grouping');
1184         // Invalidate the course group data.
1185         cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1186     }
1190 /**
1191  * Structure step that will create all the needed group memberships
1192  * by loading them from the groups.xml file performing the required matches.
1193  */
1194 class restore_groups_members_structure_step extends restore_structure_step {
1196     protected $plugins = null;
1198     protected function define_structure() {
1200         $paths = array(); // Add paths here
1202         if ($this->get_setting_value('groups') && $this->get_setting_value('users')) {
1203             $paths[] = new restore_path_element('group', '/groups/group');
1204             $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1205         }
1207         return $paths;
1208     }
1210     public function process_group($data) {
1211         $data = (object)$data; // handy
1213         // HACK ALERT!
1214         // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1215         // Let's fake internal state to make $this->get_new_parentid('group') work.
1217         $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1218     }
1220     public function process_member($data) {
1221         global $DB, $CFG;
1222         require_once("$CFG->dirroot/group/lib.php");
1224         // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1226         $data = (object)$data; // handy
1228         // get parent group->id
1229         $data->groupid = $this->get_new_parentid('group');
1231         // map user newitemid and insert if not member already
1232         if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1233             if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1234                 // Check the component, if any, exists.
1235                 if (empty($data->component)) {
1236                     groups_add_member($data->groupid, $data->userid);
1238                 } else if ((strpos($data->component, 'enrol_') === 0)) {
1239                     // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1240                     // it is possible that enrolment was restored using different plugin type.
1241                     if (!isset($this->plugins)) {
1242                         $this->plugins = enrol_get_plugins(true);
1243                     }
1244                     if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1245                         if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1246                             if (isset($this->plugins[$instance->enrol])) {
1247                                 $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1248                             }
1249                         }
1250                     }
1252                 } else {
1253                     $dir = core_component::get_component_directory($data->component);
1254                     if ($dir and is_dir($dir)) {
1255                         if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1256                             return;
1257                         }
1258                     }
1259                     // Bad luck, plugin could not restore the data, let's add normal membership.
1260                     groups_add_member($data->groupid, $data->userid);
1261                     $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1262                     $this->log($message, backup::LOG_WARNING);
1263                 }
1264             }
1265         }
1266     }
1269 /**
1270  * Structure step that will create all the needed scales
1271  * by loading them from the scales.xml
1272  */
1273 class restore_scales_structure_step extends restore_structure_step {
1275     protected function define_structure() {
1277         $paths = array(); // Add paths here
1278         $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1279         return $paths;
1280     }
1282     protected function process_scale($data) {
1283         global $DB;
1285         $data = (object)$data;
1287         $restorefiles = false; // Only if we end creating the group
1289         $oldid = $data->id;    // need this saved for later
1291         // Look for scale (by 'scale' both in standard (course=0) and current course
1292         // with priority to standard scales (ORDER clause)
1293         // scale is not course unique, use get_record_sql to suppress warning
1294         // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1295         $compare_scale_clause = $DB->sql_compare_text('scale')  . ' = ' . $DB->sql_compare_text(':scaledesc');
1296         $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1297         if (!$scadb = $DB->get_record_sql("SELECT *
1298                                             FROM {scale}
1299                                            WHERE courseid IN (0, :courseid)
1300                                              AND $compare_scale_clause
1301                                         ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1302             // Remap the user if possible, defaut to user performing the restore if not
1303             $userid = $this->get_mappingid('user', $data->userid);
1304             $data->userid = $userid ? $userid : $this->task->get_userid();
1305             // Remap the course if course scale
1306             $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1307             // If global scale (course=0), check the user has perms to create it
1308             // falling to course scale if not
1309             $systemctx = context_system::instance();
1310             if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1311                 $data->courseid = $this->get_courseid();
1312             }
1313             // scale doesn't exist, create
1314             $newitemid = $DB->insert_record('scale', $data);
1315             $restorefiles = true; // We'll restore the files
1316         } else {
1317             // scale exists, use it
1318             $newitemid = $scadb->id;
1319         }
1320         // Save the id mapping (with files support at system context)
1321         $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1322     }
1324     protected function after_execute() {
1325         // Add scales related files, matching with "scale" mappings
1326         $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1327     }
1331 /**
1332  * Structure step that will create all the needed outocomes
1333  * by loading them from the outcomes.xml
1334  */
1335 class restore_outcomes_structure_step extends restore_structure_step {
1337     protected function define_structure() {
1339         $paths = array(); // Add paths here
1340         $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1341         return $paths;
1342     }
1344     protected function process_outcome($data) {
1345         global $DB;
1347         $data = (object)$data;
1349         $restorefiles = false; // Only if we end creating the group
1351         $oldid = $data->id;    // need this saved for later
1353         // Look for outcome (by shortname both in standard (courseid=null) and current course
1354         // with priority to standard outcomes (ORDER clause)
1355         // outcome is not course unique, use get_record_sql to suppress warning
1356         $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1357         if (!$outdb = $DB->get_record_sql('SELECT *
1358                                              FROM {grade_outcomes}
1359                                             WHERE shortname = :shortname
1360                                               AND (courseid = :courseid OR courseid IS NULL)
1361                                          ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1362             // Remap the user
1363             $userid = $this->get_mappingid('user', $data->usermodified);
1364             $data->usermodified = $userid ? $userid : $this->task->get_userid();
1365             // Remap the scale
1366             $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1367             // Remap the course if course outcome
1368             $data->courseid = $data->courseid ? $this->get_courseid() : null;
1369             // If global outcome (course=null), check the user has perms to create it
1370             // falling to course outcome if not
1371             $systemctx = context_system::instance();
1372             if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1373                 $data->courseid = $this->get_courseid();
1374             }
1375             // outcome doesn't exist, create
1376             $newitemid = $DB->insert_record('grade_outcomes', $data);
1377             $restorefiles = true; // We'll restore the files
1378         } else {
1379             // scale exists, use it
1380             $newitemid = $outdb->id;
1381         }
1382         // Set the corresponding grade_outcomes_courses record
1383         $outcourserec = new stdclass();
1384         $outcourserec->courseid  = $this->get_courseid();
1385         $outcourserec->outcomeid = $newitemid;
1386         if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1387             $DB->insert_record('grade_outcomes_courses', $outcourserec);
1388         }
1389         // Save the id mapping (with files support at system context)
1390         $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1391     }
1393     protected function after_execute() {
1394         // Add outcomes related files, matching with "outcome" mappings
1395         $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1396     }
1399 /**
1400  * Execution step that, *conditionally* (if there isn't preloaded information
1401  * will load all the question categories and questions (header info only)
1402  * to backup_temp_ids. They will be stored with "question_category" and
1403  * "question" itemnames and with their original contextid and question category
1404  * id as paremitemids
1405  */
1406 class restore_load_categories_and_questions extends restore_execution_step {
1408     protected function define_execution() {
1410         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1411             return;
1412         }
1413         $file = $this->get_basepath() . '/questions.xml';
1414         restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1415     }
1418 /**
1419  * Execution step that, *conditionally* (if there isn't preloaded information)
1420  * will process all the needed categories and questions
1421  * in order to decide and perform any action with them (create / map / error)
1422  * Note: Any error will cause exception, as far as this is the same processing
1423  * than the one into restore prechecks (that should have stopped process earlier)
1424  */
1425 class restore_process_categories_and_questions extends restore_execution_step {
1427     protected function define_execution() {
1429         if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1430             return;
1431         }
1432         restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1433     }
1436 /**
1437  * Structure step that will read the section.xml creating/updating sections
1438  * as needed, rebuilding course cache and other friends
1439  */
1440 class restore_section_structure_step extends restore_structure_step {
1441     /** @var array Cache: Array of id => course format */
1442     private static $courseformats = array();
1444     /**
1445      * Resets a static cache of course formats. Required for unit testing.
1446      */
1447     public static function reset_caches() {
1448         self::$courseformats = array();
1449     }
1451     protected function define_structure() {
1452         global $CFG;
1454         $paths = array();
1456         $section = new restore_path_element('section', '/section');
1457         $paths[] = $section;
1458         if ($CFG->enableavailability) {
1459             $paths[] = new restore_path_element('availability', '/section/availability');
1460             $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1461         }
1462         $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1464         // Apply for 'format' plugins optional paths at section level
1465         $this->add_plugin_structure('format', $section);
1467         // Apply for 'local' plugins optional paths at section level
1468         $this->add_plugin_structure('local', $section);
1470         return $paths;
1471     }
1473     public function process_section($data) {
1474         global $CFG, $DB;
1475         $data = (object)$data;
1476         $oldid = $data->id; // We'll need this later
1478         $restorefiles = false;
1480         // Look for the section
1481         $section = new stdclass();
1482         $section->course  = $this->get_courseid();
1483         $section->section = $data->number;
1484         // Section doesn't exist, create it with all the info from backup
1485         if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
1486             $section->name = $data->name;
1487             $section->summary = $data->summary;
1488             $section->summaryformat = $data->summaryformat;
1489             $section->sequence = '';
1490             $section->visible = $data->visible;
1491             if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1492                 $section->availability = null;
1493             } else {
1494                 $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1495                 // Include legacy [<2.7] availability data if provided.
1496                 if (is_null($section->availability)) {
1497                     $section->availability = \core_availability\info::convert_legacy_fields(
1498                             $data, true);
1499                 }
1500             }
1501             $newitemid = $DB->insert_record('course_sections', $section);
1502             $restorefiles = true;
1504         // Section exists, update non-empty information
1505         } else {
1506             $section->id = $secrec->id;
1507             if ((string)$secrec->name === '') {
1508                 $section->name = $data->name;
1509             }
1510             if (empty($secrec->summary)) {
1511                 $section->summary = $data->summary;
1512                 $section->summaryformat = $data->summaryformat;
1513                 $restorefiles = true;
1514             }
1516             // Don't update availability (I didn't see a useful way to define
1517             // whether existing or new one should take precedence).
1519             $DB->update_record('course_sections', $section);
1520             $newitemid = $secrec->id;
1521         }
1523         // Annotate the section mapping, with restorefiles option if needed
1524         $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1526         // set the new course_section id in the task
1527         $this->task->set_sectionid($newitemid);
1529         // If there is the legacy showavailability data, store this for later use.
1530         // (This data is not present when restoring 'new' backups.)
1531         if (isset($data->showavailability)) {
1532             // Cache the showavailability flag using the backup_ids data field.
1533             restore_dbops::set_backup_ids_record($this->get_restoreid(),
1534                     'section_showavailability', $newitemid, 0, null,
1535                     (object)array('showavailability' => $data->showavailability));
1536         }
1538         // Commented out. We never modify course->numsections as far as that is used
1539         // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1540         // Note: We keep the code here, to know about and because of the possibility of making this
1541         // optional based on some setting/attribute in the future
1542         // If needed, adjust course->numsections
1543         //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1544         //    if ($numsections < $section->section) {
1545         //        $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1546         //    }
1547         //}
1548     }
1550     /**
1551      * Process the legacy availability table record. This table does not exist
1552      * in Moodle 2.7+ but we still support restore.
1553      *
1554      * @param stdClass $data Record data
1555      */
1556     public function process_availability($data) {
1557         $data = (object)$data;
1558         // Simply going to store the whole availability record now, we'll process
1559         // all them later in the final task (once all activities have been restored)
1560         // Let's call the low level one to be able to store the whole object.
1561         $data->coursesectionid = $this->task->get_sectionid();
1562         restore_dbops::set_backup_ids_record($this->get_restoreid(),
1563                 'section_availability', $data->id, 0, null, $data);
1564     }
1566     /**
1567      * Process the legacy availability fields table record. This table does not
1568      * exist in Moodle 2.7+ but we still support restore.
1569      *
1570      * @param stdClass $data Record data
1571      */
1572     public function process_availability_field($data) {
1573         global $DB;
1574         $data = (object)$data;
1575         // Mark it is as passed by default
1576         $passed = true;
1577         $customfieldid = null;
1579         // If a customfield has been used in order to pass we must be able to match an existing
1580         // customfield by name (data->customfield) and type (data->customfieldtype)
1581         if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1582             // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1583             // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1584             $passed = false;
1585         } else if (!is_null($data->customfield)) {
1586             $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype);
1587             $customfieldid = $DB->get_field('user_info_field', 'id', $params);
1588             $passed = ($customfieldid !== false);
1589         }
1591         if ($passed) {
1592             // Create the object to insert into the database
1593             $availfield = new stdClass();
1594             $availfield->coursesectionid = $this->task->get_sectionid();
1595             $availfield->userfield = $data->userfield;
1596             $availfield->customfieldid = $customfieldid;
1597             $availfield->operator = $data->operator;
1598             $availfield->value = $data->value;
1600             // Get showavailability option.
1601             $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1602                     'section_showavailability', $availfield->coursesectionid);
1603             if (!$showrec) {
1604                 // Should not happen.
1605                 throw new coding_exception('No matching showavailability record');
1606             }
1607             $show = $showrec->info->showavailability;
1609             // The $availfield object is now in the format used in the old
1610             // system. Interpret this and convert to new system.
1611             $currentvalue = $DB->get_field('course_sections', 'availability',
1612                     array('id' => $availfield->coursesectionid), MUST_EXIST);
1613             $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1614                     $currentvalue, $availfield, $show);
1615             $DB->set_field('course_sections', 'availability', $newvalue,
1616                     array('id' => $availfield->coursesectionid));
1617         }
1618     }
1620     public function process_course_format_options($data) {
1621         global $DB;
1622         $courseid = $this->get_courseid();
1623         if (!array_key_exists($courseid, self::$courseformats)) {
1624             // It is safe to have a static cache of course formats because format can not be changed after this point.
1625             self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1626         }
1627         $data = (array)$data;
1628         if (self::$courseformats[$courseid] === $data['format']) {
1629             // Import section format options only if both courses (the one that was backed up
1630             // and the one we are restoring into) have same formats.
1631             $params = array(
1632                 'courseid' => $this->get_courseid(),
1633                 'sectionid' => $this->task->get_sectionid(),
1634                 'format' => $data['format'],
1635                 'name' => $data['name']
1636             );
1637             if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1638                 // Do not overwrite existing information.
1639                 $newid = $record->id;
1640             } else {
1641                 $params['value'] = $data['value'];
1642                 $newid = $DB->insert_record('course_format_options', $params);
1643             }
1644             $this->set_mapping('course_format_options', $data['id'], $newid);
1645         }
1646     }
1648     protected function after_execute() {
1649         // Add section related files, with 'course_section' itemid to match
1650         $this->add_related_files('course', 'section', 'course_section');
1651     }
1654 /**
1655  * Structure step that will read the course.xml file, loading it and performing
1656  * various actions depending of the site/restore settings. Note that target
1657  * course always exist before arriving here so this step will be updating
1658  * the course record (never inserting)
1659  */
1660 class restore_course_structure_step extends restore_structure_step {
1661     /**
1662      * @var bool this gets set to true by {@link process_course()} if we are
1663      * restoring an old coures that used the legacy 'module security' feature.
1664      * If so, we have to do more work in {@link after_execute()}.
1665      */
1666     protected $legacyrestrictmodules = false;
1668     /**
1669      * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1670      * array with array keys the module names ('forum', 'quiz', etc.). These are
1671      * the modules that are allowed according to the data in the backup file.
1672      * In {@link after_execute()} we then have to prevent adding of all the other
1673      * types of activity.
1674      */
1675     protected $legacyallowedmodules = array();
1677     protected function define_structure() {
1679         $course = new restore_path_element('course', '/course');
1680         $category = new restore_path_element('category', '/course/category');
1681         $tag = new restore_path_element('tag', '/course/tags/tag');
1682         $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1684         // Apply for 'format' plugins optional paths at course level
1685         $this->add_plugin_structure('format', $course);
1687         // Apply for 'theme' plugins optional paths at course level
1688         $this->add_plugin_structure('theme', $course);
1690         // Apply for 'report' plugins optional paths at course level
1691         $this->add_plugin_structure('report', $course);
1693         // Apply for 'course report' plugins optional paths at course level
1694         $this->add_plugin_structure('coursereport', $course);
1696         // Apply for plagiarism plugins optional paths at course level
1697         $this->add_plugin_structure('plagiarism', $course);
1699         // Apply for local plugins optional paths at course level
1700         $this->add_plugin_structure('local', $course);
1702         // Apply for admin tool plugins optional paths at course level.
1703         $this->add_plugin_structure('tool', $course);
1705         return array($course, $category, $tag, $allowed_module);
1706     }
1708     /**
1709      * Processing functions go here
1710      *
1711      * @global moodledatabase $DB
1712      * @param stdClass $data
1713      */
1714     public function process_course($data) {
1715         global $CFG, $DB;
1716         $context = context::instance_by_id($this->task->get_contextid());
1717         $userid = $this->task->get_userid();
1718         $target = $this->get_task()->get_target();
1719         $isnewcourse = $target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING;
1721         // When restoring to a new course we can set all the things except for the ID number.
1722         $canchangeidnumber = $isnewcourse || has_capability('moodle/course:changeidnumber', $context, $userid);
1723         $canchangeshortname = $isnewcourse || has_capability('moodle/course:changeshortname', $context, $userid);
1724         $canchangefullname = $isnewcourse || has_capability('moodle/course:changefullname', $context, $userid);
1725         $canchangesummary = $isnewcourse || has_capability('moodle/course:changesummary', $context, $userid);
1727         $data = (object)$data;
1728         $data->id = $this->get_courseid();
1730         $fullname  = $this->get_setting_value('course_fullname');
1731         $shortname = $this->get_setting_value('course_shortname');
1732         $startdate = $this->get_setting_value('course_startdate');
1734         // Calculate final course names, to avoid dupes.
1735         list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1737         if ($canchangefullname) {
1738             $data->fullname = $fullname;
1739         } else {
1740             unset($data->fullname);
1741         }
1743         if ($canchangeshortname) {
1744             $data->shortname = $shortname;
1745         } else {
1746             unset($data->shortname);
1747         }
1749         if (!$canchangesummary) {
1750             unset($data->summary);
1751             unset($data->summaryformat);
1752         }
1754         // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1755         // another course on this site.
1756         if (!empty($data->idnumber) && $canchangeidnumber && $this->task->is_samesite()
1757                 && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1758             // Do not reset idnumber.
1760         } else if (!$isnewcourse) {
1761             // Prevent override when restoring as merge.
1762             unset($data->idnumber);
1764         } else {
1765             $data->idnumber = '';
1766         }
1768         // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1769         // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1770         if (empty($data->hiddensections)) {
1771             $data->hiddensections = 0;
1772         }
1774         // Set legacyrestrictmodules to true if the course was resticting modules. If so
1775         // then we will need to process restricted modules after execution.
1776         $this->legacyrestrictmodules = !empty($data->restrictmodules);
1778         $data->startdate= $this->apply_date_offset($data->startdate);
1779         if ($data->defaultgroupingid) {
1780             $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1781         }
1782         if (empty($CFG->enablecompletion)) {
1783             $data->enablecompletion = 0;
1784             $data->completionstartonenrol = 0;
1785             $data->completionnotify = 0;
1786         }
1787         $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1788         if (!array_key_exists($data->lang, $languages)) {
1789             $data->lang = '';
1790         }
1792         $themes = get_list_of_themes(); // Get themes for quick search later
1793         if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1794             $data->theme = '';
1795         }
1797         // Check if this is an old SCORM course format.
1798         if ($data->format == 'scorm') {
1799             $data->format = 'singleactivity';
1800             $data->activitytype = 'scorm';
1801         }
1803         // Course record ready, update it
1804         $DB->update_record('course', $data);
1806         course_get_format($data)->update_course_format_options($data);
1808         // Role name aliases
1809         restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1810     }
1812     public function process_category($data) {
1813         // Nothing to do with the category. UI sets it before restore starts
1814     }
1816     public function process_tag($data) {
1817         global $CFG, $DB;
1819         $data = (object)$data;
1821         core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
1822                 context_course::instance($this->get_courseid()), $data->rawname);
1823     }
1825     public function process_allowed_module($data) {
1826         $data = (object)$data;
1828         // Backwards compatiblity support for the data that used to be in the
1829         // course_allowed_modules table.
1830         if ($this->legacyrestrictmodules) {
1831             $this->legacyallowedmodules[$data->modulename] = 1;
1832         }
1833     }
1835     protected function after_execute() {
1836         global $DB;
1838         // Add course related files, without itemid to match
1839         $this->add_related_files('course', 'summary', null);
1840         $this->add_related_files('course', 'overviewfiles', null);
1842         // Deal with legacy allowed modules.
1843         if ($this->legacyrestrictmodules) {
1844             $context = context_course::instance($this->get_courseid());
1846             list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
1847             list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
1848             foreach ($managerroleids as $roleid) {
1849                 unset($roleids[$roleid]);
1850             }
1852             foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
1853                 if (isset($this->legacyallowedmodules[$modname])) {
1854                     // Module is allowed, no worries.
1855                     continue;
1856                 }
1858                 $capability = 'mod/' . $modname . ':addinstance';
1859                 foreach ($roleids as $roleid) {
1860                     assign_capability($capability, CAP_PREVENT, $roleid, $context);
1861                 }
1862             }
1863         }
1864     }
1867 /**
1868  * Execution step that will migrate legacy files if present.
1869  */
1870 class restore_course_legacy_files_step extends restore_execution_step {
1871     public function define_execution() {
1872         global $DB;
1874         // Do a check for legacy files and skip if there are none.
1875         $sql = 'SELECT count(*)
1876                   FROM {backup_files_temp}
1877                  WHERE backupid = ?
1878                    AND contextid = ?
1879                    AND component = ?
1880                    AND filearea  = ?';
1881         $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
1883         if ($DB->count_records_sql($sql, $params)) {
1884             $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
1885             restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
1886                 'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
1887         }
1888     }
1891 /*
1892  * Structure step that will read the roles.xml file (at course/activity/block levels)
1893  * containing all the role_assignments and overrides for that context. If corresponding to
1894  * one mapped role, they will be applied to target context. Will observe the role_assignments
1895  * setting to decide if ras are restored.
1896  *
1897  * Note: this needs to be executed after all users are enrolled.
1898  */
1899 class restore_ras_and_caps_structure_step extends restore_structure_step {
1900     protected $plugins = null;
1902     protected function define_structure() {
1904         $paths = array();
1906         // Observe the role_assignments setting
1907         if ($this->get_setting_value('role_assignments')) {
1908             $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1909         }
1910         $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1912         return $paths;
1913     }
1915     /**
1916      * Assign roles
1917      *
1918      * This has to be called after enrolments processing.
1919      *
1920      * @param mixed $data
1921      * @return void
1922      */
1923     public function process_assignment($data) {
1924         global $DB;
1926         $data = (object)$data;
1928         // Check roleid, userid are one of the mapped ones
1929         if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1930             return;
1931         }
1932         if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1933             return;
1934         }
1935         if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1936             // Only assign roles to not deleted users
1937             return;
1938         }
1939         if (!$contextid = $this->task->get_contextid()) {
1940             return;
1941         }
1943         if (empty($data->component)) {
1944             // assign standard manual roles
1945             // TODO: role_assign() needs one userid param to be able to specify our restore userid
1946             role_assign($newroleid, $newuserid, $contextid);
1948         } else if ((strpos($data->component, 'enrol_') === 0)) {
1949             // Deal with enrolment roles - ignore the component and just find out the instance via new id,
1950             // it is possible that enrolment was restored using different plugin type.
1951             if (!isset($this->plugins)) {
1952                 $this->plugins = enrol_get_plugins(true);
1953             }
1954             if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1955                 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1956                     if (isset($this->plugins[$instance->enrol])) {
1957                         $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
1958                     }
1959                 }
1960             }
1962         } else {
1963             $data->roleid    = $newroleid;
1964             $data->userid    = $newuserid;
1965             $data->contextid = $contextid;
1966             $dir = core_component::get_component_directory($data->component);
1967             if ($dir and is_dir($dir)) {
1968                 if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
1969                     return;
1970                 }
1971             }
1972             // Bad luck, plugin could not restore the data, let's add normal membership.
1973             role_assign($data->roleid, $data->userid, $data->contextid);
1974             $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
1975             $this->log($message, backup::LOG_WARNING);
1976         }
1977     }
1979     public function process_override($data) {
1980         $data = (object)$data;
1982         // Check roleid is one of the mapped ones
1983         $newroleid = $this->get_mappingid('role', $data->roleid);
1984         // If newroleid and context are valid assign it via API (it handles dupes and so on)
1985         if ($newroleid && $this->task->get_contextid()) {
1986             // TODO: assign_capability() needs one userid param to be able to specify our restore userid
1987             // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
1988             assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1989         }
1990     }
1993 /**
1994  * If no instances yet add default enrol methods the same way as when creating new course in UI.
1995  */
1996 class restore_default_enrolments_step extends restore_execution_step {
1998     public function define_execution() {
1999         global $DB;
2001         // No enrolments in front page.
2002         if ($this->get_courseid() == SITEID) {
2003             return;
2004         }
2006         $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
2008         if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) {
2009             // Something already added instances, do not add default instances.
2010             $plugins = enrol_get_plugins(true);
2011             foreach ($plugins as $plugin) {
2012                 $plugin->restore_sync_course($course);
2013             }
2015         } else {
2016             // Looks like a newly created course.
2017             enrol_course_updated(true, $course, null);
2018         }
2019     }
2022 /**
2023  * This structure steps restores the enrol plugins and their underlying
2024  * enrolments, performing all the mappings and/or movements required
2025  */
2026 class restore_enrolments_structure_step extends restore_structure_step {
2027     protected $enrolsynced = false;
2028     protected $plugins = null;
2029     protected $originalstatus = array();
2031     /**
2032      * Conditionally decide if this step should be executed.
2033      *
2034      * This function checks the following parameter:
2035      *
2036      *   1. the course/enrolments.xml file exists
2037      *
2038      * @return bool true is safe to execute, false otherwise
2039      */
2040     protected function execute_condition() {
2042         if ($this->get_courseid() == SITEID) {
2043             return false;
2044         }
2046         // Check it is included in the backup
2047         $fullpath = $this->task->get_taskbasepath();
2048         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2049         if (!file_exists($fullpath)) {
2050             // Not found, can't restore enrolments info
2051             return false;
2052         }
2054         return true;
2055     }
2057     protected function define_structure() {
2059         $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2060         $enrolment = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2061         // Attach local plugin stucture to enrol element.
2062         $this->add_plugin_structure('enrol', $enrol);
2064         return array($enrol, $enrolment);
2065     }
2067     /**
2068      * Create enrolment instances.
2069      *
2070      * This has to be called after creation of roles
2071      * and before adding of role assignments.
2072      *
2073      * @param mixed $data
2074      * @return void
2075      */
2076     public function process_enrol($data) {
2077         global $DB;
2079         $data = (object)$data;
2080         $oldid = $data->id; // We'll need this later.
2081         unset($data->id);
2083         $this->originalstatus[$oldid] = $data->status;
2085         if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2086             $this->set_mapping('enrol', $oldid, 0);
2087             return;
2088         }
2090         if (!isset($this->plugins)) {
2091             $this->plugins = enrol_get_plugins(true);
2092         }
2094         if (!$this->enrolsynced) {
2095             // Make sure that all plugin may create instances and enrolments automatically
2096             // before the first instance restore - this is suitable especially for plugins
2097             // that synchronise data automatically using course->idnumber or by course categories.
2098             foreach ($this->plugins as $plugin) {
2099                 $plugin->restore_sync_course($courserec);
2100             }
2101             $this->enrolsynced = true;
2102         }
2104         // Map standard fields - plugin has to process custom fields manually.
2105         $data->roleid   = $this->get_mappingid('role', $data->roleid);
2106         $data->courseid = $courserec->id;
2108         if ($this->get_setting_value('enrol_migratetomanual')) {
2109             unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2110             if (!enrol_is_enabled('manual')) {
2111                 $this->set_mapping('enrol', $oldid, 0);
2112                 return;
2113             }
2114             if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2115                 $instance = reset($instances);
2116                 $this->set_mapping('enrol', $oldid, $instance->id);
2117             } else {
2118                 if ($data->enrol === 'manual') {
2119                     $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2120                 } else {
2121                     $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2122                 }
2123                 $this->set_mapping('enrol', $oldid, $instanceid);
2124             }
2126         } else {
2127             if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2128                 $this->set_mapping('enrol', $oldid, 0);
2129                 $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments";
2130                 $this->log($message, backup::LOG_WARNING);
2131                 return;
2132             }
2133             if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2134                 // Let's keep the sortorder in old backups.
2135             } else {
2136                 // Prevent problems with colliding sortorders in old backups,
2137                 // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2138                 unset($data->sortorder);
2139             }
2140             // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2141             $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2142         }
2143     }
2145     /**
2146      * Create user enrolments.
2147      *
2148      * This has to be called after creation of enrolment instances
2149      * and before adding of role assignments.
2150      *
2151      * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2152      *
2153      * @param mixed $data
2154      * @return void
2155      */
2156     public function process_enrolment($data) {
2157         global $DB;
2159         if (!isset($this->plugins)) {
2160             $this->plugins = enrol_get_plugins(true);
2161         }
2163         $data = (object)$data;
2165         // Process only if parent instance have been mapped.
2166         if ($enrolid = $this->get_new_parentid('enrol')) {
2167             $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2168             $oldenrolid = $this->get_old_parentid('enrol');
2169             if (isset($this->originalstatus[$oldenrolid])) {
2170                 $oldinstancestatus = $this->originalstatus[$oldenrolid];
2171             }
2172             if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2173                 // And only if user is a mapped one.
2174                 if ($userid = $this->get_mappingid('user', $data->userid)) {
2175                     if (isset($this->plugins[$instance->enrol])) {
2176                         $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2177                     }
2178                 }
2179             }
2180         }
2181     }
2185 /**
2186  * Make sure the user restoring the course can actually access it.
2187  */
2188 class restore_fix_restorer_access_step extends restore_execution_step {
2189     protected function define_execution() {
2190         global $CFG, $DB;
2192         if (!$userid = $this->task->get_userid()) {
2193             return;
2194         }
2196         if (empty($CFG->restorernewroleid)) {
2197             // Bad luck, no fallback role for restorers specified
2198             return;
2199         }
2201         $courseid = $this->get_courseid();
2202         $context = context_course::instance($courseid);
2204         if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2205             // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2206             return;
2207         }
2209         // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2210         role_assign($CFG->restorernewroleid, $userid, $context);
2212         if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2213             // Extra role is enough, yay!
2214             return;
2215         }
2217         // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2218         // hopefully admin selected suitable $CFG->restorernewroleid ...
2219         if (!enrol_is_enabled('manual')) {
2220             return;
2221         }
2222         if (!$enrol = enrol_get_plugin('manual')) {
2223             return;
2224         }
2225         if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2226             $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2227             $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2228             $enrol->add_instance($course, $fields);
2229         }
2231         enrol_try_internal_enrol($courseid, $userid);
2232     }
2236 /**
2237  * This structure steps restores the filters and their configs
2238  */
2239 class restore_filters_structure_step extends restore_structure_step {
2241     protected function define_structure() {
2243         $paths = array();
2245         $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2246         $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2248         return $paths;
2249     }
2251     public function process_active($data) {
2253         $data = (object)$data;
2255         if (strpos($data->filter, 'filter/') === 0) {
2256             $data->filter = substr($data->filter, 7);
2258         } else if (strpos($data->filter, '/') !== false) {
2259             // Unsupported old filter.
2260             return;
2261         }
2263         if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2264             return;
2265         }
2266         filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2267     }
2269     public function process_config($data) {
2271         $data = (object)$data;
2273         if (strpos($data->filter, 'filter/') === 0) {
2274             $data->filter = substr($data->filter, 7);
2276         } else if (strpos($data->filter, '/') !== false) {
2277             // Unsupported old filter.
2278             return;
2279         }
2281         if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2282             return;
2283         }
2284         filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2285     }
2289 /**
2290  * This structure steps restores the comments
2291  * Note: Cannot use the comments API because defaults to USER->id.
2292  * That should change allowing to pass $userid
2293  */
2294 class restore_comments_structure_step extends restore_structure_step {
2296     protected function define_structure() {
2298         $paths = array();
2300         $paths[] = new restore_path_element('comment', '/comments/comment');
2302         return $paths;
2303     }
2305     public function process_comment($data) {
2306         global $DB;
2308         $data = (object)$data;
2310         // First of all, if the comment has some itemid, ask to the task what to map
2311         $mapping = false;
2312         if ($data->itemid) {
2313             $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2314             $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2315         }
2316         // Only restore the comment if has no mapping OR we have found the matching mapping
2317         if (!$mapping || $data->itemid) {
2318             // Only if user mapping and context
2319             $data->userid = $this->get_mappingid('user', $data->userid);
2320             if ($data->userid && $this->task->get_contextid()) {
2321                 $data->contextid = $this->task->get_contextid();
2322                 // Only if there is another comment with same context/user/timecreated
2323                 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2324                 if (!$DB->record_exists('comments', $params)) {
2325                     $DB->insert_record('comments', $data);
2326                 }
2327             }
2328         }
2329     }
2332 /**
2333  * This structure steps restores the badges and their configs
2334  */
2335 class restore_badges_structure_step extends restore_structure_step {
2337     /**
2338      * Conditionally decide if this step should be executed.
2339      *
2340      * This function checks the following parameters:
2341      *
2342      *   1. Badges and course badges are enabled on the site.
2343      *   2. The course/badges.xml file exists.
2344      *   3. All modules are restorable.
2345      *   4. All modules are marked for restore.
2346      *
2347      * @return bool True is safe to execute, false otherwise
2348      */
2349     protected function execute_condition() {
2350         global $CFG;
2352         // First check is badges and course level badges are enabled on this site.
2353         if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2354             // Disabled, don't restore course badges.
2355             return false;
2356         }
2358         // Check if badges.xml is included in the backup.
2359         $fullpath = $this->task->get_taskbasepath();
2360         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2361         if (!file_exists($fullpath)) {
2362             // Not found, can't restore course badges.
2363             return false;
2364         }
2366         // Check we are able to restore all backed up modules.
2367         if ($this->task->is_missing_modules()) {
2368             return false;
2369         }
2371         // Finally check all modules within the backup are being restored.
2372         if ($this->task->is_excluding_activities()) {
2373             return false;
2374         }
2376         return true;
2377     }
2379     protected function define_structure() {
2380         $paths = array();
2381         $paths[] = new restore_path_element('badge', '/badges/badge');
2382         $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2383         $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2384         $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2386         return $paths;
2387     }
2389     public function process_badge($data) {
2390         global $DB, $CFG;
2392         require_once($CFG->libdir . '/badgeslib.php');
2394         $data = (object)$data;
2395         $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2396         if (empty($data->usercreated)) {
2397             $data->usercreated = $this->task->get_userid();
2398         }
2399         $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2400         if (empty($data->usermodified)) {
2401             $data->usermodified = $this->task->get_userid();
2402         }
2404         // We'll restore the badge image.
2405         $restorefiles = true;
2407         $courseid = $this->get_courseid();
2409         $params = array(
2410                 'name'           => $data->name,
2411                 'description'    => $data->description,
2412                 'timecreated'    => $this->apply_date_offset($data->timecreated),
2413                 'timemodified'   => $this->apply_date_offset($data->timemodified),
2414                 'usercreated'    => $data->usercreated,
2415                 'usermodified'   => $data->usermodified,
2416                 'issuername'     => $data->issuername,
2417                 'issuerurl'      => $data->issuerurl,
2418                 'issuercontact'  => $data->issuercontact,
2419                 'expiredate'     => $this->apply_date_offset($data->expiredate),
2420                 'expireperiod'   => $data->expireperiod,
2421                 'type'           => BADGE_TYPE_COURSE,
2422                 'courseid'       => $courseid,
2423                 'message'        => $data->message,
2424                 'messagesubject' => $data->messagesubject,
2425                 'attachment'     => $data->attachment,
2426                 'notification'   => $data->notification,
2427                 'status'         => BADGE_STATUS_INACTIVE,
2428                 'nextcron'       => $this->apply_date_offset($data->nextcron)
2429         );
2431         $newid = $DB->insert_record('badge', $params);
2432         $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2433     }
2435     public function process_criterion($data) {
2436         global $DB;
2438         $data = (object)$data;
2440         $params = array(
2441                 'badgeid'           => $this->get_new_parentid('badge'),
2442                 'criteriatype'      => $data->criteriatype,
2443                 'method'            => $data->method,
2444                 'description'       => isset($data->description) ? $data->description : '',
2445                 'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0,
2446         );
2447         $newid = $DB->insert_record('badge_criteria', $params);
2448         $this->set_mapping('criterion', $data->id, $newid);
2449     }
2451     public function process_parameter($data) {
2452         global $DB, $CFG;
2454         require_once($CFG->libdir . '/badgeslib.php');
2456         $data = (object)$data;
2457         $criteriaid = $this->get_new_parentid('criterion');
2459         // Parameter array that will go to database.
2460         $params = array();
2461         $params['critid'] = $criteriaid;
2463         $oldparam = explode('_', $data->name);
2465         if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2466             $module = $this->get_mappingid('course_module', $oldparam[1]);
2467             $params['name'] = $oldparam[0] . '_' . $module;
2468             $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2469         } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2470             $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2471             $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2472         } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2473             $role = $this->get_mappingid('role', $data->value);
2474             if (!empty($role)) {
2475                 $params['name'] = 'role_' . $role;
2476                 $params['value'] = $role;
2477             } else {
2478                 return;
2479             }
2480         }
2482         if (!$DB->record_exists('badge_criteria_param', $params)) {
2483             $DB->insert_record('badge_criteria_param', $params);
2484         }
2485     }
2487     public function process_manual_award($data) {
2488         global $DB;
2490         $data = (object)$data;
2491         $role = $this->get_mappingid('role', $data->issuerrole);
2493         if (!empty($role)) {
2494             $award = array(
2495                 'badgeid'     => $this->get_new_parentid('badge'),
2496                 'recipientid' => $this->get_mappingid('user', $data->recipientid),
2497                 'issuerid'    => $this->get_mappingid('user', $data->issuerid),
2498                 'issuerrole'  => $role,
2499                 'datemet'     => $this->apply_date_offset($data->datemet)
2500             );
2502             // Skip the manual award if recipient or issuer can not be mapped to.
2503             if (empty($award['recipientid']) || empty($award['issuerid'])) {
2504                 return;
2505             }
2507             $DB->insert_record('badge_manual_award', $award);
2508         }
2509     }
2511     protected function after_execute() {
2512         // Add related files.
2513         $this->add_related_files('badges', 'badgeimage', 'badge');
2514     }
2517 /**
2518  * This structure steps restores the calendar events
2519  */
2520 class restore_calendarevents_structure_step extends restore_structure_step {
2522     protected function define_structure() {
2524         $paths = array();
2526         $paths[] = new restore_path_element('calendarevents', '/events/event');
2528         return $paths;
2529     }
2531     public function process_calendarevents($data) {
2532         global $DB, $SITE, $USER;
2534         $data = (object)$data;
2535         $oldid = $data->id;
2536         $restorefiles = true; // We'll restore the files
2537         // Find the userid and the groupid associated with the event.
2538         $data->userid = $this->get_mappingid('user', $data->userid);
2539         if ($data->userid === false) {
2540             // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2541             // Use the current user ID for these events.
2542             $data->userid = $USER->id;
2543         }
2544         if (!empty($data->groupid)) {
2545             $data->groupid = $this->get_mappingid('group', $data->groupid);
2546             if ($data->groupid === false) {
2547                 return;
2548             }
2549         }
2550         // Handle events with empty eventtype //MDL-32827
2551         if(empty($data->eventtype)) {
2552             if ($data->courseid == $SITE->id) {                                // Site event
2553                 $data->eventtype = "site";
2554             } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2555                 // Course assingment event
2556                 $data->eventtype = "due";
2557             } else if ($data->courseid != 0 && $data->groupid == 0) {      // Course event
2558                 $data->eventtype = "course";
2559             } else if ($data->groupid) {                                      // Group event
2560                 $data->eventtype = "group";
2561             } else if ($data->userid) {                                       // User event
2562                 $data->eventtype = "user";
2563             } else {
2564                 return;
2565             }
2566         }
2568         $params = array(
2569                 'name'           => $data->name,
2570                 'description'    => $data->description,
2571                 'format'         => $data->format,
2572                 'courseid'       => $this->get_courseid(),
2573                 'groupid'        => $data->groupid,
2574                 'userid'         => $data->userid,
2575                 'repeatid'       => $data->repeatid,
2576                 'modulename'     => $data->modulename,
2577                 'eventtype'      => $data->eventtype,
2578                 'timestart'      => $this->apply_date_offset($data->timestart),
2579                 'timeduration'   => $data->timeduration,
2580                 'visible'        => $data->visible,
2581                 'uuid'           => $data->uuid,
2582                 'sequence'       => $data->sequence,
2583                 'timemodified'    => $this->apply_date_offset($data->timemodified));
2584         if ($this->name == 'activity_calendar') {
2585             $params['instance'] = $this->task->get_activityid();
2586         } else {
2587             $params['instance'] = 0;
2588         }
2589         $sql = "SELECT id
2590                   FROM {event}
2591                  WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2592                    AND courseid = ?
2593                    AND repeatid = ?
2594                    AND modulename = ?
2595                    AND timestart = ?
2596                    AND timeduration = ?
2597                    AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2598         $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']);
2599         $result = $DB->record_exists_sql($sql, $arg);
2600         if (empty($result)) {
2601             $newitemid = $DB->insert_record('event', $params);
2602             $this->set_mapping('event', $oldid, $newitemid);
2603             $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2604         }
2606     }
2607     protected function after_execute() {
2608         // Add related files
2609         $this->add_related_files('calendar', 'event_description', 'event_description');
2610     }
2613 class restore_course_completion_structure_step extends restore_structure_step {
2615     /**
2616      * Conditionally decide if this step should be executed.
2617      *
2618      * This function checks parameters that are not immediate settings to ensure
2619      * that the enviroment is suitable for the restore of course completion info.
2620      *
2621      * This function checks the following four parameters:
2622      *
2623      *   1. Course completion is enabled on the site
2624      *   2. The backup includes course completion information
2625      *   3. All modules are restorable
2626      *   4. All modules are marked for restore.
2627      *   5. No completion criteria already exist for the course.
2628      *
2629      * @return bool True is safe to execute, false otherwise
2630      */
2631     protected function execute_condition() {
2632         global $CFG, $DB;
2634         // First check course completion is enabled on this site
2635         if (empty($CFG->enablecompletion)) {
2636             // Disabled, don't restore course completion
2637             return false;
2638         }
2640         // No course completion on the front page.
2641         if ($this->get_courseid() == SITEID) {
2642             return false;
2643         }
2645         // Check it is included in the backup
2646         $fullpath = $this->task->get_taskbasepath();
2647         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2648         if (!file_exists($fullpath)) {
2649             // Not found, can't restore course completion
2650             return false;
2651         }
2653         // Check we are able to restore all backed up modules
2654         if ($this->task->is_missing_modules()) {
2655             return false;
2656         }
2658         // Check all modules within the backup are being restored.
2659         if ($this->task->is_excluding_activities()) {
2660             return false;
2661         }
2663         // Check that no completion criteria is already set for the course.
2664         if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
2665             return false;
2666         }
2668         return true;
2669     }
2671     /**
2672      * Define the course completion structure
2673      *
2674      * @return array Array of restore_path_element
2675      */
2676     protected function define_structure() {
2678         // To know if we are including user completion info
2679         $userinfo = $this->get_setting_value('userscompletion');
2681         $paths = array();
2682         $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
2683         $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
2685         if ($userinfo) {
2686             $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
2687             $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
2688         }
2690         return $paths;
2692     }
2694     /**
2695      * Process course completion criteria
2696      *
2697      * @global moodle_database $DB
2698      * @param stdClass $data
2699      */
2700     public function process_course_completion_criteria($data) {
2701         global $DB;
2703         $data = (object)$data;
2704         $data->course = $this->get_courseid();
2706         // Apply the date offset to the time end field
2707         $data->timeend = $this->apply_date_offset($data->timeend);
2709         // Map the role from the criteria
2710         if (isset($data->role) && $data->role != '') {
2711             // Newer backups should include roleshortname, which makes this much easier.
2712             if (!empty($data->roleshortname)) {
2713                 $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
2714                 if (!$roleinstanceid) {
2715                     $this->log(
2716                         'Could not match the role shortname in course_completion_criteria, so skipping',
2717                         backup::LOG_DEBUG
2718                     );
2719                     return;
2720                 }
2721                 $data->role = $roleinstanceid;
2722             } else {
2723                 $data->role = $this->get_mappingid('role', $data->role);
2724             }
2726             // Check we have an id, otherwise it causes all sorts of bugs.
2727             if (!$data->role) {
2728                 $this->log(
2729                     'Could not match role in course_completion_criteria, so skipping',
2730                     backup::LOG_DEBUG
2731                 );
2732                 return;
2733             }
2734         }
2736         // If the completion criteria is for a module we need to map the module instance
2737         // to the new module id.
2738         if (!empty($data->moduleinstance) && !empty($data->module)) {
2739             $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
2740             if (empty($data->moduleinstance)) {
2741                 $this->log(
2742                     'Could not match the module instance in course_completion_criteria, so skipping',
2743                     backup::LOG_DEBUG
2744                 );
2745                 return;
2746             }
2747         } else {
2748             $data->module = null;
2749             $data->moduleinstance = null;
2750         }
2752         // We backup the course shortname rather than the ID so that we can match back to the course
2753         if (!empty($data->courseinstanceshortname)) {
2754             $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
2755             if (!$courseinstanceid) {
2756                 $this->log(
2757                     'Could not match the course instance in course_completion_criteria, so skipping',
2758                     backup::LOG_DEBUG
2759                 );
2760                 return;
2761             }
2762         } else {
2763             $courseinstanceid = null;
2764         }
2765         $data->courseinstance = $courseinstanceid;
2767         $params = array(
2768             'course'         => $data->course,
2769             'criteriatype'   => $data->criteriatype,
2770             'enrolperiod'    => $data->enrolperiod,
2771             'courseinstance' => $data->courseinstance,
2772             'module'         => $data->module,
2773             'moduleinstance' => $data->moduleinstance,
2774             'timeend'        => $data->timeend,
2775             'gradepass'      => $data->gradepass,
2776             'role'           => $data->role
2777         );
2778         $newid = $DB->insert_record('course_completion_criteria', $params);
2779         $this->set_mapping('course_completion_criteria', $data->id, $newid);
2780     }
2782     /**
2783      * Processes course compltion criteria complete records
2784      *
2785      * @global moodle_database $DB
2786      * @param stdClass $data
2787      */
2788     public function process_course_completion_crit_compl($data) {
2789         global $DB;
2791         $data = (object)$data;
2793         // This may be empty if criteria could not be restored
2794         $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
2796         $data->course = $this->get_courseid();
2797         $data->userid = $this->get_mappingid('user', $data->userid);
2799         if (!empty($data->criteriaid) && !empty($data->userid)) {
2800             $params = array(
2801                 'userid' => $data->userid,
2802                 'course' => $data->course,
2803                 'criteriaid' => $data->criteriaid,
2804                 'timecompleted' => $this->apply_date_offset($data->timecompleted)
2805             );
2806             if (isset($data->gradefinal)) {
2807                 $params['gradefinal'] = $data->gradefinal;
2808             }
2809             if (isset($data->unenroled)) {
2810                 $params['unenroled'] = $data->unenroled;
2811             }
2812             $DB->insert_record('course_completion_crit_compl', $params);
2813         }
2814     }
2816     /**
2817      * Process course completions
2818      *
2819      * @global moodle_database $DB
2820      * @param stdClass $data
2821      */
2822     public function process_course_completions($data) {
2823         global $DB;
2825         $data = (object)$data;
2827         $data->course = $this->get_courseid();
2828         $data->userid = $this->get_mappingid('user', $data->userid);
2830         if (!empty($data->userid)) {
2831             $params = array(
2832                 'userid' => $data->userid,
2833                 'course' => $data->course,
2834                 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
2835                 'timestarted' => $this->apply_date_offset($data->timestarted),
2836                 'timecompleted' => $this->apply_date_offset($data->timecompleted),
2837                 'reaggregate' => $data->reaggregate
2838             );
2840             $existing = $DB->get_record('course_completions', array(
2841                 'userid' => $data->userid,
2842                 'course' => $data->course
2843             ));
2845             // MDL-46651 - If cron writes out a new record before we get to it
2846             // then we should replace it with the Truth data from the backup.
2847             // This may be obsolete after MDL-48518 is resolved
2848             if ($existing) {
2849                 $params['id'] = $existing->id;
2850                 $DB->update_record('course_completions', $params);
2851             } else {
2852                 $DB->insert_record('course_completions', $params);
2853             }
2854         }
2855     }
2857     /**
2858      * Process course completion aggregate methods
2859      *
2860      * @global moodle_database $DB
2861      * @param stdClass $data
2862      */
2863     public function process_course_completion_aggr_methd($data) {
2864         global $DB;
2866         $data = (object)$data;
2868         $data->course = $this->get_courseid();
2870         // Only create the course_completion_aggr_methd records if
2871         // the target course has not them defined. MDL-28180
2872         if (!$DB->record_exists('course_completion_aggr_methd', array(
2873                     'course' => $data->course,
2874                     'criteriatype' => $data->criteriatype))) {
2875             $params = array(
2876                 'course' => $data->course,
2877                 'criteriatype' => $data->criteriatype,
2878                 'method' => $data->method,
2879                 'value' => $data->value,
2880             );
2881             $DB->insert_record('course_completion_aggr_methd', $params);
2882         }
2883     }
2887 /**
2888  * This structure step restores course logs (cmid = 0), delegating
2889  * the hard work to the corresponding {@link restore_logs_processor} passing the
2890  * collection of {@link restore_log_rule} rules to be observed as they are defined
2891  * by the task. Note this is only executed based in the 'logs' setting.
2892  *
2893  * NOTE: This is executed by final task, to have all the activities already restored
2894  *
2895  * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
2896  * records are. There are others like 'calendar' and 'upload' that will be handled
2897  * later.
2898  *
2899  * NOTE: All the missing actions (not able to be restored) are sent to logs for
2900  * debugging purposes
2901  */
2902 class restore_course_logs_structure_step extends restore_structure_step {
2904     /**
2905      * Conditionally decide if this step should be executed.
2906      *
2907      * This function checks the following parameter:
2908      *
2909      *   1. the course/logs.xml file exists
2910      *
2911      * @return bool true is safe to execute, false otherwise
2912      */
2913     protected function execute_condition() {
2915         // Check it is included in the backup
2916         $fullpath = $this->task->get_taskbasepath();
2917         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2918         if (!file_exists($fullpath)) {
2919             // Not found, can't restore course logs
2920             return false;
2921         }
2923         return true;
2924     }
2926     protected function define_structure() {
2928         $paths = array();
2930         // Simple, one plain level of information contains them
2931         $paths[] = new restore_path_element('log', '/logs/log');
2933         return $paths;
2934     }
2936     protected function process_log($data) {
2937         global $DB;
2939         $data = (object)($data);
2941         $data->time = $this->apply_date_offset($data->time);
2942         $data->userid = $this->get_mappingid('user', $data->userid);
2943         $data->course = $this->get_courseid();
2944         $data->cmid = 0;
2946         // For any reason user wasn't remapped ok, stop processing this
2947         if (empty($data->userid)) {
2948             return;
2949         }
2951         // Everything ready, let's delegate to the restore_logs_processor
2953         // Set some fixed values that will save tons of DB requests
2954         $values = array(
2955             'course' => $this->get_courseid());
2956         // Get instance and process log record
2957         $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
2959         // If we have data, insert it, else something went wrong in the restore_logs_processor
2960         if ($data) {
2961             if (empty($data->url)) {
2962                 $data->url = '';
2963             }
2964             if (empty($data->info)) {
2965                 $data->info = '';
2966             }
2967             // Store the data in the legacy log table if we are still using it.
2968             $manager = get_log_manager();
2969             if (method_exists($manager, 'legacy_add_to_log')) {
2970                 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
2971                     $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
2972             }
2973         }
2974     }
2977 /**
2978  * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
2979  * sharing its same structure but modifying the way records are handled
2980  */
2981 class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
2983     protected function process_log($data) {
2984         global $DB;
2986         $data = (object)($data);
2988         $data->time = $this->apply_date_offset($data->time);
2989         $data->userid = $this->get_mappingid('user', $data->userid);
2990         $data->course = $this->get_courseid();
2991         $data->cmid = $this->task->get_moduleid();
2993         // For any reason user wasn't remapped ok, stop processing this
2994         if (empty($data->userid)) {
2995             return;
2996         }
2998         // Everything ready, let's delegate to the restore_logs_processor
3000         // Set some fixed values that will save tons of DB requests
3001         $values = array(
3002             'course' => $this->get_courseid(),
3003             'course_module' => $this->task->get_moduleid(),
3004             $this->task->get_modulename() => $this->task->get_activityid());
3005         // Get instance and process log record
3006         $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3008         // If we have data, insert it, else something went wrong in the restore_logs_processor
3009         if ($data) {
3010             if (empty($data->url)) {
3011                 $data->url = '';
3012             }
3013             if (empty($data->info)) {
3014                 $data->info = '';
3015             }
3016             // Store the data in the legacy log table if we are still using it.
3017             $manager = get_log_manager();
3018             if (method_exists($manager, 'legacy_add_to_log')) {
3019                 $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3020                     $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3021             }
3022         }
3023     }
3026 /**
3027  * Structure step in charge of restoring the logstores.xml file for the course logs.
3028  *
3029  * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3030  * it, for logs belonging to the course level.
3031  */
3032 class restore_course_logstores_structure_step extends restore_structure_step {
3034     /**
3035      * Conditionally decide if this step should be executed.
3036      *
3037      * This function checks the following parameter:
3038      *
3039      *   1. the logstores.xml file exists
3040      *
3041      * @return bool true is safe to execute, false otherwise
3042      */
3043     protected function execute_condition() {
3045         // Check it is included in the backup.
3046         $fullpath = $this->task->get_taskbasepath();
3047         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3048         if (!file_exists($fullpath)) {
3049             // Not found, can't restore logstores.xml information.
3050             return false;
3051         }
3053         return true;
3054     }
3056     /**
3057      * Return the elements to be processed on restore of logstores.
3058      *
3059      * @return restore_path_element[] array of elements to be processed on restore.
3060      */
3061     protected function define_structure() {
3063         $paths = array();
3065         $logstore = new restore_path_element('logstore', '/logstores/logstore');
3066         $paths[] = $logstore;
3068         // Add logstore subplugin support to the 'logstore' element.
3069         $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3071         return array($logstore);
3072     }
3074     /**
3075      * Process the 'logstore' element,
3076      *
3077      * Note: This is empty by definition in backup, because stores do not share any
3078      * data between them, so there is nothing to process here.
3079      *
3080      * @param array $data element data
3081      */
3082     protected function process_logstore($data) {
3083         return;
3084     }
3087 /**
3088  * Structure step in charge of restoring the logstores.xml file for the activity logs.
3089  *
3090  * Note: Activity structure is completely equivalent to the course one, so just extend it.
3091  */
3092 class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3095 /**
3096  * Restore course competencies structure step.
3097  */
3098 class restore_course_competencies_structure_step extends restore_structure_step {
3100     /**
3101      * Returns the structure.
3102      *
3103      * @return array
3104      */
3105     protected function define_structure() {
3106         $userinfo = $this->get_setting_value('users');
3107         $paths = array(
3108             new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3109             new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3110         );
3111         if ($userinfo) {
3112             $paths[] = new restore_path_element('user_competency_course',
3113                 '/course_competencies/user_competencies/user_competency');
3114         }
3115         return $paths;
3116     }
3118     /**
3119      * Process a course competency settings.
3120      *
3121      * @param array $data The data.
3122      */
3123     public function process_course_competency_settings($data) {
3124         global $DB;
3125         $data = (object) $data;
3127         // We do not restore the course settings during merge.
3128         $target = $this->get_task()->get_target();
3129         if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) {
3130             return;
3131         }
3133         $courseid = $this->task->get_courseid();
3134         $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3135             array('courseid' => $courseid));
3137         // Strangely the course settings already exist, let's just leave them as is then.
3138         if ($exists) {
3139             $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING);
3140             return;
3141         }
3143         $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3144         $settings = new \core_competency\course_competency_settings(0, $data);
3145         $settings->create();
3146     }
3148     /**
3149      * Process a course competency.
3150      *
3151      * @param array $data The data.
3152      */
3153     public function process_course_competency($data) {
3154         $data = (object) $data;
3156         // Mapping the competency by ID numbers.
3157         $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3158         if (!$framework) {
3159             return;
3160         }
3161         $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3162             'competencyframeworkid' => $framework->get_id()));
3163         if (!$competency) {
3164             return;
3165         }
3166         $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get_id());
3168         $params = array(
3169             'competencyid' => $competency->get_id(),
3170             'courseid' => $this->task->get_courseid()
3171         );
3172         $query = 'competencyid = :competencyid AND courseid = :courseid';
3173         $existing = \core_competency\course_competency::record_exists_select($query, $params);
3175         if (!$existing) {
3176             // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3177             $record = (object) $params;
3178             $record->ruleoutcome = $data->ruleoutcome;
3179             $coursecompetency = new \core_competency\course_competency(0, $record);
3180             $coursecompetency->create();
3181         }
3182     }
3184     /**
3185      * Process the user competency course.
3186      *
3187      * @param array $data The data.
3188      */
3189     public function process_user_competency_course($data) {
3190         global $USER, $DB;
3191         $data = (object) $data;
3193         $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid);
3194         if (!$data->competencyid) {
3195             // This is strange, the competency does not belong to the course.
3196             return;
3197         } else if ($data->grade === null) {
3198             // We do not need to do anything when there is no grade.
3199             return;
3200         }
3202         $data->userid = $this->get_mappingid('user', $data->userid);
3203         $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
3205         // The method add_evidence also sets the course rating.
3206         \core_competency\api::add_evidence($data->userid,
3207                                            $data->competencyid,
3208                                            $this->task->get_contextid(),
3209                                            \core_competency\evidence::ACTION_OVERRIDE,
3210                                            'evidence_courserestored',
3211                                            'core_competency',
3212                                            $shortname,
3213                                            false,
3214                                            null,
3215                                            $data->grade,
3216                                            $USER->id);
3217     }
3219     /**
3220      * Execute conditions.
3221      *
3222      * @return bool
3223      */
3224     protected function execute_condition() {
3226         // Do not execute if competencies are not included.
3227         if (!$this->get_setting_value('competencies')) {
3228             return false;
3229         }
3231         // Do not execute if the competencies XML file is not found.
3232         $fullpath = $this->task->get_taskbasepath();
3233         $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3234         if (!file_exists($fullpath)) {
3235             return false;
3236         }
3238         return true;
3239     }
3242 /**
3243  * Restore activity competencies structure step.
3244  */
3245 class restore_activity_competencies_structure_step extends restore_structure_step {
3247     /**