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