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