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