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