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