MDL-26513 restore - observe target site restrictmodulesfor setting
[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/**
19 * @package moodlecore
20 * @subpackage backup-moodle2
21 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25/**
26 * Define all the restore steps that will be used by common tasks in restore
27 */
28
29/**
30 * delete old directories and conditionally create backup_temp_ids table
31 */
32class restore_create_and_clean_temp_stuff extends restore_execution_step {
33
34 protected function define_execution() {
b8bb45b0 35 $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
482aac65
EL
36 // If the table already exists, it's because restore_prechecks have been executed in the same
37 // request (without problems) and it already contains a bunch of preloaded information (users...)
38 // that we aren't going to execute again
39 if ($exists) { // Inform plan about preloaded information
40 $this->task->set_preloaded_information();
41 }
76cfb124
EL
42 // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
43 $itemid = $this->task->get_old_contextid();
44 $newitemid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
45 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
c0440b3f
EL
46 // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
47 $itemid = $this->task->get_old_system_contextid();
48 $newitemid = get_context_instance(CONTEXT_SYSTEM)->id;
49 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
d90e49f2
EL
50 // Create the old-course-id to new-course-id mapping, we need that available since the beginning
51 $itemid = $this->task->get_old_courseid();
52 $newitemid = $this->get_courseid();
53 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
54
482aac65
EL
55 }
56}
57
58/**
59 * delete the temp dir used by backup/restore (conditionally),
60 * delete old directories and drop temp ids table
61 */
62class restore_drop_and_clean_temp_stuff extends restore_execution_step {
63
64 protected function define_execution() {
65 global $CFG;
b8bb45b0 66 restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
b1eaf633 67 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
482aac65 68 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
b1eaf633 69 backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
482aac65
EL
70 }
71 }
72}
73
0067d939
AD
74/**
75 * Restore calculated grade items, grade categories etc
76 */
9a20df96 77class restore_gradebook_structure_step extends restore_structure_step {
0067d939 78
a0d27102
AD
79 /**
80 * To conditionally decide if this step must be executed
81 * Note the "settings" conditions are evaluated in the
82 * corresponding task. Here we check for other conditions
83 * not being restore settings (files, site settings...)
84 */
85 protected function execute_condition() {
9a20df96 86 global $CFG, $DB;
a0d27102
AD
87
88 // No gradebook info found, don't execute
89 $fullpath = $this->task->get_taskbasepath();
90 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
91 if (!file_exists($fullpath)) {
92 return false;
93 }
94
58328ce8
EL
95 // Some module present in backup file isn't available to restore
96 // in this site, don't execute
97 if ($this->task->is_missing_modules()) {
98 return false;
99 }
100
101 // Some activity has been excluded to be restored, don't execute
102 if ($this->task->is_excluding_activities()) {
103 return false;
104 }
105
9a20df96
AD
106 // There should only be one grade category (the 1 associated with the course itself)
107 // If other categories already exist we're restoring into an existing course.
108 // Restoring categories into a course with an existing category structure is unlikely to go well
109 $category = new stdclass();
110 $category->courseid = $this->get_courseid();
111 $catcount = $DB->count_records('grade_categories', (array)$category);
112 if ($catcount>1) {
113 return false;
114 }
115
a0d27102
AD
116 // Arrived here, execute the step
117 return true;
118 }
119
0067d939
AD
120 protected function define_structure() {
121 $paths = array();
122 $userinfo = $this->task->get_setting_value('users');
123
124 $paths[] = new restore_path_element('gradebook', '/gradebook');
125 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
126 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
127 if ($userinfo) {
128 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
129 }
130 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
b8040c83 131 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
0067d939
AD
132
133 return $paths;
134 }
135
136 protected function process_gradebook($data) {
137 }
138
139 protected function process_grade_item($data) {
140 global $DB;
141
142 $data = (object)$data;
143
144 $oldid = $data->id;
145 $data->course = $this->get_courseid();
146
147 $data->courseid = $this->get_courseid();
148
149 //manual grade items store category id in categoryid
150 if ($data->itemtype=='manual') {
151 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid);
152 } //course and category grade items store their category id in iteminstance
153 else if ($data->itemtype=='course' || $data->itemtype=='category') {
154 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance);
155 }
156
157 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
158 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
159
160 $data->locktime = $this->apply_date_offset($data->locktime);
161 $data->timecreated = $this->apply_date_offset($data->timecreated);
162 $data->timemodified = $this->apply_date_offset($data->timemodified);
163
44a25cd2 164 $coursecategory = $newitemid = null;
0067d939
AD
165 //course grade item should already exist so updating instead of inserting
166 if($data->itemtype=='course') {
167
168 //get the ID of the already created grade item
169 $gi = new stdclass();
170 $gi->courseid = $this->get_courseid();
171
172 $gi->itemtype = $data->itemtype;
173 if ($data->itemtype=='course') {
174 //need to get the id of the grade_category that was automatically created for the course
175 $category = new stdclass();
176 $category->courseid = $this->get_courseid();
177 $category->parent = null;
9a20df96
AD
178 //course category fullname starts out as ? but may be edited
179 //$category->fullname = '?';
0067d939
AD
180
181 $coursecategory = $DB->get_record('grade_categories', (array)$category);
182 $gi->iteminstance = $coursecategory->id;
183 }
184
185 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
44a25cd2
AD
186 if (!empty($existinggradeitem)) {
187 $data->id = $newitemid = $existinggradeitem->id;
188 $DB->update_record('grade_items', $data);
189 }
190 }
0067d939 191
44a25cd2
AD
192 if (empty($newitemid)) {
193 //in case we found the course category but still need to insert the course grade item
194 if ($data->itemtype=='course' && !empty($coursecategory)) {
195 $data->iteminstance = $coursecategory->id;
196 }
034ef761 197
0067d939
AD
198 $newitemid = $DB->insert_record('grade_items', $data);
199 }
200 $this->set_mapping('grade_item', $oldid, $newitemid);
201 }
202
203 protected function process_grade_grade($data) {
204 global $DB;
205
206 $data = (object)$data;
207 $oldid = $data->id;
208
209 $data->itemid = $this->get_new_parentid('grade_item');
210
211 $data->userid = $this->get_mappingid('user', $data->userid);
212 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
213 $data->locktime = $this->apply_date_offset($data->locktime);
9a20df96
AD
214 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
215 $data->overridden = $this->apply_date_offset($data->overridden);
0067d939
AD
216 $data->timecreated = $this->apply_date_offset($data->timecreated);
217 $data->timemodified = $this->apply_date_offset($data->timemodified);
218
219 $newitemid = $DB->insert_record('grade_grades', $data);
0df2981f 220 //$this->set_mapping('grade_grade', $oldid, $newitemid);
0067d939
AD
221 }
222 protected function process_grade_category($data) {
223 global $DB;
224
225 $data = (object)$data;
226 $oldid = $data->id;
227
228 $data->course = $this->get_courseid();
229 $data->courseid = $data->course;
230
231 $data->timecreated = $this->apply_date_offset($data->timecreated);
232 $data->timemodified = $this->apply_date_offset($data->timemodified);
233
499dbce8
AD
234 $newitemid = null;
235 //no parent means a course level grade category. That may have been created when the course was created
0067d939 236 if(empty($data->parent)) {
499dbce8
AD
237 //parent was being saved as 0 when it should be null
238 $data->parent = null;
239
0067d939
AD
240 //get the already created course level grade category
241 $category = new stdclass();
499dbce8 242 $category->courseid = $this->get_courseid();
0067d939
AD
243
244 $coursecategory = $DB->get_record('grade_categories', (array)$category);
499dbce8
AD
245 if (!empty($coursecategory)) {
246 $data->id = $newitemid = $coursecategory->id;
247 $DB->update_record('grade_categories', $data);
248 }
249 }
0067d939 250
499dbce8
AD
251 //need to insert a course category
252 if (empty($newitemid)) {
0067d939
AD
253 $newitemid = $DB->insert_record('grade_categories', $data);
254 }
255 $this->set_mapping('grade_category', $oldid, $newitemid);
0067d939
AD
256 }
257 protected function process_grade_letter($data) {
258 global $DB;
259
260 $data = (object)$data;
261 $oldid = $data->id;
262
e101180d 263 $data->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
0067d939
AD
264
265 $newitemid = $DB->insert_record('grade_letters', $data);
266 $this->set_mapping('grade_letter', $oldid, $newitemid);
267 }
b8040c83
AD
268 protected function process_grade_setting($data) {
269 global $DB;
270
271 $data = (object)$data;
272 $oldid = $data->id;
273
274 $data->courseid = $this->get_courseid();
275
276 $newitemid = $DB->insert_record('grade_settings', $data);
0df2981f 277 //$this->set_mapping('grade_setting', $oldid, $newitemid);
b8040c83 278 }
0f94550c
AD
279
280 //put all activity grade items in the correct grade category and mark all for recalculation
c4d2c745
AD
281 protected function after_execute() {
282 global $DB;
283
c4d2c745
AD
284 $conditions = array(
285 'backupid' => $this->get_restoreid(),
286 'itemname' => 'grade_item'//,
287 //'itemid' => $itemid
288 );
289 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
290
291 if (!empty($rs)) {
292 foreach($rs as $grade_item_backup) {
0f94550c
AD
293 $updateobj = new stdclass();
294 $updateobj->id = $grade_item_backup->newitemid;
074a765f 295
0f94550c
AD
296 //if this is an activity grade item that needs to be put back in its correct category
297 if (!empty($grade_item_backup->parentitemid)) {
298 $updateobj->categoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid);
074a765f 299 } else {
0f94550c
AD
300 //mark course and category items as needing to be recalculated
301 $updateobj->needsupdate=1;
c4d2c745 302 }
0f94550c 303 $DB->update_record('grade_items', $updateobj);
9a20df96
AD
304 }
305 }
306 $rs->close();
0f94550c 307
9a20df96
AD
308 //need to correct the grade category path and parent
309 $conditions = array(
310 'courseid' => $this->get_courseid()
311 );
312 $grade_category = new stdclass();
034ef761 313
9a20df96
AD
314 $rs = $DB->get_recordset('grade_categories', $conditions);
315 if (!empty($rs)) {
316 //get all the parents correct first as grade_category::build_path() loads category parents from the DB
317 foreach($rs as $gc) {
318 if (!empty($gc->parent)) {
319 $grade_category->id = $gc->id;
320 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
321 $DB->update_record('grade_categories', $grade_category);
322 }
323 }
324 }
325 if (isset($grade_category->parent)) {
326 unset($grade_category->parent);
327 }
328 $rs->close();
329
330 $rs = $DB->get_recordset('grade_categories', $conditions);
331 if (!empty($rs)) {
332 //now we can rebuild all the paths
333 foreach($rs as $gc) {
334 $grade_category->id = $gc->id;
335 $grade_category->path = grade_category::build_path($gc);
336 $DB->update_record('grade_categories', $grade_category);
c4d2c745
AD
337 }
338 }
339 $rs->close();
340 }
0067d939
AD
341}
342
394edb7e
EL
343/**
344 * decode all the interlinks present in restored content
345 * relying 100% in the restore_decode_processor that handles
346 * both the contents to modify and the rules to be applied
347 */
348class restore_decode_interlinks extends restore_execution_step {
349
350 protected function define_execution() {
9f68f2d5
EL
351 // Get the decoder (from the plan)
352 $decoder = $this->task->get_decoder();
353 restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
354 // And launch it, everything will be processed
355 $decoder->execute();
394edb7e
EL
356 }
357}
358
359/**
e3c2e1b2
EL
360 * first, ensure that we have no gaps in section numbers
361 * and then, rebuid the course cache
394edb7e
EL
362 */
363class restore_rebuild_course_cache extends restore_execution_step {
364
365 protected function define_execution() {
e3c2e1b2
EL
366 global $DB;
367
368 // Although there is some sort of auto-recovery of missing sections
369 // present in course/formats... here we check that all the sections
370 // from 0 to MAX(section->section) exist, creating them if necessary
371 $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
372 // Iterate over all sections
373 for ($i = 0; $i <= $maxsection; $i++) {
374 // If the section $i doesn't exist, create it
375 if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
376 $sectionrec = array(
377 'course' => $this->get_courseid(),
378 'section' => $i);
379 $DB->insert_record('course_sections', $sectionrec); // missing section created
380 }
381 }
382
383 // Rebuild cache now that all sections are in place
394edb7e
EL
384 rebuild_course_cache($this->get_courseid());
385 }
386}
387
648a575e
EL
388/**
389 * Review all the tasks having one after_restore method
390 * executing it to perform some final adjustments of information
391 * not available when the task was executed.
392 */
393class restore_execute_after_restore extends restore_execution_step {
394
395 protected function define_execution() {
396
397 // Simply call to the execute_after_restore() method of the task
398 // that always is the restore_final_task
399 $this->task->launch_execute_after_restore();
400 }
401}
402
b8e455a7
EL
403
404/**
405 * Review all the (pending) block positions in backup_ids, matching by
406 * contextid, creating positions as needed. This is executed by the
407 * final task, once all the contexts have been created
408 */
409class restore_review_pending_block_positions extends restore_execution_step {
410
411 protected function define_execution() {
412 global $DB;
413
414 // Get all the block_position objects pending to match
415 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
416 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
417 // Process block positions, creating them or accumulating for final step
418 foreach($rs as $posrec) {
419 // Get the complete position object (stored as info)
420 $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
421 // If position is for one already mapped (known) contextid
422 // process it now, creating the position, else nothing to
423 // do, position finally discarded
424 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
425 $position->contextid = $newctx->newitemid;
426 // Create the block position
427 $DB->insert_record('block_positions', $position);
428 }
429 }
430 $rs->close();
431 }
432}
433
5095f325
EL
434/**
435 * Process all the saved module availability records in backup_ids, matching
436 * course modules and grade item id once all them have been already restored.
437 * only if all matchings are satisfied the availability condition will be created.
438 * At the same time, it is required for the site to have that functionality enabled.
439 */
440class restore_process_course_modules_availability extends restore_execution_step {
441
442 protected function define_execution() {
443 global $CFG, $DB;
444
445 // Site hasn't availability enabled
446 if (empty($CFG->enableavailability)) {
447 return;
448 }
449
450 // Get all the module_availability objects to process
451 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
452 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
453 // Process availabilities, creating them if everything matches ok
454 foreach($rs as $availrec) {
455 $allmatchesok = true;
456 // Get the complete availabilityobject
457 $availability = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_availability', $availrec->itemid)->info;
458 // Map the sourcecmid if needed and possible
459 if (!empty($availability->sourcecmid)) {
460 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
461 if ($newcm) {
462 $availability->sourcecmid = $newcm->newitemid;
463 } else {
464 $allmatchesok = false; // Failed matching, we won't create this availability rule
465 }
466 }
467 // Map the gradeitemid if needed and possible
468 if (!empty($availability->gradeitemid)) {
469 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
470 if ($newgi) {
471 $availability->gradeitemid = $newgi->newitemid;
472 } else {
473 $allmatchesok = false; // Failed matching, we won't create this availability rule
474 }
475 }
476 if ($allmatchesok) { // Everything ok, create the availability rule
477 $DB->insert_record('course_modules_availability', $availability);
478 }
479 }
480 $rs->close();
481 }
482}
483
484
482aac65
EL
485/*
486 * Execution step that, *conditionally* (if there isn't preloaded information)
487 * will load the inforef files for all the included course/section/activity tasks
488 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
489 */
490class restore_load_included_inforef_records extends restore_execution_step {
491
492 protected function define_execution() {
493
494 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
495 return;
496 }
497
648a575e
EL
498 // Get all the included tasks
499 $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
500 foreach ($tasks as $task) {
501 // Load the inforef.xml file if exists
502 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
503 if (file_exists($inforefpath)) {
504 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath); // Load each inforef file to temp_ids
505 }
482aac65
EL
506 }
507 }
508}
509
76cfb124 510/*
b8bb45b0 511 * Execution step that will load all the needed files into backup_files_temp
76cfb124
EL
512 * - info: contains the whole original object (times, names...)
513 * (all them being original ids as loaded from xml)
514 */
515class restore_load_included_files extends restore_structure_step {
516
517 protected function define_structure() {
518
519 $file = new restore_path_element('file', '/files/file');
520
521 return array($file);
522 }
523
524 // Processing functions go here
525 public function process_file($data) {
526
527 $data = (object)$data; // handy
528
76cfb124
EL
529 // load it if needed:
530 // - it it is one of the annotated inforef files (course/section/activity/block)
41941110
EL
531 // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
532 // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
533 // but then we'll need to change it to load plugins itself (because this is executed too early in restore)
b8bb45b0 534 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
71a50b13 535 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
41941110
EL
536 $data->component == 'grouping' || $data->component == 'grade' ||
537 $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
76cfb124 538 if ($isfileref || $iscomponent) {
b8bb45b0 539 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
76cfb124
EL
540 }
541 }
542}
543
71a50b13
EL
544/**
545 * Execution step that, *conditionally* (if there isn't preloaded information),
546 * will load all the needed roles to backup_temp_ids. They will be stored with
547 * "role" itemname. Also it will perform one automatic mapping to roles existing
548 * in the target site, based in permissions of the user performing the restore,
549 * archetypes and other bits. At the end, each original role will have its associated
550 * target role or 0 if it's going to be skipped. Note we wrap everything over one
551 * restore_dbops method, as far as the same stuff is going to be also executed
552 * by restore prechecks
553 */
554class restore_load_and_map_roles extends restore_execution_step {
555
556 protected function define_execution() {
8d4e41f4 557 if ($this->task->get_preloaded_information()) { // if info is already preloaded
71a50b13
EL
558 return;
559 }
560
561 $file = $this->get_basepath() . '/roles.xml';
562 // Load needed toles to temp_ids
563 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
8d4e41f4 564
71a50b13 565 // Process roles, mapping/skipping. Any error throws exception
8d4e41f4
EL
566 // Note we pass controller's info because it can contain role mapping information
567 // about manual mappings performed by UI
568 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
569 }
570}
571
482aac65
EL
572/**
573 * Execution step that, *conditionally* (if there isn't preloaded information
574 * and users have been selected in settings, will load all the needed users
575 * to backup_temp_ids. They will be stored with "user" itemname and with
76cfb124 576 * their original contextid as paremitemid
482aac65
EL
577 */
578class restore_load_included_users extends restore_execution_step {
579
580 protected function define_execution() {
581
582 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
583 return;
584 }
25d3cf44 585 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
482aac65
EL
586 return;
587 }
588 $file = $this->get_basepath() . '/users.xml';
589 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
590 }
591}
592
593/**
594 * Execution step that, *conditionally* (if there isn't preloaded information
595 * and users have been selected in settings, will process all the needed users
596 * in order to decide and perform any action with them (create / map / error)
597 * Note: Any error will cause exception, as far as this is the same processing
598 * than the one into restore prechecks (that should have stopped process earlier)
599 */
76cfb124 600class restore_process_included_users extends restore_execution_step {
482aac65
EL
601
602 protected function define_execution() {
603
604 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
605 return;
606 }
25d3cf44 607 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
482aac65
EL
608 return;
609 }
610 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
611 }
612}
613
76cfb124
EL
614/**
615 * Execution step that will create all the needed users as calculated
616 * by @restore_process_included_users (those having newiteind = 0)
617 */
618class restore_create_included_users extends restore_execution_step {
619
620 protected function define_execution() {
621
b212f87e 622 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->get_setting_value('user_files'), $this->task->get_userid());
76cfb124
EL
623 }
624}
625
626/**
627 * Structure step that will create all the needed groups and groupings
628 * by loading them from the groups.xml file performing the required matches.
629 * Note group members only will be added if restoring user info
630 */
631class restore_groups_structure_step extends restore_structure_step {
632
c0440b3f
EL
633 protected function define_structure() {
634
635 $paths = array(); // Add paths here
636
637 $paths[] = new restore_path_element('group', '/groups/group');
638 if ($this->get_setting_value('users')) {
639 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
640 }
641 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
642 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
643
644 return $paths;
645 }
646
647 // Processing functions go here
648 public function process_group($data) {
649 global $DB;
650
651 $data = (object)$data; // handy
652 $data->courseid = $this->get_courseid();
653
654 $oldid = $data->id; // need this saved for later
76cfb124 655
c0440b3f
EL
656 $restorefiles = false; // Only if we end creating the group
657
658 // Search if the group already exists (by name & description) in the target course
659 $description_clause = '';
660 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
661 if (!empty($data->description)) {
662 $description_clause = ' AND ' .
d84fe4c8
EL
663 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
664 $params['description'] = $data->description;
c0440b3f
EL
665 }
666 if (!$groupdb = $DB->get_record_sql("SELECT *
667 FROM {groups}
668 WHERE courseid = :courseid
669 AND name = :grname $description_clause", $params)) {
670 // group doesn't exist, create
671 $newitemid = $DB->insert_record('groups', $data);
672 $restorefiles = true; // We'll restore the files
673 } else {
674 // group exists, use it
675 $newitemid = $groupdb->id;
676 }
677 // Save the id mapping
678 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
679 }
680
681 public function process_member($data) {
682 global $DB;
683
684 $data = (object)$data; // handy
685
686 // get parent group->id
687 $data->groupid = $this->get_new_parentid('group');
688
689 // map user newitemid and insert if not member already
690 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
691 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
692 $DB->insert_record('groups_members', $data);
693 }
694 }
695 }
696
697 public function process_grouping($data) {
71a50b13
EL
698 global $DB;
699
700 $data = (object)$data; // handy
701 $data->courseid = $this->get_courseid();
702
703 $oldid = $data->id; // need this saved for later
704 $restorefiles = false; // Only if we end creating the grouping
705
706 // Search if the grouping already exists (by name & description) in the target course
707 $description_clause = '';
708 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
709 if (!empty($data->description)) {
710 $description_clause = ' AND ' .
d84fe4c8
EL
711 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
712 $params['description'] = $data->description;
71a50b13
EL
713 }
714 if (!$groupingdb = $DB->get_record_sql("SELECT *
715 FROM {groupings}
716 WHERE courseid = :courseid
717 AND name = :grname $description_clause", $params)) {
718 // grouping doesn't exist, create
719 $newitemid = $DB->insert_record('groupings', $data);
720 $restorefiles = true; // We'll restore the files
721 } else {
722 // grouping exists, use it
723 $newitemid = $groupingdb->id;
724 }
725 // Save the id mapping
726 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
c0440b3f
EL
727 }
728
729 public function process_grouping_group($data) {
71a50b13
EL
730 global $DB;
731
732 $data = (object)$data;
733
734 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
735 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
736 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
c0440b3f
EL
737 }
738
739 protected function after_execute() {
740 // Add group related files, matching with "group" mappings
741 $this->add_related_files('group', 'icon', 'group');
742 $this->add_related_files('group', 'description', 'group');
71a50b13
EL
743 // Add grouping related files, matching with "grouping" mappings
744 $this->add_related_files('grouping', 'description', 'grouping');
c0440b3f
EL
745 }
746
747}
748
749/**
750 * Structure step that will create all the needed scales
751 * by loading them from the scales.xml
c0440b3f
EL
752 */
753class restore_scales_structure_step extends restore_structure_step {
754
755 protected function define_structure() {
756
757 $paths = array(); // Add paths here
758 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
759 return $paths;
760 }
761
762 protected function process_scale($data) {
763 global $DB;
764
765 $data = (object)$data;
766
767 $restorefiles = false; // Only if we end creating the group
768
769 $oldid = $data->id; // need this saved for later
770
771 // Look for scale (by 'scale' both in standard (course=0) and current course
772 // with priority to standard scales (ORDER clause)
773 // scale is not course unique, use get_record_sql to suppress warning
774 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
775 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
776 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
777 if (!$scadb = $DB->get_record_sql("SELECT *
778 FROM {scale}
779 WHERE courseid IN (0, :courseid)
780 AND $compare_scale_clause
781 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
782 // Remap the user if possible, defaut to user performing the restore if not
783 $userid = $this->get_mappingid('user', $data->userid);
ba8bead5 784 $data->userid = $userid ? $userid : $this->task->get_userid();
c0440b3f
EL
785 // Remap the course if course scale
786 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
787 // If global scale (course=0), check the user has perms to create it
788 // falling to course scale if not
789 $systemctx = get_context_instance(CONTEXT_SYSTEM);
394edb7e 790 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
c0440b3f
EL
791 $data->courseid = $this->get_courseid();
792 }
793 // scale doesn't exist, create
794 $newitemid = $DB->insert_record('scale', $data);
795 $restorefiles = true; // We'll restore the files
796 } else {
797 // scale exists, use it
798 $newitemid = $scadb->id;
799 }
800 // Save the id mapping (with files support at system context)
801 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
802 }
803
804 protected function after_execute() {
805 // Add scales related files, matching with "scale" mappings
806 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
807 }
76cfb124
EL
808}
809
c0440b3f 810
c8730ff0
EL
811/**
812 * Structure step that will create all the needed outocomes
813 * by loading them from the outcomes.xml
814 */
815class restore_outcomes_structure_step extends restore_structure_step {
816
817 protected function define_structure() {
818
819 $paths = array(); // Add paths here
820 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
821 return $paths;
822 }
823
824 protected function process_outcome($data) {
825 global $DB;
826
827 $data = (object)$data;
828
829 $restorefiles = false; // Only if we end creating the group
830
831 $oldid = $data->id; // need this saved for later
832
833 // Look for outcome (by shortname both in standard (courseid=null) and current course
834 // with priority to standard outcomes (ORDER clause)
835 // outcome is not course unique, use get_record_sql to suppress warning
836 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
837 if (!$outdb = $DB->get_record_sql('SELECT *
838 FROM {grade_outcomes}
839 WHERE shortname = :shortname
840 AND (courseid = :courseid OR courseid IS NULL)
841 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
842 // Remap the user
843 $userid = $this->get_mappingid('user', $data->usermodified);
ba8bead5 844 $data->usermodified = $userid ? $userid : $this->task->get_userid();
8d4e41f4
EL
845 // Remap the scale
846 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
c8730ff0
EL
847 // Remap the course if course outcome
848 $data->courseid = $data->courseid ? $this->get_courseid() : null;
849 // If global outcome (course=null), check the user has perms to create it
850 // falling to course outcome if not
851 $systemctx = get_context_instance(CONTEXT_SYSTEM);
394edb7e 852 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
c8730ff0
EL
853 $data->courseid = $this->get_courseid();
854 }
855 // outcome doesn't exist, create
856 $newitemid = $DB->insert_record('grade_outcomes', $data);
857 $restorefiles = true; // We'll restore the files
858 } else {
859 // scale exists, use it
860 $newitemid = $outdb->id;
861 }
862 // Set the corresponding grade_outcomes_courses record
863 $outcourserec = new stdclass();
864 $outcourserec->courseid = $this->get_courseid();
865 $outcourserec->outcomeid = $newitemid;
866 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
867 $DB->insert_record('grade_outcomes_courses', $outcourserec);
868 }
869 // Save the id mapping (with files support at system context)
870 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
871 }
872
873 protected function after_execute() {
874 // Add outcomes related files, matching with "outcome" mappings
875 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
876 }
877}
878
41941110
EL
879/**
880 * Execution step that, *conditionally* (if there isn't preloaded information
881 * will load all the question categories and questions (header info only)
882 * to backup_temp_ids. They will be stored with "question_category" and
883 * "question" itemnames and with their original contextid and question category
884 * id as paremitemids
885 */
886class restore_load_categories_and_questions extends restore_execution_step {
887
888 protected function define_execution() {
889
890 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
891 return;
892 }
893 $file = $this->get_basepath() . '/questions.xml';
894 restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
895 }
896}
897
898/**
899 * Execution step that, *conditionally* (if there isn't preloaded information)
900 * will process all the needed categories and questions
901 * in order to decide and perform any action with them (create / map / error)
902 * Note: Any error will cause exception, as far as this is the same processing
903 * than the one into restore prechecks (that should have stopped process earlier)
904 */
905class restore_process_categories_and_questions extends restore_execution_step {
906
907 protected function define_execution() {
908
909 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
910 return;
911 }
912 restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
913 }
914}
915
3223cc95
EL
916/**
917 * Structure step that will read the section.xml creating/updating sections
918 * as needed, rebuilding course cache and other friends
919 */
920class restore_section_structure_step extends restore_structure_step {
c8730ff0 921
3223cc95 922 protected function define_structure() {
a90659d6
EL
923 $section = new restore_path_element('section', '/section');
924
925 // Apply for 'format' plugins optional paths at section level
926 $this->add_plugin_structure('format', $section);
927
928 return array($section);
3223cc95
EL
929 }
930
931 public function process_section($data) {
932 global $DB;
933 $data = (object)$data;
934 $oldid = $data->id; // We'll need this later
935
936 $restorefiles = false;
937
938 // Look for the section
939 $section = new stdclass();
940 $section->course = $this->get_courseid();
941 $section->section = $data->number;
942 // Section doesn't exist, create it with all the info from backup
943 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
944 $section->name = $data->name;
945 $section->summary = $data->summary;
946 $section->summaryformat = $data->summaryformat;
947 $section->sequence = '';
948 $section->visible = $data->visible;
949 $newitemid = $DB->insert_record('course_sections', $section);
950 $restorefiles = true;
951
952 // Section exists, update non-empty information
953 } else {
954 $section->id = $secrec->id;
955 if (empty($secrec->name)) {
956 $section->name = $data->name;
957 }
958 if (empty($secrec->summary)) {
959 $section->summary = $data->summary;
960 $section->summaryformat = $data->summaryformat;
961 $restorefiles = true;
962 }
963 $DB->update_record('course_sections', $section);
964 $newitemid = $secrec->id;
965 }
966
967 // Annotate the section mapping, with restorefiles option if needed
968 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
969
a90659d6
EL
970 // set the new course_section id in the task
971 $this->task->set_sectionid($newitemid);
972
973
f81f5133
EL
974 // Commented out. We never modify course->numsections as far as that is used
975 // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
976 // Note: We keep the code here, to know about and because of the possibility of making this
977 // optional based on some setting/attribute in the future
3223cc95 978 // If needed, adjust course->numsections
f81f5133
EL
979 //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
980 // if ($numsections < $section->section) {
981 // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
982 // }
983 //}
3223cc95
EL
984 }
985
986 protected function after_execute() {
987 // Add section related files, with 'course_section' itemid to match
988 $this->add_related_files('course', 'section', 'course_section');
989 }
990}
991
992
993/**
482aac65 994 * Structure step that will read the course.xml file, loading it and performing
395dae30
EL
995 * various actions depending of the site/restore settings. Note that target
996 * course always exist before arriving here so this step will be updating
997 * the course record (never inserting)
482aac65
EL
998 */
999class restore_course_structure_step extends restore_structure_step {
1000
1001 protected function define_structure() {
1002
4fda584f 1003 $course = new restore_path_element('course', '/course');
482aac65
EL
1004 $category = new restore_path_element('category', '/course/category');
1005 $tag = new restore_path_element('tag', '/course/tags/tag');
4fda584f 1006 $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module');
482aac65 1007
4fda584f
EL
1008 // Apply for 'format' plugins optional paths at course level
1009 $this->add_plugin_structure('format', $course);
1010
1011 return array($course, $category, $tag, $allowed_module);
482aac65
EL
1012 }
1013
7f32340b
SH
1014 /**
1015 * Processing functions go here
1016 *
1017 * @global moodledatabase $DB
1018 * @param stdClass $data
1019 */
482aac65 1020 public function process_course($data) {
395dae30
EL
1021 global $CFG, $DB;
1022
1023 $data = (object)$data;
395dae30 1024 $oldid = $data->id; // We'll need this later
785d6603
SH
1025
1026 $fullname = $this->get_setting_value('course_fullname');
1027 $shortname = $this->get_setting_value('course_shortname');
b1eaf633 1028 $startdate = $this->get_setting_value('course_startdate');
395dae30
EL
1029
1030 // Calculate final course names, to avoid dupes
1031 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1032
1033 // Need to change some fields before updating the course record
1034 $data->id = $this->get_courseid();
1035 $data->fullname = $fullname;
1036 $data->shortname= $shortname;
1037 $data->idnumber = '';
7f32340b 1038
e4f72d14
EL
1039 // Only restrict modules if original course was and target site too for new courses
1040 $data->restrictmodules = $data->restrictmodules && !empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all';
1041
395dae30
EL
1042 $data->startdate= $this->apply_date_offset($data->startdate);
1043 if ($data->defaultgroupingid) {
1044 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1045 }
5095f325 1046 if (empty($CFG->enablecompletion)) {
395dae30
EL
1047 $data->enablecompletion = 0;
1048 $data->completionstartonenrol = 0;
1049 $data->completionnotify = 0;
1050 }
1051 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1052 if (!array_key_exists($data->lang, $languages)) {
1053 $data->lang = '';
1054 }
1055 $themes = get_list_of_themes(); // Get themes for quick search later
1056 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1057 $data->theme = '';
1058 }
1059
1060 // Course record ready, update it
1061 $DB->update_record('course', $data);
1062
4fda584f
EL
1063 // Role name aliases
1064 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1065 }
1066
1067 public function process_category($data) {
1068 // Nothing to do with the category. UI sets it before restore starts
1069 }
1070
1071 public function process_tag($data) {
1072 global $CFG, $DB;
1073
1074 $data = (object)$data;
1075
1076 if (!empty($CFG->usetags)) { // if enabled in server
1077 // TODO: This is highly inneficient. Each time we add one tag
1078 // we fetch all the existing because tag_set() deletes them
1079 // so everything must be reinserted on each call
395dae30 1080 $tags = array();
4fda584f
EL
1081 $existingtags = tag_get_tags('course', $this->get_courseid());
1082 // Re-add all the existitng tags
1083 foreach ($existingtags as $existingtag) {
1084 $tags[] = $existingtag->rawname;
395dae30 1085 }
4fda584f
EL
1086 // Add the one being restored
1087 $tags[] = $data->rawname;
1088 // Send all the tags back to the course
395dae30
EL
1089 tag_set('course', $this->get_courseid(), $tags);
1090 }
4fda584f
EL
1091 }
1092
1093 public function process_allowed_module($data) {
1094 global $CFG, $DB;
1095
1096 $data = (object)$data;
1097
1098 // only if enabled by admin setting
1099 if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all') {
395dae30 1100 $available = get_plugin_list('mod');
4fda584f
EL
1101 $mname = $data->modulename;
1102 if (array_key_exists($mname, $available)) {
1103 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
1104 $rec = new stdclass();
1105 $rec->course = $this->get_courseid();
1106 $rec->module = $module->id;
1107 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
1108 $DB->insert_record('course_allowed_modules', $rec);
395dae30
EL
1109 }
1110 }
1111 }
1112 }
482aac65
EL
1113 }
1114
395dae30
EL
1115 protected function after_execute() {
1116 // Add course related files, without itemid to match
1117 $this->add_related_files('course', 'summary', null);
1118 $this->add_related_files('course', 'legacy', null);
1119 }
482aac65 1120}
024c288d
EL
1121
1122
1123/*
1124 * Structure step that will read the roles.xml file (at course/activity/block levels)
1125 * containig all the role_assignments and overrides for that context. If corresponding to
1126 * one mapped role, they will be applied to target context. Will observe the role_assignments
1127 * setting to decide if ras are restored.
1128 * Note: only ras with component == null are restored as far as the any ra with component
1129 * is handled by one enrolment plugin, hence it will createt the ras later
1130 */
1131class restore_ras_and_caps_structure_step extends restore_structure_step {
1132
1133 protected function define_structure() {
1134
1135 $paths = array();
1136
1137 // Observe the role_assignments setting
1138 if ($this->get_setting_value('role_assignments')) {
1139 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1140 }
1141 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1142
1143 return $paths;
1144 }
1145
f2a9be5f
EL
1146 /**
1147 * Assign roles
1148 *
1149 * This has to be called after enrolments processing.
1150 *
1151 * @param mixed $data
1152 * @return void
1153 */
024c288d 1154 public function process_assignment($data) {
28b6ff82
EL
1155 global $DB;
1156
024c288d
EL
1157 $data = (object)$data;
1158
1159 // Check roleid, userid are one of the mapped ones
f2a9be5f
EL
1160 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1161 return;
1162 }
1163 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1164 return;
1165 }
1166 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
28b6ff82 1167 // Only assign roles to not deleted users
f2a9be5f
EL
1168 return;
1169 }
1170 if (!$contextid = $this->task->get_contextid()) {
1171 return;
1172 }
1173
1174 if (empty($data->component)) {
1175 // assign standard manual roles
1176 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1177 role_assign($newroleid, $newuserid, $contextid);
1178
1179 } else if ((strpos($data->component, 'enrol_') === 0)) {
1180 // Deal with enrolment roles
1181 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1182 if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
1183 //note: we have to verify component because it might have changed
1184 if ($component === 'enrol_manual') {
1185 // manual is a special case, we do not use components - this owudl happen when converting from other plugin
1186 role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
1187 } else {
1188 role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
1189 }
1190 }
28b6ff82 1191 }
024c288d
EL
1192 }
1193 }
1194
1195 public function process_override($data) {
1196 $data = (object)$data;
1197
1198 // Check roleid is one of the mapped ones
1199 $newroleid = $this->get_mappingid('role', $data->roleid);
b8e455a7
EL
1200 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1201 if ($newroleid && $this->task->get_contextid()) {
024c288d 1202 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
b8e455a7 1203 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
024c288d
EL
1204 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1205 }
1206 }
1207}
1208
1209/**
1210 * This structure steps restores the enrol plugins and their underlying
1211 * enrolments, performing all the mappings and/or movements required
1212 */
1213class restore_enrolments_structure_step extends restore_structure_step {
1214
1215 protected function define_structure() {
1216
1217 $paths = array();
1218
1219 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1220 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1221
1222 return $paths;
1223 }
1224
f2a9be5f
EL
1225 /**
1226 * Create enrolment instances.
1227 *
1228 * This has to be called after creation of roles
1229 * and before adding of role assignments.
1230 *
1231 * @param mixed $data
1232 * @return void
1233 */
024c288d
EL
1234 public function process_enrol($data) {
1235 global $DB;
1236
1237 $data = (object)$data;
1238 $oldid = $data->id; // We'll need this later
1239
f2a9be5f
EL
1240 $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);
1241
1242 if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
1243 // TODO: add complex restore support via custom class
1244 debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
1245 $this->set_mapping('enrol', $oldid, 0);
024c288d
EL
1246 return;
1247 }
1248
1249 // Perform various checks to decide what to do with the enrol plugin
f2a9be5f
EL
1250 if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
1251 // TODO: decide if we want to switch to manual enrol - we need UI for this
1252 debugging("Enrol plugin data can not be restored because it is not installed");
1253 $this->set_mapping('enrol', $oldid, 0);
1254 return;
1255
024c288d 1256 }
f2a9be5f
EL
1257 if (!enrol_is_enabled($data->enrol)) {
1258 // TODO: decide if we want to switch to manual enrol - we need UI for this
1259 debugging("Enrol plugin data can not be restored because it is not enabled");
1260 $this->set_mapping('enrol', $oldid, 0);
1261 return;
1262 }
1263
1264 // map standard fields - plugin has to process custom fields from own restore class
1265 $data->roleid = $this->get_mappingid('role', $data->roleid);
1266 //TODO: should we move the enrol start and end date here?
1267
1268 // always add instance, if the course does not support multiple instances it just returns NULL
1269 $enrol = enrol_get_plugin($data->enrol);
1270 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1271 if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
1272 // ok
1273 } else {
1274 if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
1275 // most probably plugin that supports only one instance
1276 $newitemid = key($instances);
024c288d 1277 } else {
f2a9be5f
EL
1278 debugging('Can not create new enrol instance or reuse existing');
1279 $newitemid = 0;
024c288d 1280 }
f2a9be5f 1281 }
024c288d 1282
f2a9be5f
EL
1283 if ($restoretype === ENROL_RESTORE_NOUSERS) {
1284 // plugin requests to prevent restore of any users
024c288d
EL
1285 $newitemid = 0;
1286 }
f2a9be5f 1287
024c288d
EL
1288 $this->set_mapping('enrol', $oldid, $newitemid);
1289 }
1290
f2a9be5f
EL
1291 /**
1292 * Create user enrolments
1293 *
1294 * This has to be called after creation of enrolment instances
1295 * and before adding of role assignments.
1296 *
1297 * @param mixed $data
1298 * @return void
1299 */
024c288d
EL
1300 public function process_enrolment($data) {
1301 global $DB;
1302
1303 $data = (object)$data;
1304
1305 // Process only if parent instance have been mapped
1306 if ($enrolid = $this->get_new_parentid('enrol')) {
f2a9be5f
EL
1307 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1308 // And only if user is a mapped one
1309 if ($userid = $this->get_mappingid('user', $data->userid)) {
1310 $enrol = enrol_get_plugin($instance->enrol);
1311 //TODO: do we need specify modifierid?
1312 $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
1313 //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
024c288d
EL
1314 }
1315 }
1316 }
1317 }
1318}
21e51c86
EL
1319
1320
1321/**
1322 * This structure steps restores the filters and their configs
1323 */
1324class restore_filters_structure_step extends restore_structure_step {
1325
1326 protected function define_structure() {
1327
1328 $paths = array();
1329
1330 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1331 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1332
1333 return $paths;
1334 }
1335
1336 public function process_active($data) {
1337
1338 $data = (object)$data;
1339
1340 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1341 return;
1342 }
1343 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1344 }
1345
1346 public function process_config($data) {
1347
1348 $data = (object)$data;
1349
1350 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1351 return;
1352 }
1353 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1354 }
1355}
1356
1357
1358/**
1359 * This structure steps restores the comments
1360 * Note: Cannot use the comments API because defaults to USER->id.
1361 * That should change allowing to pass $userid
1362 */
1363class restore_comments_structure_step extends restore_structure_step {
1364
1365 protected function define_structure() {
1366
1367 $paths = array();
1368
1369 $paths[] = new restore_path_element('comment', '/comments/comment');
1370
1371 return $paths;
1372 }
1373
1374 public function process_comment($data) {
1375 global $DB;
1376
1377 $data = (object)$data;
1378
1379 // First of all, if the comment has some itemid, ask to the task what to map
1380 $mapping = false;
21e51c86 1381 if ($data->itemid) {
39aa0280
EL
1382 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1383 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
21e51c86
EL
1384 }
1385 // Only restore the comment if has no mapping OR we have found the matching mapping
39aa0280 1386 if (!$mapping || $data->itemid) {
b8e455a7
EL
1387 // Only if user mapping and context
1388 $data->userid = $this->get_mappingid('user', $data->userid);
1389 if ($data->userid && $this->task->get_contextid()) {
21e51c86 1390 $data->contextid = $this->task->get_contextid();
b8e455a7
EL
1391 // Only if there is another comment with same context/user/timecreated
1392 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1393 if (!$DB->record_exists('comments', $params)) {
1394 $DB->insert_record('comments', $data);
1395 }
1396 }
1397 }
1398 }
1399}
1400
bd39b6f2
SH
1401class restore_course_completion_structure_step extends restore_structure_step {
1402
1403 /**
1404 * Conditionally decide if this step should be executed.
1405 *
1406 * This function checks parameters that are not immediate settings to ensure
1407 * that the enviroment is suitable for the restore of course completion info.
1408 *
1409 * This function checks the following four parameters:
1410 *
1411 * 1. Course completion is enabled on the site
1412 * 2. The backup includes course completion information
1413 * 3. All modules are restorable
1414 * 4. All modules are marked for restore.
1415 *
1416 * @return bool True is safe to execute, false otherwise
1417 */
1418 protected function execute_condition() {
1419 global $CFG;
1420
1421 // First check course completion is enabled on this site
1422 if (empty($CFG->enablecompletion)) {
1423 // Disabled, don't restore course completion
1424 return false;
1425 }
1426
1427 // Check it is included in the backup
1428 $fullpath = $this->task->get_taskbasepath();
1429 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1430 if (!file_exists($fullpath)) {
1431 // Not found, can't restore course completion
1432 return false;
1433 }
1434
1435 // Check we are able to restore all backed up modules
1436 if ($this->task->is_missing_modules()) {
1437 return false;
1438 }
1439
1440 // Finally check all modules within the backup are being restored.
1441 if ($this->task->is_excluding_activities()) {
1442 return false;
1443 }
1444
1445 return true;
1446 }
1447
1448 /**
1449 * Define the course completion structure
1450 *
1451 * @return array Array of restore_path_element
1452 */
1453 protected function define_structure() {
1454
1455 // To know if we are including user completion info
1456 $userinfo = $this->get_setting_value('userscompletion');
1457
1458 $paths = array();
1459 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1460 $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1461 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1462
1463 if ($userinfo) {
1464 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1465 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1466 }
1467
1468 return $paths;
1469
1470 }
1471
1472 /**
1473 * Process course completion criteria
1474 *
1475 * @global moodle_database $DB
1476 * @param stdClass $data
1477 */
1478 public function process_course_completion_criteria($data) {
1479 global $DB;
1480
1481 $data = (object)$data;
1482 $data->course = $this->get_courseid();
1483
1484 // Apply the date offset to the time end field
1485 $data->timeend = $this->apply_date_offset($data->timeend);
1486
1487 // Map the role from the criteria
1488 if (!empty($data->role)) {
1489 $data->role = $this->get_mappingid('role', $data->role);
1490 }
1491
aa548318
SH
1492 $skipcriteria = false;
1493
bd39b6f2
SH
1494 // If the completion criteria is for a module we need to map the module instance
1495 // to the new module id.
1496 if (!empty($data->moduleinstance) && !empty($data->module)) {
1497 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
aa548318
SH
1498 if (empty($data->moduleinstance)) {
1499 $skipcriteria = true;
1500 }
bd39b6f2
SH
1501 } else {
1502 $data->module = null;
1503 $data->moduleinstance = null;
1504 }
1505
1506 // We backup the course shortname rather than the ID so that we can match back to the course
bd39b6f2
SH
1507 if (!empty($data->courseinstanceshortname)) {
1508 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1509 if (!$courseinstanceid) {
1510 $skipcriteria = true;
1511 }
1512 } else {
1513 $courseinstanceid = null;
1514 }
1515 $data->courseinstance = $courseinstanceid;
1516
1517 if (!$skipcriteria) {
1518 $params = array(
1519 'course' => $data->course,
1520 'criteriatype' => $data->criteriatype,
1521 'enrolperiod' => $data->enrolperiod,
1522 'courseinstance' => $data->courseinstance,
1523 'module' => $data->module,
1524 'moduleinstance' => $data->moduleinstance,
1525 'timeend' => $data->timeend,
1526 'gradepass' => $data->gradepass,
1527 'role' => $data->role
1528 );
1529 $newid = $DB->insert_record('course_completion_criteria', $params);
1530 $this->set_mapping('course_completion_criteria', $data->id, $newid);
1531 }
1532 }
1533
1534 /**
1535 * Processes course compltion criteria complete records
1536 *
1537 * @global moodle_database $DB
1538 * @param stdClass $data
1539 */
1540 public function process_course_completion_crit_compl($data) {
1541 global $DB;
1542
1543 $data = (object)$data;
1544
1545 // This may be empty if criteria could not be restored
1546 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
034ef761 1547
bd39b6f2
SH
1548 $data->course = $this->get_courseid();
1549 $data->userid = $this->get_mappingid('user', $data->userid);
1550
1551 if (!empty($data->criteriaid) && !empty($data->userid)) {
1552 $params = array(
1553 'userid' => $data->userid,
1554 'course' => $data->course,
1555 'criteriaid' => $data->criteriaid,
1556 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1557 );
1558 if (isset($data->gradefinal)) {
1559 $params['gradefinal'] = $data->gradefinal;
1560 }
1561 if (isset($data->unenroled)) {
1562 $params['unenroled'] = $data->unenroled;
1563 }
1564 if (isset($data->deleted)) {
1565 $params['deleted'] = $data->deleted;
1566 }
1567 $DB->insert_record('course_completion_crit_compl', $params);
1568 }
1569 }
1570
1571 /**
1572 * Process course completions
1573 *
1574 * @global moodle_database $DB
1575 * @param stdClass $data
1576 */
1577 public function process_course_completions($data) {
1578 global $DB;
1579
1580 $data = (object)$data;
1581
1582 $data->course = $this->get_courseid();
1583 $data->userid = $this->get_mappingid('user', $data->userid);
1584
1585 if (!empty($data->userid)) {
1586 $params = array(
1587 'userid' => $data->userid,
1588 'course' => $data->course,
1589 'deleted' => $data->deleted,
1590 'timenotified' => $this->apply_date_offset($data->timenotified),
1591 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1592 'timestarted' => $this->apply_date_offset($data->timestarted),
1593 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1594 'reaggregate' => $data->reaggregate
1595 );
1596 $DB->insert_record('course_completions', $params);
1597 }
1598 }
1599
1600 /**
1601 * Process course completion notification records.
1602 *
1603 * Note: As of Moodle 2.0 this table is not being used however it has been
1604 * left in in the hopes that one day the functionality there will be completed
1605 *
1606 * @global moodle_database $DB
1607 * @param stdClass $data
1608 */
1609 public function process_course_completion_notify($data) {
1610 global $DB;
1611
1612 $data = (object)$data;
1613
1614 $data->course = $this->get_courseid();
1615 if (!empty($data->role)) {
1616 $data->role = $this->get_mappingid('role', $data->role);
1617 }
1618
1619 $params = array(
1620 'course' => $data->course,
1621 'role' => $data->role,
1622 'message' => $data->message,
1623 'timesent' => $this->apply_date_offset($data->timesent),
1624 );
1625 $DB->insert_record('course_completion_notify', $params);
1626 }
1627
1628 /**
1629 * Process course completion aggregate methods
1630 *
1631 * @global moodle_database $DB
1632 * @param stdClass $data
1633 */
1634 public function process_course_completion_aggr_methd($data) {
1635 global $DB;
1636
1637 $data = (object)$data;
1638
1639 $data->course = $this->get_courseid();
1640
1641 $params = array(
1642 'course' => $data->course,
1643 'criteriatype' => $data->criteriatype,
1644 'method' => $data->method,
1645 'value' => $data->value,
1646 );
1647 $DB->insert_record('course_completion_aggr_methd', $params);
1648 }
1649
1650}
1651
0f66aced
EL
1652
1653/**
1654 * This structure step restores course logs (cmid = 0), delegating
1655 * the hard work to the corresponding {@link restore_logs_processor} passing the
1656 * collection of {@link restore_log_rule} rules to be observed as they are defined
1657 * by the task. Note this is only executed based in the 'logs' setting.
1658 *
1659 * NOTE: This is executed by final task, to have all the activities already restored
1660 *
1661 * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
1662 * records are. There are others like 'calendar' and 'upload' that will be handled
1663 * later.
1664 *
1665 * NOTE: All the missing actions (not able to be restored) are sent to logs for
1666 * debugging purposes
1667 */
1668class restore_course_logs_structure_step extends restore_structure_step {
1669
1670 /**
1671 * Conditionally decide if this step should be executed.
1672 *
1673 * This function checks the following four parameters:
1674 *
1675 * 1. the course/logs.xml file exists
1676 *
1677 * @return bool true is safe to execute, false otherwise
1678 */
1679 protected function execute_condition() {
1680
1681 // Check it is included in the backup
1682 $fullpath = $this->task->get_taskbasepath();
1683 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1684 if (!file_exists($fullpath)) {
1685 // Not found, can't restore course logs
1686 return false;
1687 }
1688
1689 return true;
1690 }
1691
1692 protected function define_structure() {
1693
1694 $paths = array();
1695
1696 // Simple, one plain level of information contains them
1697 $paths[] = new restore_path_element('log', '/logs/log');
1698
1699 return $paths;
1700 }
1701
1702 protected function process_log($data) {
1703 global $DB;
1704
1705 $data = (object)($data);
1706
1707 $data->time = $this->apply_date_offset($data->time);
1708 $data->userid = $this->get_mappingid('user', $data->userid);
1709 $data->course = $this->get_courseid();
1710 $data->cmid = 0;
1711
1712 // For any reason user wasn't remapped ok, stop processing this
1713 if (empty($data->userid)) {
1714 return;
1715 }
1716
1717 // Everything ready, let's delegate to the restore_logs_processor
1718
1719 // Set some fixed values that will save tons of DB requests
1720 $values = array(
1721 'course' => $this->get_courseid());
1722 // Get instance and process log record
1723 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
1724
1725 // If we have data, insert it, else something went wrong in the restore_logs_processor
1726 if ($data) {
1727 $DB->insert_record('log', $data);
1728 }
1729 }
1730}
1731
1732/**
1733 * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
1734 * sharing its same structure but modifying the way records are handled
1735 */
1736class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
1737
1738 protected function process_log($data) {
1739 global $DB;
1740
1741 $data = (object)($data);
1742
1743 $data->time = $this->apply_date_offset($data->time);
1744 $data->userid = $this->get_mappingid('user', $data->userid);
1745 $data->course = $this->get_courseid();
1746 $data->cmid = $this->task->get_moduleid();
1747
1748 // For any reason user wasn't remapped ok, stop processing this
1749 if (empty($data->userid)) {
1750 return;
1751 }
1752
1753 // Everything ready, let's delegate to the restore_logs_processor
1754
1755 // Set some fixed values that will save tons of DB requests
1756 $values = array(
1757 'course' => $this->get_courseid(),
1758 'course_module' => $this->task->get_moduleid(),
1759 $this->task->get_modulename() => $this->task->get_activityid());
1760 // Get instance and process log record
1761 $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
1762
1763 // If we have data, insert it, else something went wrong in the restore_logs_processor
1764 if ($data) {
1765 $DB->insert_record('log', $data);
1766 }
1767 }
1768}
1769
9a1cfcbc
EL
1770/**
1771 * This structure step restores the grade items associated with one activity
1772 * All the grade items are made child of the "course" grade item but the original
1773 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
1774 * the complete gradebook (categories and calculations), that information is
1775 * available there
1776 */
1777class restore_activity_grades_structure_step extends restore_structure_step {
1778
1779 protected function define_structure() {
1780
1781 $paths = array();
1782 $userinfo = $this->get_setting_value('userinfo');
1783
1784 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
1785 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
1786 if ($userinfo) {
1787 $paths[] = new restore_path_element('grade_grade',
1788 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
1789 }
1790 return $paths;
1791 }
1792
1793 protected function process_grade_item($data) {
1794
1795 $data = (object)($data);
1796 $oldid = $data->id; // We'll need these later
1797 $oldparentid = $data->categoryid;
1798
1799 // make sure top course category exists, all grade items will be associated
1800 // to it. Later, if restoring the whole gradebook, categories will be introduced
1801 $coursecat = grade_category::fetch_course_category($this->get_courseid());
1802 $coursecatid = $coursecat->id; // Get the categoryid to be used
1803
1804 unset($data->id);
1805 $data->categoryid = $coursecatid;
1806 $data->courseid = $this->get_courseid();
1807 $data->iteminstance = $this->task->get_activityid();
1808 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
1809 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
1810 // so the best is to keep the ones already in the gradebook
1811 // Potential problem: duplicates if same items are restored more than once. :-(
1812 // This needs to be fixed in some way (outcomes & activities with multiple items)
1813 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
1814 // In any case, verify always for uniqueness
a789ac6f 1815 $data->idnumber = grade_verify_idnumber($data->idnumber, $this->get_courseid()) ? $data->idnumber : null;
9a1cfcbc
EL
1816 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1817 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
1818 $data->timecreated = $this->apply_date_offset($data->timecreated);
1819 $data->timemodified = $this->apply_date_offset($data->timemodified);
1820
d84fe4c8 1821 $gradeitem = new grade_item($data, false);
9a1cfcbc 1822 $gradeitem->insert('restore');
4d787d8a
AD
1823
1824 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
1825 $gradeitem->sortorder = $data->sortorder;
1826 $gradeitem->update('restore');
1827
dc362c44
EL
1828 // Set mapping, saving the original category id into parentitemid
1829 // gradebook restore (final task) will need it to reorganise items
1830 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
9a1cfcbc
EL
1831 }
1832
1833 protected function process_grade_grade($data) {
1834 $data = (object)($data);
1835
1836 unset($data->id);
1837 $data->itemid = $this->get_new_parentid('grade_item');
1838 $data->userid = $this->get_mappingid('user', $data->userid);
1839 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
1840 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
1841 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
1842 $data->overridden = $this->apply_date_offset($data->overridden);
1843
d84fe4c8 1844 $grade = new grade_grade($data, false);
9a1cfcbc
EL
1845 $grade->insert('restore');
1846 // no need to save any grade_grade mapping
1847 }
1848
1849 /**
1850 * process activity grade_letters. Note that, while these are possible,
1851 * because grade_letters are contextid based, in proctice, only course
1852 * context letters can be defined. So we keep here this method knowing
1853 * it won't be executed ever. gradebook restore will restore course letters.
1854 */
1855 protected function process_grade_letter($data) {
1856 global $DB;
1857
1858 $data = (object)$data;
1859
1860 $data->contextid = $this->task->get_contextid();
1861 $newitemid = $DB->insert_record('grade_letters', $data);
1862 // no need to save any grade_letter mapping
1863 }
1864}
1865
b8e455a7
EL
1866
1867/**
1868 * This structure steps restores one instance + positions of one block
1869 * Note: Positions corresponding to one existing context are restored
1870 * here, but all the ones having unknown contexts are sent to backup_ids
1871 * for a later chance to be restored at the end (final task)
1872 */
1873class restore_block_instance_structure_step extends restore_structure_step {
1874
1875 protected function define_structure() {
1876
1877 $paths = array();
1878
1879 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
1880 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
1881
1882 return $paths;
1883 }
1884
1885 public function process_block($data) {
0f8941e2 1886 global $DB, $CFG;
b8e455a7
EL
1887
1888 $data = (object)$data; // Handy
1889 $oldcontextid = $data->contextid;
1890 $oldid = $data->id;
1891 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1892
1893 // Look for the parent contextid
1894 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1895 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1896 }
1897
767cb7f0 1898 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
b8e455a7
EL
1899 // If there is already one block of that type in the parent context
1900 // and the block is not multiple, stop processing
767cb7f0
EL
1901 // Use blockslib loader / method executor
1902 if (!block_method_result($data->blockname, 'instance_allow_multiple')) {
0f8941e2
EL
1903 if ($DB->record_exists_sql("SELECT bi.id
1904 FROM {block_instances} bi
1905 JOIN {block} b ON b.name = bi.blockname
1906 WHERE bi.parentcontextid = ?
1907 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
1908 return false;
1909 }
b8e455a7
EL
1910 }
1911
1912 // If there is already one block of that type in the parent context
1913 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
1914 // stop processing
1915 $params = array(
1916 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
1917 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
1918 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
1919 if ($birecs = $DB->get_records('block_instances', $params)) {
1920 foreach($birecs as $birec) {
1921 if ($birec->configdata == $data->configdata) {
1922 return false;
1923 }
1924 }
1925 }
1926
1927 // Set task old contextid, blockid and blockname once we know them
1928 $this->task->set_old_contextid($oldcontextid);
1929 $this->task->set_old_blockid($oldid);
1930 $this->task->set_blockname($data->blockname);
1931
1932 // Let's look for anything within configdata neededing processing
1933 // (nulls and uses of legacy file.php)
1934 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1935 $configdata = (array)unserialize(base64_decode($data->configdata));
1936 foreach ($configdata as $attribute => $value) {
1937 if (in_array($attribute, $attrstotransform)) {
1938 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
1939 }
1940 }
1941 $data->configdata = base64_encode(serialize((object)$configdata));
1942 }
1943
1944 // Create the block instance
1945 $newitemid = $DB->insert_record('block_instances', $data);
1946 // Save the mapping (with restorefiles support)
1947 $this->set_mapping('block_instance', $oldid, $newitemid, true);
1948 // Create the block context
1949 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
1950 // Save the block contexts mapping and sent it to task
1951 $this->set_mapping('context', $oldcontextid, $newcontextid);
1952 $this->task->set_contextid($newcontextid);
1953 $this->task->set_blockid($newitemid);
1954
1955 // Restore block fileareas if declared
1956 $component = 'block_' . $this->task->get_blockname();
1957 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
1958 $this->add_related_files($component, $filearea, null);
1959 }
1960
1961 // Process block positions, creating them or accumulating for final step
1962 foreach($positions as $position) {
1963 $position = (object)$position;
1964 $position->blockinstanceid = $newitemid; // The instance is always the restored one
1965 // If position is for one already mapped (known) contextid
1966 // process it now, creating the position
1967 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
1968 $position->contextid = $newpositionctxid;
1969 // Create the block position
1970 $DB->insert_record('block_positions', $position);
1971
1972 // The position belongs to an unknown context, send it to backup_ids
1973 // to process them as part of the final steps of restore. We send the
1974 // whole $position object there, hence use the low level method.
1975 } else {
1976 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
21e51c86
EL
1977 }
1978 }
1979 }
1980}
394edb7e
EL
1981
1982/**
1983 * Structure step to restore common course_module information
1984 *
1985 * This step will process the module.xml file for one activity, in order to restore
1986 * the corresponding information to the course_modules table, skipping various bits
1987 * of information based on CFG settings (groupings, completion...) in order to fullfill
1988 * all the reqs to be able to create the context to be used by all the rest of steps
1989 * in the activity restore task
1990 */
1991class restore_module_structure_step extends restore_structure_step {
1992
1993 protected function define_structure() {
1994 global $CFG;
1995
1996 $paths = array();
1997
a90659d6
EL
1998 $module = new restore_path_element('module', '/module');
1999 $paths[] = $module;
394edb7e
EL
2000 if ($CFG->enableavailability) {
2001 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
2002 }
2003
a90659d6
EL
2004 // Apply for 'format' plugins optional paths at module level
2005 $this->add_plugin_structure('format', $module);
2006
394edb7e
EL
2007 return $paths;
2008 }
2009
2010 protected function process_module($data) {
2011 global $CFG, $DB;
2012
2013 $data = (object)$data;
2014 $oldid = $data->id;
2015
2016 $data->course = $this->task->get_courseid();
2017 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
aa39be20
EL
2018 // Map section (first try by course_section mapping match. Useful in course and section restores)
2019 $data->section = $this->get_mappingid('course_section', $data->sectionid);
2020 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
2021 $params = array(
2022 'course' => $this->get_courseid(),
2023 'section' => $data->sectionnumber);
2024 $data->section = $DB->get_field('course_sections', 'id', $params);
2025 }
2026 if (!$data->section) { // sectionnumber failed, try to get first section in course
2027 $params = array(
2028 'course' => $this->get_courseid());
2029 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
2030 }
2031 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
2032 $sectionrec = array(
2033 'course' => $this->get_courseid(),
2034 'section' => 0);
2035 $DB->insert_record('course_sections', $sectionrec); // section 0
2036 $sectionrec = array(
2037 'course' => $this->get_courseid(),
2038 'section' => 1);
2039 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
2040 }
394edb7e
EL
2041 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
2042 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
2043 $data->groupmembersonly = 0;
2044 }
2045 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
2046 $data->idnumber = '';
2047 }
5095f325 2048 if (empty($CFG->enablecompletion)) { // completion
394edb7e
EL
2049 $data->completion = 0;
2050 $data->completiongradeitemnumber = null;
2051 $data->completionview = 0;
2052 $data->completionexpected = 0;
2053 } else {
2054 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
2055 }
2056 if (empty($CFG->enableavailability)) {
2057 $data->availablefrom = 0;
2058 $data->availableuntil = 0;
2059 $data->showavailability = 0;
2060 } else {
2061 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
2062 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
2063 }
2064 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
2065
2066 // course_module record ready, insert it
2067 $newitemid = $DB->insert_record('course_modules', $data);
2068 // save mapping
2069 $this->set_mapping('course_module', $oldid, $newitemid);
2070 // set the new course_module id in the task
2071 $this->task->set_moduleid($newitemid);
2072 // we can now create the context safely
2073 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
2074 // set the new context id in the task
2075 $this->task->set_contextid($ctxid);
2076 // update sequence field in course_section
2077 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
2078 $sequence .= ',' . $newitemid;
2079 } else {
2080 $sequence = $newitemid;
2081 }
2082 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
2083 }
2084
2085
2086 protected function process_availability($data) {
394edb7e 2087 $data = (object)$data;
5095f325
EL
2088 // Simply going to store the whole availability record now, we'll process
2089 // all them later in the final task (once all actvivities have been restored)
2090 // Let's call the low level one to be able to store the whole object
2091 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
2092 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
2093 }
2094}
2095
2096/**
2097 * Structure step that will process the user activity completion
2098 * information if all these conditions are met:
2099 * - Target site has completion enabled ($CFG->enablecompletion)
2100 * - Activity includes completion info (file_exists)
2101 */
2102class restore_userscompletion_structure_step extends restore_structure_step {
2103
2104 /**
2105 * To conditionally decide if this step must be executed
2106 * Note the "settings" conditions are evaluated in the
2107 * corresponding task. Here we check for other conditions
2108 * not being restore settings (files, site settings...)
2109 */
2110 protected function execute_condition() {
2111 global $CFG;
2112
2113 // Completion disabled in this site, don't execute
2114 if (empty($CFG->enablecompletion)) {
2115 return false;
2116 }
2117
2118 // No user completion info found, don't execute
2119 $fullpath = $this->task->get_taskbasepath();
2120 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2121 if (!file_exists($fullpath)) {
2122 return false;
2123 }
2124
2125 // Arrived here, execute the step
2126 return true;
2127 }
2128
2129 protected function define_structure() {
2130
2131 $paths = array();
2132
2133 $paths[] = new restore_path_element('completion', '/completions/completion');
2134
2135 return $paths;
2136 }
2137
2138 protected function process_completion($data) {
2139 global $DB;
2140
2141 $data = (object)$data;
2142
2143 $data->coursemoduleid = $this->task->get_moduleid();
2144 $data->userid = $this->get_mappingid('user', $data->userid);
2145 $data->timemodified = $this->apply_date_offset($data->timemodified);
2146
2147 $DB->insert_record('course_modules_completion', $data);
394edb7e
EL
2148 }
2149}
2150
2151/**
2152 * Abstract structure step, parent of all the activity structure steps. Used to suuport
2153 * the main <activity ...> tag and process it. Also provides subplugin support for
2154 * activities.
2155 */
2156abstract class restore_activity_structure_step extends restore_structure_step {
2157
91d11057
EL
2158 protected function add_subplugin_structure($subplugintype, $element) {
2159
2160 global $CFG;
2161
2162 // Check the requested subplugintype is a valid one
2163 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
2164 if (!file_exists($subpluginsfile)) {
2165 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
2166 }
2167 include($subpluginsfile);
2168 if (!array_key_exists($subplugintype, $subplugins)) {
2169 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
2170 }
2171 // Get all the restore path elements, looking across all the subplugin dirs
2172 $subpluginsdirs = get_plugin_list($subplugintype);
2173 foreach ($subpluginsdirs as $name => $subpluginsdir) {
2174 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
2175 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
2176 if (file_exists($restorefile)) {
2177 require_once($restorefile);
2178 $restoresubplugin = new $classname($subplugintype, $name, $this);
2179 // Add subplugin paths to the step
2180 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
2181 }
2182 }
2183 }
2184
2185 /**
2186 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
2187 * have the parent task available for wrapping purposes (get course/context....)
2188 */
2189 public function get_task() {
2190 return $this->task;
394edb7e
EL
2191 }
2192
2193 /**
2194 * Adds support for the 'activity' path that is common to all the activities
2195 * and will be processed globally here
2196 */
2197 protected function prepare_activity_structure($paths) {
2198
2199 $paths[] = new restore_path_element('activity', '/activity');
2200
2201 return $paths;
2202 }
2203
2204 /**
2205 * Process the activity path, informing the task about various ids, needed later
2206 */
2207 protected function process_activity($data) {
2208 $data = (object)$data;
2209 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
2210 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
2211 $this->task->set_old_activityid($data->id); // Save old activityid in task
2212 }
2213
2214 /**
034ef761 2215 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
394edb7e
EL
2216 * and will adjust the new activity id (the instance) in various places
2217 */
2218 protected function apply_activity_instance($newitemid) {
2219 global $DB;
2220
2221 $this->task->set_activityid($newitemid); // Save activity id in task
2222 // Apply the id to course_sections->instanceid
2223 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
2224 // Do the mapping for modulename, preparing it for files by oldcontext
2225 $modulename = $this->task->get_modulename();
2226 $oldid = $this->task->get_old_activityid();
2227 $this->set_mapping($modulename, $oldid, $newitemid, true);
2228 }
2229}
41941110
EL
2230
2231/**
2232 * Structure step in charge of creating/mapping all the qcats and qs
2233 * by parsing the questions.xml file and checking it against the
2234 * results calculated by {@link restore_process_categories_and_questions}
2235 * and stored in backup_ids_temp
2236 */
2237class restore_create_categories_and_questions extends restore_structure_step {
2238
2239 protected function define_structure() {
2240
2241 $category = new restore_path_element('question_category', '/question_categories/question_category');
2242 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
2243
2244 // Apply for 'qtype' plugins optional paths at question level
2245 $this->add_plugin_structure('qtype', $question);
2246
2247 return array($category, $question);
2248 }
2249
2250 protected function process_question_category($data) {
2251 global $DB;
2252
2253 $data = (object)$data;
2254 $oldid = $data->id;
2255
2256 // Check we have one mapping for this category
2257 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
0149e6c7 2258 return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
41941110
EL
2259 }
2260
2261 // Check we have to create the category (newitemid = 0)
2262 if ($mapping->newitemid) {
2263 return; // newitemid != 0, this category is going to be mapped. Nothing to do
2264 }
2265
2266 // Arrived here, newitemid = 0, we need to create the category
2267 // we'll do it at parentitemid context, but for CONTEXT_MODULE
2268 // categories, that will be created at CONTEXT_COURSE and moved
2269 // to module context later when the activity is created
2270 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
2271 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
2272 }
2273 $data->contextid = $mapping->parentitemid;
2274
2275 // Let's create the question_category and save mapping
2276 $newitemid = $DB->insert_record('question_categories', $data);
2277 $this->set_mapping('question_category', $oldid, $newitemid);
2278 // Also annotate them as question_category_created, we need
2279 // that later when remapping parents
2280 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
2281 }
2282
2283 protected function process_question($data) {
2284 global $DB;
2285
2286 $data = (object)$data;
2287 $oldid = $data->id;
2288
2289 // Check we have one mapping for this question
2290 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
2291 return; // No mapping = this question doesn't need to be created/mapped
2292 }
2293
2294 // Get the mapped category (cannot use get_new_parentid() because not
2295 // all the categories have been created, so it is not always available
2296 // Instead we get the mapping for the question->parentitemid because
2297 // we have loaded qcatids there for all parsed questions
2298 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
2299
2300 $data->timecreated = $this->apply_date_offset($data->timecreated);
2301 $data->timemodified = $this->apply_date_offset($data->timemodified);
2302
2303 $userid = $this->get_mappingid('user', $data->createdby);
2304 $data->createdby = $userid ? $userid : $this->task->get_userid();
2305
2306 $userid = $this->get_mappingid('user', $data->modifiedby);
2307 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
2308
2309 // With newitemid = 0, let's create the question
2310 if (!$questionmapping->newitemid) {
2311 $newitemid = $DB->insert_record('question', $data);
2312 $this->set_mapping('question', $oldid, $newitemid);
2313 // Also annotate them as question_created, we need
2314 // that later when remapping parents (keeping the old categoryid as parentid)
2315 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
2316 } else {
2317 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
2318 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
2319 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
2320 }
2321
2322 // Note, we don't restore any question files yet
2323 // as far as the CONTEXT_MODULE categories still
2324 // haven't their contexts to be restored to
2325 // The {@link restore_create_question_files}, executed in the final step
2326 // step will be in charge of restoring all the question files
2327 }
2328
2329 protected function after_execute() {
2330 global $DB;
2331
2332 // First of all, recode all the created question_categories->parent fields
2333 $qcats = $DB->get_records('backup_ids_temp', array(
2334 'backupid' => $this->get_restoreid(),
2335 'itemname' => 'question_category_created'));
2336 foreach ($qcats as $qcat) {
2337 $newparent = 0;
2338 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
2339 // Get new parent (mapped or created, so we look in quesiton_category mappings)
2340 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2341 'backupid' => $this->get_restoreid(),
2342 'itemname' => 'question_category',
2343 'itemid' => $dbcat->parent))) {
2344 // contextids must match always, as far as we always include complete qbanks, just check it
2345 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
2346 if ($dbcat->contextid == $newparentctxid) {
2347 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
2348 } else {
2349 $newparent = 0; // No ctx match for both cats, no parent relationship
2350 }
2351 }
2352 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
2353 if (!$newparent) {
2354 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
2355 }
2356 }
2357
2358 // Now, recode all the created question->parent fields
2359 $qs = $DB->get_records('backup_ids_temp', array(
2360 'backupid' => $this->get_restoreid(),
2361 'itemname' => 'question_created'));
2362 foreach ($qs as $q) {
2363 $newparent = 0;
2364 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
2365 // Get new parent (mapped or created, so we look in question mappings)
2366 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2367 'backupid' => $this->get_restoreid(),
2368 'itemname' => 'question',
2369 'itemid' => $dbq->parent))) {
2370 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
2371 }
2372 }
2373
2374 // Note, we don't restore any question files yet
2375 // as far as the CONTEXT_MODULE categories still
2376 // haven't their contexts to be restored to
2377 // The {@link restore_create_question_files}, executed in the final step
2378 // step will be in charge of restoring all the question files
2379 }
2380}
2381
2382/**
2383 * Execution step that will move all the CONTEXT_MODULE question categories
2384 * created at early stages of restore in course context (because modules weren't
2385 * created yet) to their target module (matching by old-new-contextid mapping)
2386 */
2387class restore_move_module_questions_categories extends restore_execution_step {
2388
2389 protected function define_execution() {
2390 global $DB;
2391
2392 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
2393 foreach ($contexts as $contextid => $contextlevel) {
2394 // Only if context mapping exists (i.e. the module has been restored)
2395 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
2396 // Update all the qcats having their parentitemid set to the original contextid
2397 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
2398 FROM {backup_ids_temp}
2399 WHERE backupid = ?
2400 AND itemname = 'question_category'
2401 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
2402 foreach ($modulecats as $modulecat) {
2403 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
2404 // And set new contextid also in question_category mapping (will be
2405 // used by {@link restore_create_question_files} later
2406 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
2407 }
2408 }
2409 }
2410 }
2411}
2412
2413/**
2414 * Execution step that will create all the question/answers/qtype-specific files for the restored
2415 * questions. It must be executed after {@link restore_move_module_questions_categories}
2416 * because only then each question is in its final category and only then the
2417 * context can be determined
2418 *
2419 * TODO: Improve this. Instead of looping over each question, it can be reduced to
2420 * be done by contexts (this will save a huge ammount of queries)
2421 */
2422class restore_create_question_files extends restore_execution_step {
2423
2424 protected function define_execution() {
2425 global $DB;
2426
2427 // Let's process only created questions
2428 $questionsrs = $DB->get_recordset_sql("SELECT bi.itemid, bi.newitemid, bi.parentitemid, q.qtype
2429 FROM {backup_ids_temp} bi
2430 JOIN {question} q ON q.id = bi.newitemid
2431 WHERE bi.backupid = ?
2432 AND bi.itemname = 'question_created'", array($this->get_restoreid()));
2433 foreach ($questionsrs as $question) {
2434 // Get question_category mapping, it contains the target context for the question
2435 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $question->parentitemid)) {
2436 // Something went really wrong, cannot find the question_category for the question
2437 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
2438 continue;
2439 }
2440 // Calculate source and target contexts
2441 $oldctxid = $qcatmapping->info->contextid;
2442 $newctxid = $qcatmapping->parentitemid;
2443
2444 // Add common question files (question and question_answer ones)
2445 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
2446 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2447 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
2448 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2449 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
2450 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
2451 // Add qtype dependent files
2452 $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
2453 foreach ($components as $component => $fileareas) {
2454 foreach ($fileareas as $filearea => $mapping) {
2455 // Use itemid only if mapping is question_created
2456 $itemid = ($mapping == 'question_created') ? $question->itemid : null;
2457 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
2458 $oldctxid, $this->task->get_userid(), $mapping, $itemid, $newctxid, true);
2459 }
2460 }
2461 }
2462 $questionsrs->close();
2463 }
2464}
2465
2466/**
2467 * Abstract structure step, to be used by all the activities using core questions stuff
2468 * (like the quiz module), to support qtype plugins, states and sessions
2469 */
2470abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
2471
2472 /**
2473 * Attach below $element (usually attempts) the needed restore_path_elements
2474 * to restore question_states
2475 */
2476 protected function add_question_attempts_states($element, &$paths) {
2477 // Check $element is restore_path_element
2478 if (! $element instanceof restore_path_element) {
2479 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2480 }
2481 // Check $paths is one array
2482 if (!is_array($paths)) {
2483 throw new restore_step_exception('paths_must_be_array', $paths);
2484 }
2485 $paths[] = new restore_path_element('question_state', $element->get_path() . '/states/state');
2486 }
2487
2488 /**
2489 * Attach below $element (usually attempts) the needed restore_path_elements
2490 * to restore question_sessions
2491 */
2492 protected function add_question_attempts_sessions($element, &$paths) {
2493 // Check $element is restore_path_element
2494 if (! $element instanceof restore_path_element) {
2495 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2496 }
2497 // Check $paths is one array
2498 if (!is_array($paths)) {
2499 throw new restore_step_exception('paths_must_be_array', $paths);
2500 }
2501 $paths[] = new restore_path_element('question_session', $element->get_path() . '/sessions/session');
2502 }
2503
2504 /**
2505 * Process question_states
2506 */
2507 protected function process_question_state($data) {
2508 global $DB;
2509
2510 $data = (object)$data;
2511 $oldid = $data->id;
2512
2513 // Get complete question mapping, we'll need info
2514 $question = $this->get_mapping('question', $data->question);
2515
2516 // In the quiz_attempt mapping we are storing uniqueid
2517 // and not id, so this gets the correct question_attempt to point to
2518 $data->attempt = $this->get_new_parentid('quiz_attempt');
2519 $data->question = $question->newitemid;
2520 $data->answer = $this->restore_recode_answer($data, $question->info->qtype); // Delegate recoding of answer
2521 $data->timestamp= $this->apply_date_offset($data->timestamp);
2522
2523 // Everything ready, insert and create mapping (needed by question_sessions)
2524 $newitemid = $DB->insert_record('question_states', $data);
2525 $this->set_mapping('question_state', $oldid, $newitemid);
2526 }
2527
2528 /**
2529 * Process question_sessions
2530 */
2531 protected function process_question_session($data) {
2532 global $DB;
2533
2534 $data = (object)$data;
2535 $oldid = $data->id;
2536
2537 // In the quiz_attempt mapping we are storing uniqueid
2538 // and not id, so this gets the correct question_attempt to point to
2539 $data->attemptid = $this->get_new_parentid('quiz_attempt');
2540 $data->questionid = $this->get_mappingid('question', $data->questionid);
2541 $data->newest = $this->get_mappingid('question_state', $data->newest);
2542 $data->newgraded = $this->get_mappingid('question_state', $data->newgraded);
2543
2544 // Everything ready, insert (no mapping needed)
2545 $newitemid = $DB->insert_record('question_sessions', $data);
2546
2547 // Note: question_sessions haven't files associated. On purpose manualcomment is lacking
2548 // support for them, so we don't need to handle them here.
2549 }
2550
2551 /**
2552 * Given a list of question->ids, separated by commas, returns the
2553 * recoded list, with all the restore question mappings applied.
2554 * Note: Used by quiz->questions and quiz_attempts->layout
2555 * Note: 0 = page break (unconverted)
2556 */
2557 protected function questions_recode_layout($layout) {
2558 // Extracts question id from sequence
2559 if ($questionids = explode(',', $layout)) {
2560 foreach ($questionids as $id => $questionid) {
2561 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
2562 $newquestionid = $this->get_mappingid('question', $questionid);
2563 $questionids[$id] = $newquestionid;
2564 }
2565 }
2566 }
2567 return implode(',', $questionids);
2568 }
2569
2570 /**
2571 * Given one question_states record, return the answer
2572 * recoded pointing to all the restored stuff
2573 */
2574 public function restore_recode_answer($state, $qtype) {
2575 // Build one static cache to store {@link restore_qtype_plugin}
2576 // while we are needing them, just to save zillions of instantiations
2577 // or using static stuff that will break our nice API
2578 static $qtypeplugins = array();
2579
2580 // If we haven't the corresponding restore_qtype_plugin for current qtype
2581 // instantiate it and add to cache
2582 if (!isset($qtypeplugins[$qtype])) {
2583 $classname = 'restore_qtype_' . $qtype . '_plugin';
2584 if (class_exists($classname)) {
2585 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
2586 } else {
2587 $qtypeplugins[$qtype] = false;
2588 }
2589 }
2590 return !empty($qtypeplugins[$qtype]) ? $qtypeplugins[$qtype]->recode_state_answer($state) : $state->answer;
2591 }
2592}