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