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