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