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