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