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