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