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