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