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