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