NOBUG: Added support for after_restore() methods on restore. Will help some blocks.
[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 ' .
663 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
664 $params['desc'] = $data->description;
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 ' .
711 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
712 $params['desc'] = $data->description;
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
EL
922 protected function define_structure() {
923 return array(new restore_path_element('section', '/section'));
924 }
925
926 public function process_section($data) {
927 global $DB;
928 $data = (object)$data;
929 $oldid = $data->id; // We'll need this later
930
931 $restorefiles = false;
932
933 // Look for the section
934 $section = new stdclass();
935 $section->course = $this->get_courseid();
936 $section->section = $data->number;
937 // Section doesn't exist, create it with all the info from backup
938 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
939 $section->name = $data->name;
940 $section->summary = $data->summary;
941 $section->summaryformat = $data->summaryformat;
942 $section->sequence = '';
943 $section->visible = $data->visible;
944 $newitemid = $DB->insert_record('course_sections', $section);
945 $restorefiles = true;
946
947 // Section exists, update non-empty information
948 } else {
949 $section->id = $secrec->id;
950 if (empty($secrec->name)) {
951 $section->name = $data->name;
952 }
953 if (empty($secrec->summary)) {
954 $section->summary = $data->summary;
955 $section->summaryformat = $data->summaryformat;
956 $restorefiles = true;
957 }
958 $DB->update_record('course_sections', $section);
959 $newitemid = $secrec->id;
960 }
961
962 // Annotate the section mapping, with restorefiles option if needed
963 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
964
965 // If needed, adjust course->numsections
966 if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
967 if ($numsections < $section->section) {
968 $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
969 }
970 }
971 }
972
973 protected function after_execute() {
974 // Add section related files, with 'course_section' itemid to match
975 $this->add_related_files('course', 'section', 'course_section');
976 }
977}
978
979
980/**
482aac65 981 * Structure step that will read the course.xml file, loading it and performing
395dae30
EL
982 * various actions depending of the site/restore settings. Note that target
983 * course always exist before arriving here so this step will be updating
984 * the course record (never inserting)
482aac65
EL
985 */
986class restore_course_structure_step extends restore_structure_step {
987
988 protected function define_structure() {
989
990 $course = new restore_path_element('course', '/course', true); // Grouped
991 $category = new restore_path_element('category', '/course/category');
992 $tag = new restore_path_element('tag', '/course/tags/tag');
993 $allowed = new restore_path_element('allowed', '/course/allowed_modules/module');
994
995 return array($course, $category, $tag, $allowed);
996 }
997
7f32340b
SH
998 /**
999 * Processing functions go here
1000 *
1001 * @global moodledatabase $DB
1002 * @param stdClass $data
1003 */
482aac65 1004 public function process_course($data) {
395dae30
EL
1005 global $CFG, $DB;
1006
1007 $data = (object)$data;
1008 $coursetags = isset($data->tags['tag']) ? $data->tags['tag'] : array();
1009 $coursemodules = isset($data->allowed_modules['module']) ? $data->allowed_modules['module'] : array();
1010 $oldid = $data->id; // We'll need this later
785d6603
SH
1011
1012 $fullname = $this->get_setting_value('course_fullname');
1013 $shortname = $this->get_setting_value('course_shortname');
b1eaf633 1014 $startdate = $this->get_setting_value('course_startdate');
395dae30
EL
1015
1016 // Calculate final course names, to avoid dupes
1017 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
1018
1019 // Need to change some fields before updating the course record
1020 $data->id = $this->get_courseid();
1021 $data->fullname = $fullname;
1022 $data->shortname= $shortname;
1023 $data->idnumber = '';
7f32340b
SH
1024
1025 // Category is set by UI when choosing the destination
1026 unset($data->category);
1027
395dae30
EL
1028 $data->startdate= $this->apply_date_offset($data->startdate);
1029 if ($data->defaultgroupingid) {
1030 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1031 }
5095f325 1032 if (empty($CFG->enablecompletion)) {
395dae30
EL
1033 $data->enablecompletion = 0;
1034 $data->completionstartonenrol = 0;
1035 $data->completionnotify = 0;
1036 }
1037 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1038 if (!array_key_exists($data->lang, $languages)) {
1039 $data->lang = '';
1040 }
1041 $themes = get_list_of_themes(); // Get themes for quick search later
1042 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1043 $data->theme = '';
1044 }
1045
1046 // Course record ready, update it
1047 $DB->update_record('course', $data);
1048
1049 // Course tags
1050 if (!empty($CFG->usetags) && isset($coursetags)) { // if enabled in server and present in backup
1051 $tags = array();
1052 foreach ($coursetags as $coursetag) {
1053 $coursetag = (object)$coursetag;
1054 $tags[] = $coursetag->rawname;
1055 }
1056 tag_set('course', $this->get_courseid(), $tags);
1057 }
1058 // Course allowed modules
1059 if (!empty($data->restrictmodules) && !empty($coursemodules)) {
1060 $available = get_plugin_list('mod');
1061 foreach ($coursemodules as $coursemodule) {
1062 $mname = $coursemodule['modulename'];
1063 if (array_key_exists($mname, $available)) {
1064 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
1065 $rec = new stdclass();
1066 $rec->course = $this->get_courseid();
1067 $rec->module = $module->id;
1068 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
1069 $DB->insert_record('course_allowed_modules', $rec);
1070 }
1071 }
1072 }
1073 }
1074 }
1075 // Role name aliases
1076 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
482aac65
EL
1077 }
1078
395dae30
EL
1079 protected function after_execute() {
1080 // Add course related files, without itemid to match
1081 $this->add_related_files('course', 'summary', null);
1082 $this->add_related_files('course', 'legacy', null);
1083 }
482aac65 1084}
024c288d
EL
1085
1086
1087/*
1088 * Structure step that will read the roles.xml file (at course/activity/block levels)
1089 * containig all the role_assignments and overrides for that context. If corresponding to
1090 * one mapped role, they will be applied to target context. Will observe the role_assignments
1091 * setting to decide if ras are restored.
1092 * Note: only ras with component == null are restored as far as the any ra with component
1093 * is handled by one enrolment plugin, hence it will createt the ras later
1094 */
1095class restore_ras_and_caps_structure_step extends restore_structure_step {
1096
1097 protected function define_structure() {
1098
1099 $paths = array();
1100
1101 // Observe the role_assignments setting
1102 if ($this->get_setting_value('role_assignments')) {
1103 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1104 }
1105 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1106
1107 return $paths;
1108 }
1109
f2a9be5f
EL
1110 /**
1111 * Assign roles
1112 *
1113 * This has to be called after enrolments processing.
1114 *
1115 * @param mixed $data
1116 * @return void
1117 */
024c288d 1118 public function process_assignment($data) {
28b6ff82
EL
1119 global $DB;
1120
024c288d
EL
1121 $data = (object)$data;
1122
1123 // Check roleid, userid are one of the mapped ones
f2a9be5f
EL
1124 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1125 return;
1126 }
1127 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1128 return;
1129 }
1130 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
28b6ff82 1131 // Only assign roles to not deleted users
f2a9be5f
EL
1132 return;
1133 }
1134 if (!$contextid = $this->task->get_contextid()) {
1135 return;
1136 }
1137
1138 if (empty($data->component)) {
1139 // assign standard manual roles
1140 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1141 role_assign($newroleid, $newuserid, $contextid);
1142
1143 } else if ((strpos($data->component, 'enrol_') === 0)) {
1144 // Deal with enrolment roles
1145 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1146 if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
1147 //note: we have to verify component because it might have changed
1148 if ($component === 'enrol_manual') {
1149 // manual is a special case, we do not use components - this owudl happen when converting from other plugin
1150 role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
1151 } else {
1152 role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
1153 }
1154 }
28b6ff82 1155 }
024c288d
EL
1156 }
1157 }
1158
1159 public function process_override($data) {
1160 $data = (object)$data;
1161
1162 // Check roleid is one of the mapped ones
1163 $newroleid = $this->get_mappingid('role', $data->roleid);
b8e455a7
EL
1164 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1165 if ($newroleid && $this->task->get_contextid()) {
024c288d 1166 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
b8e455a7 1167 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
024c288d
EL
1168 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1169 }
1170 }
1171}
1172
1173/**
1174 * This structure steps restores the enrol plugins and their underlying
1175 * enrolments, performing all the mappings and/or movements required
1176 */
1177class restore_enrolments_structure_step extends restore_structure_step {
1178
1179 protected function define_structure() {
1180
1181 $paths = array();
1182
1183 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1184 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1185
1186 return $paths;
1187 }
1188
f2a9be5f
EL
1189 /**
1190 * Create enrolment instances.
1191 *
1192 * This has to be called after creation of roles
1193 * and before adding of role assignments.
1194 *
1195 * @param mixed $data
1196 * @return void
1197 */
024c288d
EL
1198 public function process_enrol($data) {
1199 global $DB;
1200
1201 $data = (object)$data;
1202 $oldid = $data->id; // We'll need this later
1203
f2a9be5f
EL
1204 $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);
1205
1206 if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
1207 // TODO: add complex restore support via custom class
1208 debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
1209 $this->set_mapping('enrol', $oldid, 0);
024c288d
EL
1210 return;
1211 }
1212
1213 // Perform various checks to decide what to do with the enrol plugin
f2a9be5f
EL
1214 if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
1215 // TODO: decide if we want to switch to manual enrol - we need UI for this
1216 debugging("Enrol plugin data can not be restored because it is not installed");
1217 $this->set_mapping('enrol', $oldid, 0);
1218 return;
1219
024c288d 1220 }
f2a9be5f
EL
1221 if (!enrol_is_enabled($data->enrol)) {
1222 // TODO: decide if we want to switch to manual enrol - we need UI for this
1223 debugging("Enrol plugin data can not be restored because it is not enabled");
1224 $this->set_mapping('enrol', $oldid, 0);
1225 return;
1226 }
1227
1228 // map standard fields - plugin has to process custom fields from own restore class
1229 $data->roleid = $this->get_mappingid('role', $data->roleid);
1230 //TODO: should we move the enrol start and end date here?
1231
1232 // always add instance, if the course does not support multiple instances it just returns NULL
1233 $enrol = enrol_get_plugin($data->enrol);
1234 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1235 if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
1236 // ok
1237 } else {
1238 if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
1239 // most probably plugin that supports only one instance
1240 $newitemid = key($instances);
024c288d 1241 } else {
f2a9be5f
EL
1242 debugging('Can not create new enrol instance or reuse existing');
1243 $newitemid = 0;
024c288d 1244 }
f2a9be5f 1245 }
024c288d 1246
f2a9be5f
EL
1247 if ($restoretype === ENROL_RESTORE_NOUSERS) {
1248 // plugin requests to prevent restore of any users
024c288d
EL
1249 $newitemid = 0;
1250 }
f2a9be5f 1251
024c288d
EL
1252 $this->set_mapping('enrol', $oldid, $newitemid);
1253 }
1254
f2a9be5f
EL
1255 /**
1256 * Create user enrolments
1257 *
1258 * This has to be called after creation of enrolment instances
1259 * and before adding of role assignments.
1260 *
1261 * @param mixed $data
1262 * @return void
1263 */
024c288d
EL
1264 public function process_enrolment($data) {
1265 global $DB;
1266
1267 $data = (object)$data;
1268
1269 // Process only if parent instance have been mapped
1270 if ($enrolid = $this->get_new_parentid('enrol')) {
f2a9be5f
EL
1271 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1272 // And only if user is a mapped one
1273 if ($userid = $this->get_mappingid('user', $data->userid)) {
1274 $enrol = enrol_get_plugin($instance->enrol);
1275 //TODO: do we need specify modifierid?
1276 $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
1277 //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
024c288d
EL
1278 }
1279 }
1280 }
1281 }
1282}
21e51c86
EL
1283
1284
1285/**
1286 * This structure steps restores the filters and their configs
1287 */
1288class restore_filters_structure_step extends restore_structure_step {
1289
1290 protected function define_structure() {
1291
1292 $paths = array();
1293
1294 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1295 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1296
1297 return $paths;
1298 }
1299
1300 public function process_active($data) {
1301
1302 $data = (object)$data;
1303
1304 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1305 return;
1306 }
1307 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1308 }
1309
1310 public function process_config($data) {
1311
1312 $data = (object)$data;
1313
1314 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1315 return;
1316 }
1317 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1318 }
1319}
1320
1321
1322/**
1323 * This structure steps restores the comments
1324 * Note: Cannot use the comments API because defaults to USER->id.
1325 * That should change allowing to pass $userid
1326 */
1327class restore_comments_structure_step extends restore_structure_step {
1328
1329 protected function define_structure() {
1330
1331 $paths = array();
1332
1333 $paths[] = new restore_path_element('comment', '/comments/comment');
1334
1335 return $paths;
1336 }
1337
1338 public function process_comment($data) {
1339 global $DB;
1340
1341 $data = (object)$data;
1342
1343 // First of all, if the comment has some itemid, ask to the task what to map
1344 $mapping = false;
21e51c86 1345 if ($data->itemid) {
39aa0280
EL
1346 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1347 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
21e51c86
EL
1348 }
1349 // Only restore the comment if has no mapping OR we have found the matching mapping
39aa0280 1350 if (!$mapping || $data->itemid) {
b8e455a7
EL
1351 // Only if user mapping and context
1352 $data->userid = $this->get_mappingid('user', $data->userid);
1353 if ($data->userid && $this->task->get_contextid()) {
21e51c86 1354 $data->contextid = $this->task->get_contextid();
b8e455a7
EL
1355 // Only if there is another comment with same context/user/timecreated
1356 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1357 if (!$DB->record_exists('comments', $params)) {
1358 $DB->insert_record('comments', $data);
1359 }
1360 }
1361 }
1362 }
1363}
1364
bd39b6f2
SH
1365class restore_course_completion_structure_step extends restore_structure_step {
1366
1367 /**
1368 * Conditionally decide if this step should be executed.
1369 *
1370 * This function checks parameters that are not immediate settings to ensure
1371 * that the enviroment is suitable for the restore of course completion info.
1372 *
1373 * This function checks the following four parameters:
1374 *
1375 * 1. Course completion is enabled on the site
1376 * 2. The backup includes course completion information
1377 * 3. All modules are restorable
1378 * 4. All modules are marked for restore.
1379 *
1380 * @return bool True is safe to execute, false otherwise
1381 */
1382 protected function execute_condition() {
1383 global $CFG;
1384
1385 // First check course completion is enabled on this site
1386 if (empty($CFG->enablecompletion)) {
1387 // Disabled, don't restore course completion
1388 return false;
1389 }
1390
1391 // Check it is included in the backup
1392 $fullpath = $this->task->get_taskbasepath();
1393 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1394 if (!file_exists($fullpath)) {
1395 // Not found, can't restore course completion
1396 return false;
1397 }
1398
1399 // Check we are able to restore all backed up modules
1400 if ($this->task->is_missing_modules()) {
1401 return false;
1402 }
1403
1404 // Finally check all modules within the backup are being restored.
1405 if ($this->task->is_excluding_activities()) {
1406 return false;
1407 }
1408
1409 return true;
1410 }
1411
1412 /**
1413 * Define the course completion structure
1414 *
1415 * @return array Array of restore_path_element
1416 */
1417 protected function define_structure() {
1418
1419 // To know if we are including user completion info
1420 $userinfo = $this->get_setting_value('userscompletion');
1421
1422 $paths = array();
1423 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1424 $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1425 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1426
1427 if ($userinfo) {
1428 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1429 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1430 }
1431
1432 return $paths;
1433
1434 }
1435
1436 /**
1437 * Process course completion criteria
1438 *
1439 * @global moodle_database $DB
1440 * @param stdClass $data
1441 */
1442 public function process_course_completion_criteria($data) {
1443 global $DB;
1444
1445 $data = (object)$data;
1446 $data->course = $this->get_courseid();
1447
1448 // Apply the date offset to the time end field
1449 $data->timeend = $this->apply_date_offset($data->timeend);
1450
1451 // Map the role from the criteria
1452 if (!empty($data->role)) {
1453 $data->role = $this->get_mappingid('role', $data->role);
1454 }
1455
aa548318
SH
1456 $skipcriteria = false;
1457
bd39b6f2
SH
1458 // If the completion criteria is for a module we need to map the module instance
1459 // to the new module id.
1460 if (!empty($data->moduleinstance) && !empty($data->module)) {
1461 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
aa548318
SH
1462 if (empty($data->moduleinstance)) {
1463 $skipcriteria = true;
1464 }
bd39b6f2
SH
1465 } else {
1466 $data->module = null;
1467 $data->moduleinstance = null;
1468 }
1469
1470 // We backup the course shortname rather than the ID so that we can match back to the course
bd39b6f2
SH
1471 if (!empty($data->courseinstanceshortname)) {
1472 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1473 if (!$courseinstanceid) {
1474 $skipcriteria = true;
1475 }
1476 } else {
1477 $courseinstanceid = null;
1478 }
1479 $data->courseinstance = $courseinstanceid;
1480
1481 if (!$skipcriteria) {
1482 $params = array(
1483 'course' => $data->course,
1484 'criteriatype' => $data->criteriatype,
1485 'enrolperiod' => $data->enrolperiod,
1486 'courseinstance' => $data->courseinstance,
1487 'module' => $data->module,
1488 'moduleinstance' => $data->moduleinstance,
1489 'timeend' => $data->timeend,
1490 'gradepass' => $data->gradepass,
1491 'role' => $data->role
1492 );
1493 $newid = $DB->insert_record('course_completion_criteria', $params);
1494 $this->set_mapping('course_completion_criteria', $data->id, $newid);
1495 }
1496 }
1497
1498 /**
1499 * Processes course compltion criteria complete records
1500 *
1501 * @global moodle_database $DB
1502 * @param stdClass $data
1503 */
1504 public function process_course_completion_crit_compl($data) {
1505 global $DB;
1506
1507 $data = (object)$data;
1508
1509 // This may be empty if criteria could not be restored
1510 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
034ef761 1511
bd39b6f2
SH
1512 $data->course = $this->get_courseid();
1513 $data->userid = $this->get_mappingid('user', $data->userid);
1514
1515 if (!empty($data->criteriaid) && !empty($data->userid)) {
1516 $params = array(
1517 'userid' => $data->userid,
1518 'course' => $data->course,
1519 'criteriaid' => $data->criteriaid,
1520 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1521 );
1522 if (isset($data->gradefinal)) {
1523 $params['gradefinal'] = $data->gradefinal;
1524 }
1525 if (isset($data->unenroled)) {
1526 $params['unenroled'] = $data->unenroled;
1527 }
1528 if (isset($data->deleted)) {
1529 $params['deleted'] = $data->deleted;
1530 }
1531 $DB->insert_record('course_completion_crit_compl', $params);
1532 }
1533 }
1534
1535 /**
1536 * Process course completions
1537 *
1538 * @global moodle_database $DB
1539 * @param stdClass $data
1540 */
1541 public function process_course_completions($data) {
1542 global $DB;
1543
1544 $data = (object)$data;
1545
1546 $data->course = $this->get_courseid();
1547 $data->userid = $this->get_mappingid('user', $data->userid);
1548
1549 if (!empty($data->userid)) {
1550 $params = array(
1551 'userid' => $data->userid,
1552 'course' => $data->course,
1553 'deleted' => $data->deleted,
1554 'timenotified' => $this->apply_date_offset($data->timenotified),
1555 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1556 'timestarted' => $this->apply_date_offset($data->timestarted),
1557 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1558 'reaggregate' => $data->reaggregate
1559 );
1560 $DB->insert_record('course_completions', $params);
1561 }
1562 }
1563
1564 /**
1565 * Process course completion notification records.
1566 *
1567 * Note: As of Moodle 2.0 this table is not being used however it has been
1568 * left in in the hopes that one day the functionality there will be completed
1569 *
1570 * @global moodle_database $DB
1571 * @param stdClass $data
1572 */
1573 public function process_course_completion_notify($data) {
1574 global $DB;
1575
1576 $data = (object)$data;
1577
1578 $data->course = $this->get_courseid();
1579 if (!empty($data->role)) {
1580 $data->role = $this->get_mappingid('role', $data->role);
1581 }
1582
1583 $params = array(
1584 'course' => $data->course,
1585 'role' => $data->role,
1586 'message' => $data->message,
1587 'timesent' => $this->apply_date_offset($data->timesent),
1588 );
1589 $DB->insert_record('course_completion_notify', $params);
1590 }
1591
1592 /**
1593 * Process course completion aggregate methods
1594 *
1595 * @global moodle_database $DB
1596 * @param stdClass $data
1597 */
1598 public function process_course_completion_aggr_methd($data) {
1599 global $DB;
1600
1601 $data = (object)$data;
1602
1603 $data->course = $this->get_courseid();
1604
1605 $params = array(
1606 'course' => $data->course,
1607 'criteriatype' => $data->criteriatype,
1608 'method' => $data->method,
1609 'value' => $data->value,
1610 );
1611 $DB->insert_record('course_completion_aggr_methd', $params);
1612 }
1613
1614}
1615
9a1cfcbc
EL
1616/**
1617 * This structure step restores the grade items associated with one activity
1618 * All the grade items are made child of the "course" grade item but the original
1619 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
1620 * the complete gradebook (categories and calculations), that information is
1621 * available there
1622 */
1623class restore_activity_grades_structure_step extends restore_structure_step {
1624
1625 protected function define_structure() {
1626
1627 $paths = array();
1628 $userinfo = $this->get_setting_value('userinfo');
1629
1630 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
1631 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
1632 if ($userinfo) {
1633 $paths[] = new restore_path_element('grade_grade',
1634 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
1635 }
1636 return $paths;
1637 }
1638
1639 protected function process_grade_item($data) {
1640
1641 $data = (object)($data);
1642 $oldid = $data->id; // We'll need these later
1643 $oldparentid = $data->categoryid;
1644
1645 // make sure top course category exists, all grade items will be associated
1646 // to it. Later, if restoring the whole gradebook, categories will be introduced
1647 $coursecat = grade_category::fetch_course_category($this->get_courseid());
1648 $coursecatid = $coursecat->id; // Get the categoryid to be used
1649
1650 unset($data->id);
1651 $data->categoryid = $coursecatid;
1652 $data->courseid = $this->get_courseid();
1653 $data->iteminstance = $this->task->get_activityid();
1654 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
1655 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
1656 // so the best is to keep the ones already in the gradebook
1657 // Potential problem: duplicates if same items are restored more than once. :-(
1658 // This needs to be fixed in some way (outcomes & activities with multiple items)
1659 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
1660 // In any case, verify always for uniqueness
a789ac6f 1661 $data->idnumber = grade_verify_idnumber($data->idnumber, $this->get_courseid()) ? $data->idnumber : null;
9a1cfcbc
EL
1662 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1663 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
1664 $data->timecreated = $this->apply_date_offset($data->timecreated);
1665 $data->timemodified = $this->apply_date_offset($data->timemodified);
1666
1667 $gradeitem = new grade_item($data);
1668 $gradeitem->insert('restore');
4d787d8a
AD
1669
1670 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
1671 $gradeitem->sortorder = $data->sortorder;
1672 $gradeitem->update('restore');
1673
dc362c44
EL
1674 // Set mapping, saving the original category id into parentitemid
1675 // gradebook restore (final task) will need it to reorganise items
1676 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
9a1cfcbc
EL
1677 }
1678
1679 protected function process_grade_grade($data) {
1680 $data = (object)($data);
1681
1682 unset($data->id);
1683 $data->itemid = $this->get_new_parentid('grade_item');
1684 $data->userid = $this->get_mappingid('user', $data->userid);
1685 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
1686 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
1687 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
1688 $data->overridden = $this->apply_date_offset($data->overridden);
1689
1690 $grade = new grade_grade($data);
1691 $grade->insert('restore');
1692 // no need to save any grade_grade mapping
1693 }
1694
1695 /**
1696 * process activity grade_letters. Note that, while these are possible,
1697 * because grade_letters are contextid based, in proctice, only course
1698 * context letters can be defined. So we keep here this method knowing
1699 * it won't be executed ever. gradebook restore will restore course letters.
1700 */
1701 protected function process_grade_letter($data) {
1702 global $DB;
1703
1704 $data = (object)$data;
1705
1706 $data->contextid = $this->task->get_contextid();
1707 $newitemid = $DB->insert_record('grade_letters', $data);
1708 // no need to save any grade_letter mapping
1709 }
1710}
1711
b8e455a7
EL
1712
1713/**
1714 * This structure steps restores one instance + positions of one block
1715 * Note: Positions corresponding to one existing context are restored
1716 * here, but all the ones having unknown contexts are sent to backup_ids
1717 * for a later chance to be restored at the end (final task)
1718 */
1719class restore_block_instance_structure_step extends restore_structure_step {
1720
1721 protected function define_structure() {
1722
1723 $paths = array();
1724
1725 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
1726 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
1727
1728 return $paths;
1729 }
1730
1731 public function process_block($data) {
0f8941e2 1732 global $DB, $CFG;
b8e455a7
EL
1733
1734 $data = (object)$data; // Handy
1735 $oldcontextid = $data->contextid;
1736 $oldid = $data->id;
1737 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1738
1739 // Look for the parent contextid
1740 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1741 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1742 }
1743
767cb7f0 1744 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
b8e455a7
EL
1745 // If there is already one block of that type in the parent context
1746 // and the block is not multiple, stop processing
767cb7f0
EL
1747 // Use blockslib loader / method executor
1748 if (!block_method_result($data->blockname, 'instance_allow_multiple')) {
0f8941e2
EL
1749 if ($DB->record_exists_sql("SELECT bi.id
1750 FROM {block_instances} bi
1751 JOIN {block} b ON b.name = bi.blockname
1752 WHERE bi.parentcontextid = ?
1753 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
1754 return false;
1755 }
b8e455a7
EL
1756 }
1757
1758 // If there is already one block of that type in the parent context
1759 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
1760 // stop processing
1761 $params = array(
1762 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
1763 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
1764 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
1765 if ($birecs = $DB->get_records('block_instances', $params)) {
1766 foreach($birecs as $birec) {
1767 if ($birec->configdata == $data->configdata) {
1768 return false;
1769 }
1770 }
1771 }
1772
1773 // Set task old contextid, blockid and blockname once we know them
1774 $this->task->set_old_contextid($oldcontextid);
1775 $this->task->set_old_blockid($oldid);
1776 $this->task->set_blockname($data->blockname);
1777
1778 // Let's look for anything within configdata neededing processing
1779 // (nulls and uses of legacy file.php)
1780 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1781 $configdata = (array)unserialize(base64_decode($data->configdata));
1782 foreach ($configdata as $attribute => $value) {
1783 if (in_array($attribute, $attrstotransform)) {
1784 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
1785 }
1786 }
1787 $data->configdata = base64_encode(serialize((object)$configdata));
1788 }
1789
1790 // Create the block instance
1791 $newitemid = $DB->insert_record('block_instances', $data);
1792 // Save the mapping (with restorefiles support)
1793 $this->set_mapping('block_instance', $oldid, $newitemid, true);
1794 // Create the block context
1795 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
1796 // Save the block contexts mapping and sent it to task
1797 $this->set_mapping('context', $oldcontextid, $newcontextid);
1798 $this->task->set_contextid($newcontextid);
1799 $this->task->set_blockid($newitemid);
1800
1801 // Restore block fileareas if declared
1802 $component = 'block_' . $this->task->get_blockname();
1803 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
1804 $this->add_related_files($component, $filearea, null);
1805 }
1806
1807 // Process block positions, creating them or accumulating for final step
1808 foreach($positions as $position) {
1809 $position = (object)$position;
1810 $position->blockinstanceid = $newitemid; // The instance is always the restored one
1811 // If position is for one already mapped (known) contextid
1812 // process it now, creating the position
1813 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
1814 $position->contextid = $newpositionctxid;
1815 // Create the block position
1816 $DB->insert_record('block_positions', $position);
1817
1818 // The position belongs to an unknown context, send it to backup_ids
1819 // to process them as part of the final steps of restore. We send the
1820 // whole $position object there, hence use the low level method.
1821 } else {
1822 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
21e51c86
EL
1823 }
1824 }
1825 }
1826}
394edb7e
EL
1827
1828/**
1829 * Structure step to restore common course_module information
1830 *
1831 * This step will process the module.xml file for one activity, in order to restore
1832 * the corresponding information to the course_modules table, skipping various bits
1833 * of information based on CFG settings (groupings, completion...) in order to fullfill
1834 * all the reqs to be able to create the context to be used by all the rest of steps
1835 * in the activity restore task
1836 */
1837class restore_module_structure_step extends restore_structure_step {
1838
1839 protected function define_structure() {
1840 global $CFG;
1841
1842 $paths = array();
1843
1844 $paths[] = new restore_path_element('module', '/module');
1845 if ($CFG->enableavailability) {
1846 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
1847 }
1848
1849 return $paths;
1850 }
1851
1852 protected function process_module($data) {
1853 global $CFG, $DB;
1854
1855 $data = (object)$data;
1856 $oldid = $data->id;
1857
1858 $data->course = $this->task->get_courseid();
1859 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
aa39be20
EL
1860 // Map section (first try by course_section mapping match. Useful in course and section restores)
1861 $data->section = $this->get_mappingid('course_section', $data->sectionid);
1862 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
1863 $params = array(
1864 'course' => $this->get_courseid(),
1865 'section' => $data->sectionnumber);
1866 $data->section = $DB->get_field('course_sections', 'id', $params);
1867 }
1868 if (!$data->section) { // sectionnumber failed, try to get first section in course
1869 $params = array(
1870 'course' => $this->get_courseid());
1871 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
1872 }
1873 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
1874 $sectionrec = array(
1875 'course' => $this->get_courseid(),
1876 'section' => 0);
1877 $DB->insert_record('course_sections', $sectionrec); // section 0
1878 $sectionrec = array(
1879 'course' => $this->get_courseid(),
1880 'section' => 1);
1881 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
1882 }
394edb7e
EL
1883 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
1884 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
1885 $data->groupmembersonly = 0;
1886 }
1887 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
1888 $data->idnumber = '';
1889 }
5095f325 1890 if (empty($CFG->enablecompletion)) { // completion
394edb7e
EL
1891 $data->completion = 0;
1892 $data->completiongradeitemnumber = null;
1893 $data->completionview = 0;
1894 $data->completionexpected = 0;
1895 } else {
1896 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
1897 }
1898 if (empty($CFG->enableavailability)) {
1899 $data->availablefrom = 0;
1900 $data->availableuntil = 0;
1901 $data->showavailability = 0;
1902 } else {
1903 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
1904 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
1905 }
1906 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
1907
1908 // course_module record ready, insert it
1909 $newitemid = $DB->insert_record('course_modules', $data);
1910 // save mapping
1911 $this->set_mapping('course_module', $oldid, $newitemid);
1912 // set the new course_module id in the task
1913 $this->task->set_moduleid($newitemid);
1914 // we can now create the context safely
1915 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
1916 // set the new context id in the task
1917 $this->task->set_contextid($ctxid);
1918 // update sequence field in course_section
1919 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
1920 $sequence .= ',' . $newitemid;
1921 } else {
1922 $sequence = $newitemid;
1923 }
1924 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
1925 }
1926
1927
1928 protected function process_availability($data) {
394edb7e 1929 $data = (object)$data;
5095f325
EL
1930 // Simply going to store the whole availability record now, we'll process
1931 // all them later in the final task (once all actvivities have been restored)
1932 // Let's call the low level one to be able to store the whole object
1933 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
1934 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
1935 }
1936}
1937
1938/**
1939 * Structure step that will process the user activity completion
1940 * information if all these conditions are met:
1941 * - Target site has completion enabled ($CFG->enablecompletion)
1942 * - Activity includes completion info (file_exists)
1943 */
1944class restore_userscompletion_structure_step extends restore_structure_step {
1945
1946 /**
1947 * To conditionally decide if this step must be executed
1948 * Note the "settings" conditions are evaluated in the
1949 * corresponding task. Here we check for other conditions
1950 * not being restore settings (files, site settings...)
1951 */
1952 protected function execute_condition() {
1953 global $CFG;
1954
1955 // Completion disabled in this site, don't execute
1956 if (empty($CFG->enablecompletion)) {
1957 return false;
1958 }
1959
1960 // No user completion info found, don't execute
1961 $fullpath = $this->task->get_taskbasepath();
1962 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1963 if (!file_exists($fullpath)) {
1964 return false;
1965 }
1966
1967 // Arrived here, execute the step
1968 return true;
1969 }
1970
1971 protected function define_structure() {
1972
1973 $paths = array();
1974
1975 $paths[] = new restore_path_element('completion', '/completions/completion');
1976
1977 return $paths;
1978 }
1979
1980 protected function process_completion($data) {
1981 global $DB;
1982
1983 $data = (object)$data;
1984
1985 $data->coursemoduleid = $this->task->get_moduleid();
1986 $data->userid = $this->get_mappingid('user', $data->userid);
1987 $data->timemodified = $this->apply_date_offset($data->timemodified);
1988
1989 $DB->insert_record('course_modules_completion', $data);
394edb7e
EL
1990 }
1991}
1992
1993/**
1994 * Abstract structure step, parent of all the activity structure steps. Used to suuport
1995 * the main <activity ...> tag and process it. Also provides subplugin support for
1996 * activities.
1997 */
1998abstract class restore_activity_structure_step extends restore_structure_step {
1999
91d11057
EL
2000 protected function add_subplugin_structure($subplugintype, $element) {
2001
2002 global $CFG;
2003
2004 // Check the requested subplugintype is a valid one
2005 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
2006 if (!file_exists($subpluginsfile)) {
2007 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
2008 }
2009 include($subpluginsfile);
2010 if (!array_key_exists($subplugintype, $subplugins)) {
2011 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
2012 }
2013 // Get all the restore path elements, looking across all the subplugin dirs
2014 $subpluginsdirs = get_plugin_list($subplugintype);
2015 foreach ($subpluginsdirs as $name => $subpluginsdir) {
2016 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
2017 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
2018 if (file_exists($restorefile)) {
2019 require_once($restorefile);
2020 $restoresubplugin = new $classname($subplugintype, $name, $this);
2021 // Add subplugin paths to the step
2022 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
2023 }
2024 }
2025 }
2026
2027 /**
2028 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
2029 * have the parent task available for wrapping purposes (get course/context....)
2030 */
2031 public function get_task() {
2032 return $this->task;
394edb7e
EL
2033 }
2034
2035 /**
2036 * Adds support for the 'activity' path that is common to all the activities
2037 * and will be processed globally here
2038 */
2039 protected function prepare_activity_structure($paths) {
2040
2041 $paths[] = new restore_path_element('activity', '/activity');
2042
2043 return $paths;
2044 }
2045
2046 /**
2047 * Process the activity path, informing the task about various ids, needed later
2048 */
2049 protected function process_activity($data) {
2050 $data = (object)$data;
2051 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
2052 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
2053 $this->task->set_old_activityid($data->id); // Save old activityid in task
2054 }
2055
2056 /**
034ef761 2057 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
394edb7e
EL
2058 * and will adjust the new activity id (the instance) in various places
2059 */
2060 protected function apply_activity_instance($newitemid) {
2061 global $DB;
2062
2063 $this->task->set_activityid($newitemid); // Save activity id in task
2064 // Apply the id to course_sections->instanceid
2065 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
2066 // Do the mapping for modulename, preparing it for files by oldcontext
2067 $modulename = $this->task->get_modulename();
2068 $oldid = $this->task->get_old_activityid();
2069 $this->set_mapping($modulename, $oldid, $newitemid, true);
2070 }
2071}
41941110
EL
2072
2073/**
2074 * Structure step in charge of creating/mapping all the qcats and qs
2075 * by parsing the questions.xml file and checking it against the
2076 * results calculated by {@link restore_process_categories_and_questions}
2077 * and stored in backup_ids_temp
2078 */
2079class restore_create_categories_and_questions extends restore_structure_step {
2080
2081 protected function define_structure() {
2082
2083 $category = new restore_path_element('question_category', '/question_categories/question_category');
2084 $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
2085
2086 // Apply for 'qtype' plugins optional paths at question level
2087 $this->add_plugin_structure('qtype', $question);
2088
2089 return array($category, $question);
2090 }
2091
2092 protected function process_question_category($data) {
2093 global $DB;
2094
2095 $data = (object)$data;
2096 $oldid = $data->id;
2097
2098 // Check we have one mapping for this category
2099 if (!$mapping = $this->get_mapping('question_category', $oldid)) {
2100 return; // No mapping = this category doesn't need to be created/mapped
2101 }
2102
2103 // Check we have to create the category (newitemid = 0)
2104 if ($mapping->newitemid) {
2105 return; // newitemid != 0, this category is going to be mapped. Nothing to do
2106 }
2107
2108 // Arrived here, newitemid = 0, we need to create the category
2109 // we'll do it at parentitemid context, but for CONTEXT_MODULE
2110 // categories, that will be created at CONTEXT_COURSE and moved
2111 // to module context later when the activity is created
2112 if ($mapping->info->contextlevel == CONTEXT_MODULE) {
2113 $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
2114 }
2115 $data->contextid = $mapping->parentitemid;
2116
2117 // Let's create the question_category and save mapping
2118 $newitemid = $DB->insert_record('question_categories', $data);
2119 $this->set_mapping('question_category', $oldid, $newitemid);
2120 // Also annotate them as question_category_created, we need
2121 // that later when remapping parents
2122 $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
2123 }
2124
2125 protected function process_question($data) {
2126 global $DB;
2127
2128 $data = (object)$data;
2129 $oldid = $data->id;
2130
2131 // Check we have one mapping for this question
2132 if (!$questionmapping = $this->get_mapping('question', $oldid)) {
2133 return; // No mapping = this question doesn't need to be created/mapped
2134 }
2135
2136 // Get the mapped category (cannot use get_new_parentid() because not
2137 // all the categories have been created, so it is not always available
2138 // Instead we get the mapping for the question->parentitemid because
2139 // we have loaded qcatids there for all parsed questions
2140 $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
2141
2142 $data->timecreated = $this->apply_date_offset($data->timecreated);
2143 $data->timemodified = $this->apply_date_offset($data->timemodified);
2144
2145 $userid = $this->get_mappingid('user', $data->createdby);
2146 $data->createdby = $userid ? $userid : $this->task->get_userid();
2147
2148 $userid = $this->get_mappingid('user', $data->modifiedby);
2149 $data->modifiedby = $userid ? $userid : $this->task->get_userid();
2150
2151 // With newitemid = 0, let's create the question
2152 if (!$questionmapping->newitemid) {
2153 $newitemid = $DB->insert_record('question', $data);
2154 $this->set_mapping('question', $oldid, $newitemid);
2155 // Also annotate them as question_created, we need
2156 // that later when remapping parents (keeping the old categoryid as parentid)
2157 $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid);
2158 } else {
2159 // By performing this set_mapping() we make get_old/new_parentid() to work for all the
2160 // children elements of the 'question' one (so qtype plugins will know the question they belong to)
2161 $this->set_mapping('question', $oldid, $questionmapping->newitemid);
2162 }
2163
2164 // Note, we don't restore any question files yet
2165 // as far as the CONTEXT_MODULE categories still
2166 // haven't their contexts to be restored to
2167 // The {@link restore_create_question_files}, executed in the final step
2168 // step will be in charge of restoring all the question files
2169 }
2170
2171 protected function after_execute() {
2172 global $DB;
2173
2174 // First of all, recode all the created question_categories->parent fields
2175 $qcats = $DB->get_records('backup_ids_temp', array(
2176 'backupid' => $this->get_restoreid(),
2177 'itemname' => 'question_category_created'));
2178 foreach ($qcats as $qcat) {
2179 $newparent = 0;
2180 $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
2181 // Get new parent (mapped or created, so we look in quesiton_category mappings)
2182 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2183 'backupid' => $this->get_restoreid(),
2184 'itemname' => 'question_category',
2185 'itemid' => $dbcat->parent))) {
2186 // contextids must match always, as far as we always include complete qbanks, just check it
2187 $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
2188 if ($dbcat->contextid == $newparentctxid) {
2189 $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
2190 } else {
2191 $newparent = 0; // No ctx match for both cats, no parent relationship
2192 }
2193 }
2194 // Here with $newparent empty, problem with contexts or remapping, set it to top cat
2195 if (!$newparent) {
2196 $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id));
2197 }
2198 }
2199
2200 // Now, recode all the created question->parent fields
2201 $qs = $DB->get_records('backup_ids_temp', array(
2202 'backupid' => $this->get_restoreid(),
2203 'itemname' => 'question_created'));
2204 foreach ($qs as $q) {
2205 $newparent = 0;
2206 $dbq = $DB->get_record('question', array('id' => $q->newitemid));
2207 // Get new parent (mapped or created, so we look in question mappings)
2208 if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
2209 'backupid' => $this->get_restoreid(),
2210 'itemname' => 'question',
2211 'itemid' => $dbq->parent))) {
2212 $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
2213 }
2214 }
2215
2216 // Note, we don't restore any question files yet
2217 // as far as the CONTEXT_MODULE categories still
2218 // haven't their contexts to be restored to
2219 // The {@link restore_create_question_files}, executed in the final step
2220 // step will be in charge of restoring all the question files
2221 }
2222}
2223
2224/**
2225 * Execution step that will move all the CONTEXT_MODULE question categories
2226 * created at early stages of restore in course context (because modules weren't
2227 * created yet) to their target module (matching by old-new-contextid mapping)
2228 */
2229class restore_move_module_questions_categories extends restore_execution_step {
2230
2231 protected function define_execution() {
2232 global $DB;
2233
2234 $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
2235 foreach ($contexts as $contextid => $contextlevel) {
2236 // Only if context mapping exists (i.e. the module has been restored)
2237 if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
2238 // Update all the qcats having their parentitemid set to the original contextid
2239 $modulecats = $DB->get_records_sql("SELECT itemid, newitemid
2240 FROM {backup_ids_temp}
2241 WHERE backupid = ?
2242 AND itemname = 'question_category'
2243 AND parentitemid = ?", array($this->get_restoreid(), $contextid));
2244 foreach ($modulecats as $modulecat) {
2245 $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid));
2246 // And set new contextid also in question_category mapping (will be
2247 // used by {@link restore_create_question_files} later
2248 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid);
2249 }
2250 }
2251 }
2252 }
2253}
2254
2255/**
2256 * Execution step that will create all the question/answers/qtype-specific files for the restored
2257 * questions. It must be executed after {@link restore_move_module_questions_categories}
2258 * because only then each question is in its final category and only then the
2259 * context can be determined
2260 *
2261 * TODO: Improve this. Instead of looping over each question, it can be reduced to
2262 * be done by contexts (this will save a huge ammount of queries)
2263 */
2264class restore_create_question_files extends restore_execution_step {
2265
2266 protected function define_execution() {
2267 global $DB;
2268
2269 // Let's process only created questions
2270 $questionsrs = $DB->get_recordset_sql("SELECT bi.itemid, bi.newitemid, bi.parentitemid, q.qtype
2271 FROM {backup_ids_temp} bi
2272 JOIN {question} q ON q.id = bi.newitemid
2273 WHERE bi.backupid = ?
2274 AND bi.itemname = 'question_created'", array($this->get_restoreid()));
2275 foreach ($questionsrs as $question) {
2276 // Get question_category mapping, it contains the target context for the question
2277 if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $question->parentitemid)) {
2278 // Something went really wrong, cannot find the question_category for the question
2279 debugging('Error fetching target context for question', DEBUG_DEVELOPER);
2280 continue;
2281 }
2282 // Calculate source and target contexts
2283 $oldctxid = $qcatmapping->info->contextid;
2284 $newctxid = $qcatmapping->parentitemid;
2285
2286 // Add common question files (question and question_answer ones)
2287 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
2288 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2289 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
2290 $oldctxid, $this->task->get_userid(), 'question_created', $question->itemid, $newctxid, true);
2291 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
2292 $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true);
2293 // Add qtype dependent files
2294 $components = backup_qtype_plugin::get_components_and_fileareas($question->qtype);
2295 foreach ($components as $component => $fileareas) {
2296 foreach ($fileareas as $filearea => $mapping) {
2297 // Use itemid only if mapping is question_created
2298 $itemid = ($mapping == 'question_created') ? $question->itemid : null;
2299 restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
2300 $oldctxid, $this->task->get_userid(), $mapping, $itemid, $newctxid, true);
2301 }
2302 }
2303 }
2304 $questionsrs->close();
2305 }
2306}
2307
2308/**
2309 * Abstract structure step, to be used by all the activities using core questions stuff
2310 * (like the quiz module), to support qtype plugins, states and sessions
2311 */
2312abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
2313
2314 /**
2315 * Attach below $element (usually attempts) the needed restore_path_elements
2316 * to restore question_states
2317 */
2318 protected function add_question_attempts_states($element, &$paths) {
2319 // Check $element is restore_path_element
2320 if (! $element instanceof restore_path_element) {
2321 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2322 }
2323 // Check $paths is one array
2324 if (!is_array($paths)) {
2325 throw new restore_step_exception('paths_must_be_array', $paths);
2326 }
2327 $paths[] = new restore_path_element('question_state', $element->get_path() . '/states/state');
2328 }
2329
2330 /**
2331 * Attach below $element (usually attempts) the needed restore_path_elements
2332 * to restore question_sessions
2333 */
2334 protected function add_question_attempts_sessions($element, &$paths) {
2335 // Check $element is restore_path_element
2336 if (! $element instanceof restore_path_element) {
2337 throw new restore_step_exception('element_must_be_restore_path_element', $element);
2338 }
2339 // Check $paths is one array
2340 if (!is_array($paths)) {
2341 throw new restore_step_exception('paths_must_be_array', $paths);
2342 }
2343 $paths[] = new restore_path_element('question_session', $element->get_path() . '/sessions/session');
2344 }
2345
2346 /**
2347 * Process question_states
2348 */
2349 protected function process_question_state($data) {
2350 global $DB;
2351
2352 $data = (object)$data;
2353 $oldid = $data->id;
2354
2355 // Get complete question mapping, we'll need info
2356 $question = $this->get_mapping('question', $data->question);
2357
2358 // In the quiz_attempt mapping we are storing uniqueid
2359 // and not id, so this gets the correct question_attempt to point to
2360 $data->attempt = $this->get_new_parentid('quiz_attempt');
2361 $data->question = $question->newitemid;
2362 $data->answer = $this->restore_recode_answer($data, $question->info->qtype); // Delegate recoding of answer
2363 $data->timestamp= $this->apply_date_offset($data->timestamp);
2364
2365 // Everything ready, insert and create mapping (needed by question_sessions)
2366 $newitemid = $DB->insert_record('question_states', $data);
2367 $this->set_mapping('question_state', $oldid, $newitemid);
2368 }
2369
2370 /**
2371 * Process question_sessions
2372 */
2373 protected function process_question_session($data) {
2374 global $DB;
2375
2376 $data = (object)$data;
2377 $oldid = $data->id;
2378
2379 // In the quiz_attempt mapping we are storing uniqueid
2380 // and not id, so this gets the correct question_attempt to point to
2381 $data->attemptid = $this->get_new_parentid('quiz_attempt');
2382 $data->questionid = $this->get_mappingid('question', $data->questionid);
2383 $data->newest = $this->get_mappingid('question_state', $data->newest);
2384 $data->newgraded = $this->get_mappingid('question_state', $data->newgraded);
2385
2386 // Everything ready, insert (no mapping needed)
2387 $newitemid = $DB->insert_record('question_sessions', $data);
2388
2389 // Note: question_sessions haven't files associated. On purpose manualcomment is lacking
2390 // support for them, so we don't need to handle them here.
2391 }
2392
2393 /**
2394 * Given a list of question->ids, separated by commas, returns the
2395 * recoded list, with all the restore question mappings applied.
2396 * Note: Used by quiz->questions and quiz_attempts->layout
2397 * Note: 0 = page break (unconverted)
2398 */
2399 protected function questions_recode_layout($layout) {
2400 // Extracts question id from sequence
2401 if ($questionids = explode(',', $layout)) {
2402 foreach ($questionids as $id => $questionid) {
2403 if ($questionid) { // If it is zero then this is a pagebreak, don't translate
2404 $newquestionid = $this->get_mappingid('question', $questionid);
2405 $questionids[$id] = $newquestionid;
2406 }
2407 }
2408 }
2409 return implode(',', $questionids);
2410 }
2411
2412 /**
2413 * Given one question_states record, return the answer
2414 * recoded pointing to all the restored stuff
2415 */
2416 public function restore_recode_answer($state, $qtype) {
2417 // Build one static cache to store {@link restore_qtype_plugin}
2418 // while we are needing them, just to save zillions of instantiations
2419 // or using static stuff that will break our nice API
2420 static $qtypeplugins = array();
2421
2422 // If we haven't the corresponding restore_qtype_plugin for current qtype
2423 // instantiate it and add to cache
2424 if (!isset($qtypeplugins[$qtype])) {
2425 $classname = 'restore_qtype_' . $qtype . '_plugin';
2426 if (class_exists($classname)) {
2427 $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
2428 } else {
2429 $qtypeplugins[$qtype] = false;
2430 }
2431 }
2432 return !empty($qtypeplugins[$qtype]) ? $qtypeplugins[$qtype]->recode_state_answer($state) : $state->answer;
2433 }
2434}