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