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