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