backup MDL-22254 Added backup and restore of course completion information
[moodle.git] / backup / moodle2 / restore_stepslib.php
CommitLineData
482aac65
EL
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * @package moodlecore
20 * @subpackage backup-moodle2
21 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25/**
26 * Define all the restore steps that will be used by common tasks in restore
27 */
28
29/**
30 * delete old directories and conditionally create backup_temp_ids table
31 */
32class restore_create_and_clean_temp_stuff extends restore_execution_step {
33
34 protected function define_execution() {
b8bb45b0 35 $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
482aac65
EL
36 // If the table already exists, it's because restore_prechecks have been executed in the same
37 // request (without problems) and it already contains a bunch of preloaded information (users...)
38 // that we aren't going to execute again
39 if ($exists) { // Inform plan about preloaded information
40 $this->task->set_preloaded_information();
41 }
76cfb124
EL
42 // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
43 $itemid = $this->task->get_old_contextid();
44 $newitemid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
45 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
c0440b3f
EL
46 // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
47 $itemid = $this->task->get_old_system_contextid();
48 $newitemid = get_context_instance(CONTEXT_SYSTEM)->id;
49 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
d90e49f2
EL
50 // Create the old-course-id to new-course-id mapping, we need that available since the beginning
51 $itemid = $this->task->get_old_courseid();
52 $newitemid = $this->get_courseid();
53 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
54
482aac65
EL
55 }
56}
57
58/**
59 * delete the temp dir used by backup/restore (conditionally),
60 * delete old directories and drop temp ids table
61 */
62class restore_drop_and_clean_temp_stuff extends restore_execution_step {
63
64 protected function define_execution() {
65 global $CFG;
b8bb45b0 66 restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
b1eaf633 67 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
482aac65 68 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
b1eaf633 69 backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
482aac65
EL
70 }
71 }
72}
73
0067d939
AD
74/**
75 * Restore calculated grade items, grade categories etc
76 */
9a20df96 77class restore_gradebook_structure_step extends restore_structure_step {
0067d939 78
a0d27102
AD
79 /**
80 * To conditionally decide if this step must be executed
81 * Note the "settings" conditions are evaluated in the
82 * corresponding task. Here we check for other conditions
83 * not being restore settings (files, site settings...)
84 */
85 protected function execute_condition() {
9a20df96 86 global $CFG, $DB;
a0d27102
AD
87
88 // No gradebook info found, don't execute
89 $fullpath = $this->task->get_taskbasepath();
90 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
91 if (!file_exists($fullpath)) {
92 return false;
93 }
94
58328ce8
EL
95 // Some module present in backup file isn't available to restore
96 // in this site, don't execute
97 if ($this->task->is_missing_modules()) {
98 return false;
99 }
100
101 // Some activity has been excluded to be restored, don't execute
102 if ($this->task->is_excluding_activities()) {
103 return false;
104 }
105
9a20df96
AD
106 // There should only be one grade category (the 1 associated with the course itself)
107 // If other categories already exist we're restoring into an existing course.
108 // Restoring categories into a course with an existing category structure is unlikely to go well
109 $category = new stdclass();
110 $category->courseid = $this->get_courseid();
111 $catcount = $DB->count_records('grade_categories', (array)$category);
112 if ($catcount>1) {
113 return false;
114 }
115
a0d27102
AD
116 // Arrived here, execute the step
117 return true;
118 }
119
0067d939
AD
120 protected function define_structure() {
121 $paths = array();
122 $userinfo = $this->task->get_setting_value('users');
123
124 $paths[] = new restore_path_element('gradebook', '/gradebook');
125 $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
126 $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
127 if ($userinfo) {
128 $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
129 }
130 $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
b8040c83 131 $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
0067d939
AD
132
133 return $paths;
134 }
135
136 protected function process_gradebook($data) {
137 }
138
139 protected function process_grade_item($data) {
140 global $DB;
141
142 $data = (object)$data;
143
144 $oldid = $data->id;
145 $data->course = $this->get_courseid();
146
147 $data->courseid = $this->get_courseid();
148
149 //manual grade items store category id in categoryid
150 if ($data->itemtype=='manual') {
151 $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid);
152 } //course and category grade items store their category id in iteminstance
153 else if ($data->itemtype=='course' || $data->itemtype=='category') {
154 $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance);
155 }
156
157 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
158 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
159
160 $data->locktime = $this->apply_date_offset($data->locktime);
161 $data->timecreated = $this->apply_date_offset($data->timecreated);
162 $data->timemodified = $this->apply_date_offset($data->timemodified);
163
44a25cd2 164 $coursecategory = $newitemid = null;
0067d939
AD
165 //course grade item should already exist so updating instead of inserting
166 if($data->itemtype=='course') {
167
168 //get the ID of the already created grade item
169 $gi = new stdclass();
170 $gi->courseid = $this->get_courseid();
171
172 $gi->itemtype = $data->itemtype;
173 if ($data->itemtype=='course') {
174 //need to get the id of the grade_category that was automatically created for the course
175 $category = new stdclass();
176 $category->courseid = $this->get_courseid();
177 $category->parent = null;
9a20df96
AD
178 //course category fullname starts out as ? but may be edited
179 //$category->fullname = '?';
0067d939
AD
180
181 $coursecategory = $DB->get_record('grade_categories', (array)$category);
182 $gi->iteminstance = $coursecategory->id;
183 }
184
185 $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
44a25cd2
AD
186 if (!empty($existinggradeitem)) {
187 $data->id = $newitemid = $existinggradeitem->id;
188 $DB->update_record('grade_items', $data);
189 }
190 }
0067d939 191
44a25cd2
AD
192 if (empty($newitemid)) {
193 //in case we found the course category but still need to insert the course grade item
194 if ($data->itemtype=='course' && !empty($coursecategory)) {
195 $data->iteminstance = $coursecategory->id;
196 }
197
0067d939
AD
198 $newitemid = $DB->insert_record('grade_items', $data);
199 }
200 $this->set_mapping('grade_item', $oldid, $newitemid);
201 }
202
203 protected function process_grade_grade($data) {
204 global $DB;
205
206 $data = (object)$data;
207 $oldid = $data->id;
208
209 $data->itemid = $this->get_new_parentid('grade_item');
210
211 $data->userid = $this->get_mappingid('user', $data->userid);
212 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
213 $data->locktime = $this->apply_date_offset($data->locktime);
9a20df96
AD
214 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
215 $data->overridden = $this->apply_date_offset($data->overridden);
0067d939
AD
216 $data->timecreated = $this->apply_date_offset($data->timecreated);
217 $data->timemodified = $this->apply_date_offset($data->timemodified);
218
219 $newitemid = $DB->insert_record('grade_grades', $data);
0df2981f 220 //$this->set_mapping('grade_grade', $oldid, $newitemid);
0067d939
AD
221 }
222 protected function process_grade_category($data) {
223 global $DB;
224
225 $data = (object)$data;
226 $oldid = $data->id;
227
228 $data->course = $this->get_courseid();
229 $data->courseid = $data->course;
230
231 $data->timecreated = $this->apply_date_offset($data->timecreated);
232 $data->timemodified = $this->apply_date_offset($data->timemodified);
233
499dbce8
AD
234 $newitemid = null;
235 //no parent means a course level grade category. That may have been created when the course was created
0067d939 236 if(empty($data->parent)) {
499dbce8
AD
237 //parent was being saved as 0 when it should be null
238 $data->parent = null;
239
0067d939
AD
240 //get the already created course level grade category
241 $category = new stdclass();
499dbce8 242 $category->courseid = $this->get_courseid();
0067d939
AD
243
244 $coursecategory = $DB->get_record('grade_categories', (array)$category);
499dbce8
AD
245 if (!empty($coursecategory)) {
246 $data->id = $newitemid = $coursecategory->id;
247 $DB->update_record('grade_categories', $data);
248 }
249 }
0067d939 250
499dbce8
AD
251 //need to insert a course category
252 if (empty($newitemid)) {
0067d939
AD
253 $newitemid = $DB->insert_record('grade_categories', $data);
254 }
255 $this->set_mapping('grade_category', $oldid, $newitemid);
0067d939
AD
256 }
257 protected function process_grade_letter($data) {
258 global $DB;
259
260 $data = (object)$data;
261 $oldid = $data->id;
262
e101180d 263 $data->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
0067d939
AD
264
265 $newitemid = $DB->insert_record('grade_letters', $data);
266 $this->set_mapping('grade_letter', $oldid, $newitemid);
267 }
b8040c83
AD
268 protected function process_grade_setting($data) {
269 global $DB;
270
271 $data = (object)$data;
272 $oldid = $data->id;
273
274 $data->courseid = $this->get_courseid();
275
276 $newitemid = $DB->insert_record('grade_settings', $data);
0df2981f 277 //$this->set_mapping('grade_setting', $oldid, $newitemid);
b8040c83 278 }
0f94550c
AD
279
280 //put all activity grade items in the correct grade category and mark all for recalculation
c4d2c745
AD
281 protected function after_execute() {
282 global $DB;
283
c4d2c745
AD
284 $conditions = array(
285 'backupid' => $this->get_restoreid(),
286 'itemname' => 'grade_item'//,
287 //'itemid' => $itemid
288 );
289 $rs = $DB->get_recordset('backup_ids_temp', $conditions);
290
291 if (!empty($rs)) {
292 foreach($rs as $grade_item_backup) {
0f94550c
AD
293 $updateobj = new stdclass();
294 $updateobj->id = $grade_item_backup->newitemid;
074a765f 295
0f94550c
AD
296 //if this is an activity grade item that needs to be put back in its correct category
297 if (!empty($grade_item_backup->parentitemid)) {
298 $updateobj->categoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid);
074a765f 299 } else {
0f94550c
AD
300 //mark course and category items as needing to be recalculated
301 $updateobj->needsupdate=1;
c4d2c745 302 }
0f94550c 303 $DB->update_record('grade_items', $updateobj);
9a20df96
AD
304 }
305 }
306 $rs->close();
0f94550c 307
9a20df96
AD
308 //need to correct the grade category path and parent
309 $conditions = array(
310 'courseid' => $this->get_courseid()
311 );
312 $grade_category = new stdclass();
313
314 $rs = $DB->get_recordset('grade_categories', $conditions);
315 if (!empty($rs)) {
316 //get all the parents correct first as grade_category::build_path() loads category parents from the DB
317 foreach($rs as $gc) {
318 if (!empty($gc->parent)) {
319 $grade_category->id = $gc->id;
320 $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
321 $DB->update_record('grade_categories', $grade_category);
322 }
323 }
324 }
325 if (isset($grade_category->parent)) {
326 unset($grade_category->parent);
327 }
328 $rs->close();
329
330 $rs = $DB->get_recordset('grade_categories', $conditions);
331 if (!empty($rs)) {
332 //now we can rebuild all the paths
333 foreach($rs as $gc) {
334 $grade_category->id = $gc->id;
335 $grade_category->path = grade_category::build_path($gc);
336 $DB->update_record('grade_categories', $grade_category);
c4d2c745
AD
337 }
338 }
339 $rs->close();
340 }
0067d939
AD
341}
342
394edb7e
EL
343/**
344 * decode all the interlinks present in restored content
345 * relying 100% in the restore_decode_processor that handles
346 * both the contents to modify and the rules to be applied
347 */
348class restore_decode_interlinks extends restore_execution_step {
349
350 protected function define_execution() {
351 // Just that
352 $this->task->get_decoder()->execute();
353 }
354}
355
356/**
357 * rebuid the course cache
358 */
359class restore_rebuild_course_cache extends restore_execution_step {
360
361 protected function define_execution() {
362 // Just that
363 rebuild_course_cache($this->get_courseid());
364 }
365}
366
b8e455a7
EL
367
368/**
369 * Review all the (pending) block positions in backup_ids, matching by
370 * contextid, creating positions as needed. This is executed by the
371 * final task, once all the contexts have been created
372 */
373class restore_review_pending_block_positions extends restore_execution_step {
374
375 protected function define_execution() {
376 global $DB;
377
378 // Get all the block_position objects pending to match
379 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
380 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
381 // Process block positions, creating them or accumulating for final step
382 foreach($rs as $posrec) {
383 // Get the complete position object (stored as info)
384 $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
385 // If position is for one already mapped (known) contextid
386 // process it now, creating the position, else nothing to
387 // do, position finally discarded
388 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
389 $position->contextid = $newctx->newitemid;
390 // Create the block position
391 $DB->insert_record('block_positions', $position);
392 }
393 }
394 $rs->close();
395 }
396}
397
5095f325
EL
398/**
399 * Process all the saved module availability records in backup_ids, matching
400 * course modules and grade item id once all them have been already restored.
401 * only if all matchings are satisfied the availability condition will be created.
402 * At the same time, it is required for the site to have that functionality enabled.
403 */
404class restore_process_course_modules_availability extends restore_execution_step {
405
406 protected function define_execution() {
407 global $CFG, $DB;
408
409 // Site hasn't availability enabled
410 if (empty($CFG->enableavailability)) {
411 return;
412 }
413
414 // Get all the module_availability objects to process
415 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'module_availability');
416 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
417 // Process availabilities, creating them if everything matches ok
418 foreach($rs as $availrec) {
419 $allmatchesok = true;
420 // Get the complete availabilityobject
421 $availability = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_availability', $availrec->itemid)->info;
422 // Map the sourcecmid if needed and possible
423 if (!empty($availability->sourcecmid)) {
424 $newcm = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'course_module', $availability->sourcecmid);
425 if ($newcm) {
426 $availability->sourcecmid = $newcm->newitemid;
427 } else {
428 $allmatchesok = false; // Failed matching, we won't create this availability rule
429 }
430 }
431 // Map the gradeitemid if needed and possible
432 if (!empty($availability->gradeitemid)) {
433 $newgi = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'grade_item', $availability->gradeitemid);
434 if ($newgi) {
435 $availability->gradeitemid = $newgi->newitemid;
436 } else {
437 $allmatchesok = false; // Failed matching, we won't create this availability rule
438 }
439 }
440 if ($allmatchesok) { // Everything ok, create the availability rule
441 $DB->insert_record('course_modules_availability', $availability);
442 }
443 }
444 $rs->close();
445 }
446}
447
448
482aac65
EL
449/*
450 * Execution step that, *conditionally* (if there isn't preloaded information)
451 * will load the inforef files for all the included course/section/activity tasks
452 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
453 */
454class restore_load_included_inforef_records extends restore_execution_step {
455
456 protected function define_execution() {
457
458 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
459 return;
460 }
461
462 // Get all the included inforef files
463 $files = restore_dbops::get_needed_inforef_files($this->get_restoreid());
464 foreach ($files as $file) {
465 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $file); // Load each inforef file to temp_ids
466 }
467 }
468}
469
76cfb124 470/*
b8bb45b0 471 * Execution step that will load all the needed files into backup_files_temp
76cfb124
EL
472 * - info: contains the whole original object (times, names...)
473 * (all them being original ids as loaded from xml)
474 */
475class restore_load_included_files extends restore_structure_step {
476
477 protected function define_structure() {
478
479 $file = new restore_path_element('file', '/files/file');
480
481 return array($file);
482 }
483
484 // Processing functions go here
485 public function process_file($data) {
486
487 $data = (object)$data; // handy
488
76cfb124
EL
489 // load it if needed:
490 // - it it is one of the annotated inforef files (course/section/activity/block)
71a50b13 491 // - it is one "user", "group", "grouping" or "grade" component file (that aren't sent to inforef ever)
b8bb45b0 492 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
71a50b13
EL
493 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
494 $data->component == 'grouping' || $data->component == 'grade');
76cfb124 495 if ($isfileref || $iscomponent) {
b8bb45b0 496 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
76cfb124
EL
497 }
498 }
499}
500
71a50b13
EL
501/**
502 * Execution step that, *conditionally* (if there isn't preloaded information),
503 * will load all the needed roles to backup_temp_ids. They will be stored with
504 * "role" itemname. Also it will perform one automatic mapping to roles existing
505 * in the target site, based in permissions of the user performing the restore,
506 * archetypes and other bits. At the end, each original role will have its associated
507 * target role or 0 if it's going to be skipped. Note we wrap everything over one
508 * restore_dbops method, as far as the same stuff is going to be also executed
509 * by restore prechecks
510 */
511class restore_load_and_map_roles extends restore_execution_step {
512
513 protected function define_execution() {
8d4e41f4 514 if ($this->task->get_preloaded_information()) { // if info is already preloaded
71a50b13
EL
515 return;
516 }
517
518 $file = $this->get_basepath() . '/roles.xml';
519 // Load needed toles to temp_ids
520 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
8d4e41f4 521
71a50b13 522 // Process roles, mapping/skipping. Any error throws exception
8d4e41f4
EL
523 // Note we pass controller's info because it can contain role mapping information
524 // about manual mappings performed by UI
525 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
526 }
527}
528
482aac65
EL
529/**
530 * Execution step that, *conditionally* (if there isn't preloaded information
531 * and users have been selected in settings, will load all the needed users
532 * to backup_temp_ids. They will be stored with "user" itemname and with
76cfb124 533 * their original contextid as paremitemid
482aac65
EL
534 */
535class restore_load_included_users extends restore_execution_step {
536
537 protected function define_execution() {
538
539 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
540 return;
541 }
25d3cf44 542 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
482aac65
EL
543 return;
544 }
545 $file = $this->get_basepath() . '/users.xml';
546 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
547 }
548}
549
550/**
551 * Execution step that, *conditionally* (if there isn't preloaded information
552 * and users have been selected in settings, will process all the needed users
553 * in order to decide and perform any action with them (create / map / error)
554 * Note: Any error will cause exception, as far as this is the same processing
555 * than the one into restore prechecks (that should have stopped process earlier)
556 */
76cfb124 557class restore_process_included_users extends restore_execution_step {
482aac65
EL
558
559 protected function define_execution() {
560
561 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
562 return;
563 }
25d3cf44 564 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
482aac65
EL
565 return;
566 }
567 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
568 }
569}
570
76cfb124
EL
571/**
572 * Execution step that will create all the needed users as calculated
573 * by @restore_process_included_users (those having newiteind = 0)
574 */
575class restore_create_included_users extends restore_execution_step {
576
577 protected function define_execution() {
578
b212f87e 579 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->get_setting_value('user_files'), $this->task->get_userid());
76cfb124
EL
580 }
581}
582
583/**
584 * Structure step that will create all the needed groups and groupings
585 * by loading them from the groups.xml file performing the required matches.
586 * Note group members only will be added if restoring user info
587 */
588class restore_groups_structure_step extends restore_structure_step {
589
c0440b3f
EL
590 protected function define_structure() {
591
592 $paths = array(); // Add paths here
593
594 $paths[] = new restore_path_element('group', '/groups/group');
595 if ($this->get_setting_value('users')) {
596 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
597 }
598 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
599 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
600
601 return $paths;
602 }
603
604 // Processing functions go here
605 public function process_group($data) {
606 global $DB;
607
608 $data = (object)$data; // handy
609 $data->courseid = $this->get_courseid();
610
611 $oldid = $data->id; // need this saved for later
76cfb124 612
c0440b3f
EL
613 $restorefiles = false; // Only if we end creating the group
614
615 // Search if the group already exists (by name & description) in the target course
616 $description_clause = '';
617 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
618 if (!empty($data->description)) {
619 $description_clause = ' AND ' .
620 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
621 $params['desc'] = $data->description;
622 }
623 if (!$groupdb = $DB->get_record_sql("SELECT *
624 FROM {groups}
625 WHERE courseid = :courseid
626 AND name = :grname $description_clause", $params)) {
627 // group doesn't exist, create
628 $newitemid = $DB->insert_record('groups', $data);
629 $restorefiles = true; // We'll restore the files
630 } else {
631 // group exists, use it
632 $newitemid = $groupdb->id;
633 }
634 // Save the id mapping
635 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
636 }
637
638 public function process_member($data) {
639 global $DB;
640
641 $data = (object)$data; // handy
642
643 // get parent group->id
644 $data->groupid = $this->get_new_parentid('group');
645
646 // map user newitemid and insert if not member already
647 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
648 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
649 $DB->insert_record('groups_members', $data);
650 }
651 }
652 }
653
654 public function process_grouping($data) {
71a50b13
EL
655 global $DB;
656
657 $data = (object)$data; // handy
658 $data->courseid = $this->get_courseid();
659
660 $oldid = $data->id; // need this saved for later
661 $restorefiles = false; // Only if we end creating the grouping
662
663 // Search if the grouping already exists (by name & description) in the target course
664 $description_clause = '';
665 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
666 if (!empty($data->description)) {
667 $description_clause = ' AND ' .
668 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
669 $params['desc'] = $data->description;
670 }
671 if (!$groupingdb = $DB->get_record_sql("SELECT *
672 FROM {groupings}
673 WHERE courseid = :courseid
674 AND name = :grname $description_clause", $params)) {
675 // grouping doesn't exist, create
676 $newitemid = $DB->insert_record('groupings', $data);
677 $restorefiles = true; // We'll restore the files
678 } else {
679 // grouping exists, use it
680 $newitemid = $groupingdb->id;
681 }
682 // Save the id mapping
683 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
c0440b3f
EL
684 }
685
686 public function process_grouping_group($data) {
71a50b13
EL
687 global $DB;
688
689 $data = (object)$data;
690
691 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
692 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
693 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
c0440b3f
EL
694 }
695
696 protected function after_execute() {
697 // Add group related files, matching with "group" mappings
698 $this->add_related_files('group', 'icon', 'group');
699 $this->add_related_files('group', 'description', 'group');
71a50b13
EL
700 // Add grouping related files, matching with "grouping" mappings
701 $this->add_related_files('grouping', 'description', 'grouping');
c0440b3f
EL
702 }
703
704}
705
706/**
707 * Structure step that will create all the needed scales
708 * by loading them from the scales.xml
c0440b3f
EL
709 */
710class restore_scales_structure_step extends restore_structure_step {
711
712 protected function define_structure() {
713
714 $paths = array(); // Add paths here
715 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
716 return $paths;
717 }
718
719 protected function process_scale($data) {
720 global $DB;
721
722 $data = (object)$data;
723
724 $restorefiles = false; // Only if we end creating the group
725
726 $oldid = $data->id; // need this saved for later
727
728 // Look for scale (by 'scale' both in standard (course=0) and current course
729 // with priority to standard scales (ORDER clause)
730 // scale is not course unique, use get_record_sql to suppress warning
731 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
732 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
733 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
734 if (!$scadb = $DB->get_record_sql("SELECT *
735 FROM {scale}
736 WHERE courseid IN (0, :courseid)
737 AND $compare_scale_clause
738 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
739 // Remap the user if possible, defaut to user performing the restore if not
740 $userid = $this->get_mappingid('user', $data->userid);
ba8bead5 741 $data->userid = $userid ? $userid : $this->task->get_userid();
c0440b3f
EL
742 // Remap the course if course scale
743 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
744 // If global scale (course=0), check the user has perms to create it
745 // falling to course scale if not
746 $systemctx = get_context_instance(CONTEXT_SYSTEM);
394edb7e 747 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
c0440b3f
EL
748 $data->courseid = $this->get_courseid();
749 }
750 // scale doesn't exist, create
751 $newitemid = $DB->insert_record('scale', $data);
752 $restorefiles = true; // We'll restore the files
753 } else {
754 // scale exists, use it
755 $newitemid = $scadb->id;
756 }
757 // Save the id mapping (with files support at system context)
758 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
759 }
760
761 protected function after_execute() {
762 // Add scales related files, matching with "scale" mappings
763 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
764 }
76cfb124
EL
765}
766
c0440b3f 767
c8730ff0
EL
768/**
769 * Structure step that will create all the needed outocomes
770 * by loading them from the outcomes.xml
771 */
772class restore_outcomes_structure_step extends restore_structure_step {
773
774 protected function define_structure() {
775
776 $paths = array(); // Add paths here
777 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
778 return $paths;
779 }
780
781 protected function process_outcome($data) {
782 global $DB;
783
784 $data = (object)$data;
785
786 $restorefiles = false; // Only if we end creating the group
787
788 $oldid = $data->id; // need this saved for later
789
790 // Look for outcome (by shortname both in standard (courseid=null) and current course
791 // with priority to standard outcomes (ORDER clause)
792 // outcome is not course unique, use get_record_sql to suppress warning
793 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
794 if (!$outdb = $DB->get_record_sql('SELECT *
795 FROM {grade_outcomes}
796 WHERE shortname = :shortname
797 AND (courseid = :courseid OR courseid IS NULL)
798 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
799 // Remap the user
800 $userid = $this->get_mappingid('user', $data->usermodified);
ba8bead5 801 $data->usermodified = $userid ? $userid : $this->task->get_userid();
8d4e41f4
EL
802 // Remap the scale
803 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
c8730ff0
EL
804 // Remap the course if course outcome
805 $data->courseid = $data->courseid ? $this->get_courseid() : null;
806 // If global outcome (course=null), check the user has perms to create it
807 // falling to course outcome if not
808 $systemctx = get_context_instance(CONTEXT_SYSTEM);
394edb7e 809 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
c8730ff0
EL
810 $data->courseid = $this->get_courseid();
811 }
812 // outcome doesn't exist, create
813 $newitemid = $DB->insert_record('grade_outcomes', $data);
814 $restorefiles = true; // We'll restore the files
815 } else {
816 // scale exists, use it
817 $newitemid = $outdb->id;
818 }
819 // Set the corresponding grade_outcomes_courses record
820 $outcourserec = new stdclass();
821 $outcourserec->courseid = $this->get_courseid();
822 $outcourserec->outcomeid = $newitemid;
823 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
824 $DB->insert_record('grade_outcomes_courses', $outcourserec);
825 }
826 // Save the id mapping (with files support at system context)
827 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
828 }
829
830 protected function after_execute() {
831 // Add outcomes related files, matching with "outcome" mappings
832 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
833 }
834}
835
3223cc95
EL
836/**
837 * Structure step that will read the section.xml creating/updating sections
838 * as needed, rebuilding course cache and other friends
839 */
840class restore_section_structure_step extends restore_structure_step {
c8730ff0 841
3223cc95
EL
842 protected function define_structure() {
843 return array(new restore_path_element('section', '/section'));
844 }
845
846 public function process_section($data) {
847 global $DB;
848 $data = (object)$data;
849 $oldid = $data->id; // We'll need this later
850
851 $restorefiles = false;
852
853 // Look for the section
854 $section = new stdclass();
855 $section->course = $this->get_courseid();
856 $section->section = $data->number;
857 // Section doesn't exist, create it with all the info from backup
858 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
859 $section->name = $data->name;
860 $section->summary = $data->summary;
861 $section->summaryformat = $data->summaryformat;
862 $section->sequence = '';
863 $section->visible = $data->visible;
864 $newitemid = $DB->insert_record('course_sections', $section);
865 $restorefiles = true;
866
867 // Section exists, update non-empty information
868 } else {
869 $section->id = $secrec->id;
870 if (empty($secrec->name)) {
871 $section->name = $data->name;
872 }
873 if (empty($secrec->summary)) {
874 $section->summary = $data->summary;
875 $section->summaryformat = $data->summaryformat;
876 $restorefiles = true;
877 }
878 $DB->update_record('course_sections', $section);
879 $newitemid = $secrec->id;
880 }
881
882 // Annotate the section mapping, with restorefiles option if needed
883 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
884
885 // If needed, adjust course->numsections
886 if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
887 if ($numsections < $section->section) {
888 $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
889 }
890 }
891 }
892
893 protected function after_execute() {
894 // Add section related files, with 'course_section' itemid to match
895 $this->add_related_files('course', 'section', 'course_section');
896 }
897}
898
899
900/**
482aac65 901 * Structure step that will read the course.xml file, loading it and performing
395dae30
EL
902 * various actions depending of the site/restore settings. Note that target
903 * course always exist before arriving here so this step will be updating
904 * the course record (never inserting)
482aac65
EL
905 */
906class restore_course_structure_step extends restore_structure_step {
907
908 protected function define_structure() {
909
910 $course = new restore_path_element('course', '/course', true); // Grouped
911 $category = new restore_path_element('category', '/course/category');
912 $tag = new restore_path_element('tag', '/course/tags/tag');
913 $allowed = new restore_path_element('allowed', '/course/allowed_modules/module');
914
915 return array($course, $category, $tag, $allowed);
916 }
917
7f32340b
SH
918 /**
919 * Processing functions go here
920 *
921 * @global moodledatabase $DB
922 * @param stdClass $data
923 */
482aac65 924 public function process_course($data) {
395dae30
EL
925 global $CFG, $DB;
926
927 $data = (object)$data;
928 $coursetags = isset($data->tags['tag']) ? $data->tags['tag'] : array();
929 $coursemodules = isset($data->allowed_modules['module']) ? $data->allowed_modules['module'] : array();
930 $oldid = $data->id; // We'll need this later
785d6603
SH
931
932 $fullname = $this->get_setting_value('course_fullname');
933 $shortname = $this->get_setting_value('course_shortname');
b1eaf633 934 $startdate = $this->get_setting_value('course_startdate');
395dae30
EL
935
936 // Calculate final course names, to avoid dupes
937 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
938
939 // Need to change some fields before updating the course record
940 $data->id = $this->get_courseid();
941 $data->fullname = $fullname;
942 $data->shortname= $shortname;
943 $data->idnumber = '';
7f32340b
SH
944
945 // Category is set by UI when choosing the destination
946 unset($data->category);
947
395dae30
EL
948 $data->startdate= $this->apply_date_offset($data->startdate);
949 if ($data->defaultgroupingid) {
950 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
951 }
5095f325 952 if (empty($CFG->enablecompletion)) {
395dae30
EL
953 $data->enablecompletion = 0;
954 $data->completionstartonenrol = 0;
955 $data->completionnotify = 0;
956 }
957 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
958 if (!array_key_exists($data->lang, $languages)) {
959 $data->lang = '';
960 }
961 $themes = get_list_of_themes(); // Get themes for quick search later
962 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
963 $data->theme = '';
964 }
965
966 // Course record ready, update it
967 $DB->update_record('course', $data);
968
969 // Course tags
970 if (!empty($CFG->usetags) && isset($coursetags)) { // if enabled in server and present in backup
971 $tags = array();
972 foreach ($coursetags as $coursetag) {
973 $coursetag = (object)$coursetag;
974 $tags[] = $coursetag->rawname;
975 }
976 tag_set('course', $this->get_courseid(), $tags);
977 }
978 // Course allowed modules
979 if (!empty($data->restrictmodules) && !empty($coursemodules)) {
980 $available = get_plugin_list('mod');
981 foreach ($coursemodules as $coursemodule) {
982 $mname = $coursemodule['modulename'];
983 if (array_key_exists($mname, $available)) {
984 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
985 $rec = new stdclass();
986 $rec->course = $this->get_courseid();
987 $rec->module = $module->id;
988 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
989 $DB->insert_record('course_allowed_modules', $rec);
990 }
991 }
992 }
993 }
994 }
995 // Role name aliases
996 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
482aac65
EL
997 }
998
395dae30
EL
999 protected function after_execute() {
1000 // Add course related files, without itemid to match
1001 $this->add_related_files('course', 'summary', null);
1002 $this->add_related_files('course', 'legacy', null);
1003 }
482aac65 1004}
024c288d
EL
1005
1006
1007/*
1008 * Structure step that will read the roles.xml file (at course/activity/block levels)
1009 * containig all the role_assignments and overrides for that context. If corresponding to
1010 * one mapped role, they will be applied to target context. Will observe the role_assignments
1011 * setting to decide if ras are restored.
1012 * Note: only ras with component == null are restored as far as the any ra with component
1013 * is handled by one enrolment plugin, hence it will createt the ras later
1014 */
1015class restore_ras_and_caps_structure_step extends restore_structure_step {
1016
1017 protected function define_structure() {
1018
1019 $paths = array();
1020
1021 // Observe the role_assignments setting
1022 if ($this->get_setting_value('role_assignments')) {
1023 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
1024 }
1025 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
1026
1027 return $paths;
1028 }
1029
1030 public function process_assignment($data) {
28b6ff82
EL
1031 global $DB;
1032
024c288d
EL
1033 $data = (object)$data;
1034
1035 // Check roleid, userid are one of the mapped ones
1036 $newroleid = $this->get_mappingid('role', $data->roleid);
1037 $newuserid = $this->get_mappingid('user', $data->userid);
b8e455a7
EL
1038 // If newroleid and newuserid and component is empty and context valid assign via API (handles dupes and friends)
1039 if ($newroleid && $newuserid && empty($data->component) && $this->task->get_contextid()) {
28b6ff82
EL
1040 // Only assign roles to not deleted users
1041 if ($DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
1042 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1043 role_assign($newroleid, $newuserid, $this->task->get_contextid());
1044 }
024c288d
EL
1045 }
1046 }
1047
1048 public function process_override($data) {
1049 $data = (object)$data;
1050
1051 // Check roleid is one of the mapped ones
1052 $newroleid = $this->get_mappingid('role', $data->roleid);
b8e455a7
EL
1053 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1054 if ($newroleid && $this->task->get_contextid()) {
024c288d 1055 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
b8e455a7 1056 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
024c288d
EL
1057 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1058 }
1059 }
1060}
1061
1062/**
1063 * This structure steps restores the enrol plugins and their underlying
1064 * enrolments, performing all the mappings and/or movements required
1065 */
1066class restore_enrolments_structure_step extends restore_structure_step {
1067
1068 protected function define_structure() {
1069
1070 $paths = array();
1071
1072 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1073 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1074
1075 return $paths;
1076 }
1077
1078 public function process_enrol($data) {
1079 global $DB;
1080
1081 $data = (object)$data;
1082 $oldid = $data->id; // We'll need this later
1083
1084 // TODO: Just one quick process of manual enrol_plugin. Add the rest (complex ones) and fix this
1085 if ($data->enrol !== 'manual') {
1086 debugging("Skipping '{$data->enrol}' enrolment plugin. Must be implemented", DEBUG_DEVELOPER);
1087 return;
1088 }
1089
1090 // Perform various checks to decide what to do with the enrol plugin
1091 $installed = array_key_exists($data->enrol, enrol_get_plugins(false));
1092 $enabled = enrol_is_enabled($data->enrol);
1093 $exists = 0;
1094 $roleid = $this->get_mappingid('role', $data->roleid);
1095 if ($rec = $DB->get_record('enrol', array('courseid' => $this->get_courseid(), 'enrol' => $data->enrol))) {
1096 $exists = $rec->id;
1097 }
1098 // If installed and enabled, continue processing
1099 if ($installed && $enabled) {
1100 // If not exists in course and we have a target role mapping
1101 if (!$exists && $roleid) {
1102 $data->roleid = $roleid;
1103 $enrol = enrol_get_plugin($data->enrol);
1104 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1105 $newitemid = $enrol->add_instance($courserec, array($data));
1106
1107 // Already exists, user it for enrolments
1108 } else {
1109 $newitemid = $exists;
1110 }
1111
1112 // Not installed and enabled, map to 0
1113 } else {
1114 $newitemid = 0;
1115 }
1116 // Perform the simple mapping and done
1117 $this->set_mapping('enrol', $oldid, $newitemid);
1118 }
1119
1120 public function process_enrolment($data) {
1121 global $DB;
1122
1123 $data = (object)$data;
1124
1125 // Process only if parent instance have been mapped
1126 if ($enrolid = $this->get_new_parentid('enrol')) {
1127 // And only if user is a mapped one
1128 if ($userid = $this->get_mappingid('user', $data->userid)) {
1129 // TODO: Surely need to use API (enrol_user) here, instead of the current low-level impl
1130 // TODO: Note enrol_user() sticks to $USER->id (need to add userid param)
1131 $enrolment = new stdclass();
1132 $enrolment->enrolid = $enrolid;
1133 $enrolment->userid = $userid;
1134 if (!$DB->record_exists('user_enrolments', (array)$enrolment)) {
1135 $enrolment->status = $data->status;
1136 $enrolment->timestart = $data->timestart;
1137 $enrolment->timeend = $data->timeend;
1138 $enrolment->modifierid = $this->task->get_userid();
1139 $enrolment->timecreated = time();
1140 $enrolment->timemodified = 0;
1141 $DB->insert_record('user_enrolments', $enrolment);
1142 }
1143 }
1144 }
1145 }
1146}
21e51c86
EL
1147
1148
1149/**
1150 * This structure steps restores the filters and their configs
1151 */
1152class restore_filters_structure_step extends restore_structure_step {
1153
1154 protected function define_structure() {
1155
1156 $paths = array();
1157
1158 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1159 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1160
1161 return $paths;
1162 }
1163
1164 public function process_active($data) {
1165
1166 $data = (object)$data;
1167
1168 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1169 return;
1170 }
1171 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1172 }
1173
1174 public function process_config($data) {
1175
1176 $data = (object)$data;
1177
1178 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1179 return;
1180 }
1181 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1182 }
1183}
1184
1185
1186/**
1187 * This structure steps restores the comments
1188 * Note: Cannot use the comments API because defaults to USER->id.
1189 * That should change allowing to pass $userid
1190 */
1191class restore_comments_structure_step extends restore_structure_step {
1192
1193 protected function define_structure() {
1194
1195 $paths = array();
1196
1197 $paths[] = new restore_path_element('comment', '/comments/comment');
1198
1199 return $paths;
1200 }
1201
1202 public function process_comment($data) {
1203 global $DB;
1204
1205 $data = (object)$data;
1206
1207 // First of all, if the comment has some itemid, ask to the task what to map
1208 $mapping = false;
21e51c86 1209 if ($data->itemid) {
39aa0280
EL
1210 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1211 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
21e51c86
EL
1212 }
1213 // Only restore the comment if has no mapping OR we have found the matching mapping
39aa0280 1214 if (!$mapping || $data->itemid) {
b8e455a7
EL
1215 // Only if user mapping and context
1216 $data->userid = $this->get_mappingid('user', $data->userid);
1217 if ($data->userid && $this->task->get_contextid()) {
21e51c86 1218 $data->contextid = $this->task->get_contextid();
b8e455a7
EL
1219 // Only if there is another comment with same context/user/timecreated
1220 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1221 if (!$DB->record_exists('comments', $params)) {
1222 $DB->insert_record('comments', $data);
1223 }
1224 }
1225 }
1226 }
1227}
1228
bd39b6f2
SH
1229class restore_course_completion_structure_step extends restore_structure_step {
1230
1231 /**
1232 * Conditionally decide if this step should be executed.
1233 *
1234 * This function checks parameters that are not immediate settings to ensure
1235 * that the enviroment is suitable for the restore of course completion info.
1236 *
1237 * This function checks the following four parameters:
1238 *
1239 * 1. Course completion is enabled on the site
1240 * 2. The backup includes course completion information
1241 * 3. All modules are restorable
1242 * 4. All modules are marked for restore.
1243 *
1244 * @return bool True is safe to execute, false otherwise
1245 */
1246 protected function execute_condition() {
1247 global $CFG;
1248
1249 // First check course completion is enabled on this site
1250 if (empty($CFG->enablecompletion)) {
1251 // Disabled, don't restore course completion
1252 return false;
1253 }
1254
1255 // Check it is included in the backup
1256 $fullpath = $this->task->get_taskbasepath();
1257 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1258 if (!file_exists($fullpath)) {
1259 // Not found, can't restore course completion
1260 return false;
1261 }
1262
1263 // Check we are able to restore all backed up modules
1264 if ($this->task->is_missing_modules()) {
1265 return false;
1266 }
1267
1268 // Finally check all modules within the backup are being restored.
1269 if ($this->task->is_excluding_activities()) {
1270 return false;
1271 }
1272
1273 return true;
1274 }
1275
1276 /**
1277 * Define the course completion structure
1278 *
1279 * @return array Array of restore_path_element
1280 */
1281 protected function define_structure() {
1282
1283 // To know if we are including user completion info
1284 $userinfo = $this->get_setting_value('userscompletion');
1285
1286 $paths = array();
1287 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1288 $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1289 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1290
1291 if ($userinfo) {
1292 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1293 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1294 }
1295
1296 return $paths;
1297
1298 }
1299
1300 /**
1301 * Process course completion criteria
1302 *
1303 * @global moodle_database $DB
1304 * @param stdClass $data
1305 */
1306 public function process_course_completion_criteria($data) {
1307 global $DB;
1308
1309 $data = (object)$data;
1310 $data->course = $this->get_courseid();
1311
1312 // Apply the date offset to the time end field
1313 $data->timeend = $this->apply_date_offset($data->timeend);
1314
1315 // Map the role from the criteria
1316 if (!empty($data->role)) {
1317 $data->role = $this->get_mappingid('role', $data->role);
1318 }
1319
1320 // If the completion criteria is for a module we need to map the module instance
1321 // to the new module id.
1322 if (!empty($data->moduleinstance) && !empty($data->module)) {
1323 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
1324 } else {
1325 $data->module = null;
1326 $data->moduleinstance = null;
1327 }
1328
1329 // We backup the course shortname rather than the ID so that we can match back to the course
1330 $skipcriteria = false;
1331 if (!empty($data->courseinstanceshortname)) {
1332 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1333 if (!$courseinstanceid) {
1334 $skipcriteria = true;
1335 }
1336 } else {
1337 $courseinstanceid = null;
1338 }
1339 $data->courseinstance = $courseinstanceid;
1340
1341 if (!$skipcriteria) {
1342 $params = array(
1343 'course' => $data->course,
1344 'criteriatype' => $data->criteriatype,
1345 'enrolperiod' => $data->enrolperiod,
1346 'courseinstance' => $data->courseinstance,
1347 'module' => $data->module,
1348 'moduleinstance' => $data->moduleinstance,
1349 'timeend' => $data->timeend,
1350 'gradepass' => $data->gradepass,
1351 'role' => $data->role
1352 );
1353 $newid = $DB->insert_record('course_completion_criteria', $params);
1354 $this->set_mapping('course_completion_criteria', $data->id, $newid);
1355 }
1356 }
1357
1358 /**
1359 * Processes course compltion criteria complete records
1360 *
1361 * @global moodle_database $DB
1362 * @param stdClass $data
1363 */
1364 public function process_course_completion_crit_compl($data) {
1365 global $DB;
1366
1367 $data = (object)$data;
1368
1369 // This may be empty if criteria could not be restored
1370 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
1371
1372 $data->course = $this->get_courseid();
1373 $data->userid = $this->get_mappingid('user', $data->userid);
1374
1375 if (!empty($data->criteriaid) && !empty($data->userid)) {
1376 $params = array(
1377 'userid' => $data->userid,
1378 'course' => $data->course,
1379 'criteriaid' => $data->criteriaid,
1380 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1381 );
1382 if (isset($data->gradefinal)) {
1383 $params['gradefinal'] = $data->gradefinal;
1384 }
1385 if (isset($data->unenroled)) {
1386 $params['unenroled'] = $data->unenroled;
1387 }
1388 if (isset($data->deleted)) {
1389 $params['deleted'] = $data->deleted;
1390 }
1391 $DB->insert_record('course_completion_crit_compl', $params);
1392 }
1393 }
1394
1395 /**
1396 * Process course completions
1397 *
1398 * @global moodle_database $DB
1399 * @param stdClass $data
1400 */
1401 public function process_course_completions($data) {
1402 global $DB;
1403
1404 $data = (object)$data;
1405
1406 $data->course = $this->get_courseid();
1407 $data->userid = $this->get_mappingid('user', $data->userid);
1408
1409 if (!empty($data->userid)) {
1410 $params = array(
1411 'userid' => $data->userid,
1412 'course' => $data->course,
1413 'deleted' => $data->deleted,
1414 'timenotified' => $this->apply_date_offset($data->timenotified),
1415 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1416 'timestarted' => $this->apply_date_offset($data->timestarted),
1417 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1418 'reaggregate' => $data->reaggregate
1419 );
1420 $DB->insert_record('course_completions', $params);
1421 }
1422 }
1423
1424 /**
1425 * Process course completion notification records.
1426 *
1427 * Note: As of Moodle 2.0 this table is not being used however it has been
1428 * left in in the hopes that one day the functionality there will be completed
1429 *
1430 * @global moodle_database $DB
1431 * @param stdClass $data
1432 */
1433 public function process_course_completion_notify($data) {
1434 global $DB;
1435
1436 $data = (object)$data;
1437
1438 $data->course = $this->get_courseid();
1439 if (!empty($data->role)) {
1440 $data->role = $this->get_mappingid('role', $data->role);
1441 }
1442
1443 $params = array(
1444 'course' => $data->course,
1445 'role' => $data->role,
1446 'message' => $data->message,
1447 'timesent' => $this->apply_date_offset($data->timesent),
1448 );
1449 $DB->insert_record('course_completion_notify', $params);
1450 }
1451
1452 /**
1453 * Process course completion aggregate methods
1454 *
1455 * @global moodle_database $DB
1456 * @param stdClass $data
1457 */
1458 public function process_course_completion_aggr_methd($data) {
1459 global $DB;
1460
1461 $data = (object)$data;
1462
1463 $data->course = $this->get_courseid();
1464
1465 $params = array(
1466 'course' => $data->course,
1467 'criteriatype' => $data->criteriatype,
1468 'method' => $data->method,
1469 'value' => $data->value,
1470 );
1471 $DB->insert_record('course_completion_aggr_methd', $params);
1472 }
1473
1474}
1475
9a1cfcbc
EL
1476/**
1477 * This structure step restores the grade items associated with one activity
1478 * All the grade items are made child of the "course" grade item but the original
1479 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
1480 * the complete gradebook (categories and calculations), that information is
1481 * available there
1482 */
1483class restore_activity_grades_structure_step extends restore_structure_step {
1484
1485 protected function define_structure() {
1486
1487 $paths = array();
1488 $userinfo = $this->get_setting_value('userinfo');
1489
1490 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
1491 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
1492 if ($userinfo) {
1493 $paths[] = new restore_path_element('grade_grade',
1494 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
1495 }
1496 return $paths;
1497 }
1498
1499 protected function process_grade_item($data) {
1500
1501 $data = (object)($data);
1502 $oldid = $data->id; // We'll need these later
1503 $oldparentid = $data->categoryid;
1504
1505 // make sure top course category exists, all grade items will be associated
1506 // to it. Later, if restoring the whole gradebook, categories will be introduced
1507 $coursecat = grade_category::fetch_course_category($this->get_courseid());
1508 $coursecatid = $coursecat->id; // Get the categoryid to be used
1509
1510 unset($data->id);
1511 $data->categoryid = $coursecatid;
1512 $data->courseid = $this->get_courseid();
1513 $data->iteminstance = $this->task->get_activityid();
1514 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
1515 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
1516 // so the best is to keep the ones already in the gradebook
1517 // Potential problem: duplicates if same items are restored more than once. :-(
1518 // This needs to be fixed in some way (outcomes & activities with multiple items)
1519 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
1520 // In any case, verify always for uniqueness
a789ac6f 1521 $data->idnumber = grade_verify_idnumber($data->idnumber, $this->get_courseid()) ? $data->idnumber : null;
9a1cfcbc
EL
1522 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1523 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
1524 $data->timecreated = $this->apply_date_offset($data->timecreated);
1525 $data->timemodified = $this->apply_date_offset($data->timemodified);
1526
1527 $gradeitem = new grade_item($data);
1528 $gradeitem->insert('restore');
4d787d8a
AD
1529
1530 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
1531 $gradeitem->sortorder = $data->sortorder;
1532 $gradeitem->update('restore');
1533
dc362c44
EL
1534 // Set mapping, saving the original category id into parentitemid
1535 // gradebook restore (final task) will need it to reorganise items
1536 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
9a1cfcbc
EL
1537 }
1538
1539 protected function process_grade_grade($data) {
1540 $data = (object)($data);
1541
1542 unset($data->id);
1543 $data->itemid = $this->get_new_parentid('grade_item');
1544 $data->userid = $this->get_mappingid('user', $data->userid);
1545 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
1546 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
1547 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
1548 $data->overridden = $this->apply_date_offset($data->overridden);
1549
1550 $grade = new grade_grade($data);
1551 $grade->insert('restore');
1552 // no need to save any grade_grade mapping
1553 }
1554
1555 /**
1556 * process activity grade_letters. Note that, while these are possible,
1557 * because grade_letters are contextid based, in proctice, only course
1558 * context letters can be defined. So we keep here this method knowing
1559 * it won't be executed ever. gradebook restore will restore course letters.
1560 */
1561 protected function process_grade_letter($data) {
1562 global $DB;
1563
1564 $data = (object)$data;
1565
1566 $data->contextid = $this->task->get_contextid();
1567 $newitemid = $DB->insert_record('grade_letters', $data);
1568 // no need to save any grade_letter mapping
1569 }
1570}
1571
b8e455a7
EL
1572
1573/**
1574 * This structure steps restores one instance + positions of one block
1575 * Note: Positions corresponding to one existing context are restored
1576 * here, but all the ones having unknown contexts are sent to backup_ids
1577 * for a later chance to be restored at the end (final task)
1578 */
1579class restore_block_instance_structure_step extends restore_structure_step {
1580
1581 protected function define_structure() {
1582
1583 $paths = array();
1584
1585 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
1586 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
1587
1588 return $paths;
1589 }
1590
1591 public function process_block($data) {
1592 global $DB;
1593
1594 $data = (object)$data; // Handy
1595 $oldcontextid = $data->contextid;
1596 $oldid = $data->id;
1597 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1598
1599 // Look for the parent contextid
1600 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1601 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1602 }
1603
1604 // If there is already one block of that type in the parent context
1605 // and the block is not multiple, stop processing
1606 if ($DB->record_exists_sql("SELECT bi.id
1607 FROM {block_instances} bi
1608 JOIN {block} b ON b.name = bi.blockname
1609 WHERE bi.parentcontextid = ?
1610 AND bi.blockname = ?
1611 AND b.multiple = 0", array($data->parentcontextid, $data->blockname))) {
1612 return false;
1613 }
1614
1615 // If there is already one block of that type in the parent context
1616 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
1617 // stop processing
1618 $params = array(
1619 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
1620 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
1621 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
1622 if ($birecs = $DB->get_records('block_instances', $params)) {
1623 foreach($birecs as $birec) {
1624 if ($birec->configdata == $data->configdata) {
1625 return false;
1626 }
1627 }
1628 }
1629
1630 // Set task old contextid, blockid and blockname once we know them
1631 $this->task->set_old_contextid($oldcontextid);
1632 $this->task->set_old_blockid($oldid);
1633 $this->task->set_blockname($data->blockname);
1634
1635 // Let's look for anything within configdata neededing processing
1636 // (nulls and uses of legacy file.php)
1637 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1638 $configdata = (array)unserialize(base64_decode($data->configdata));
1639 foreach ($configdata as $attribute => $value) {
1640 if (in_array($attribute, $attrstotransform)) {
1641 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
1642 }
1643 }
1644 $data->configdata = base64_encode(serialize((object)$configdata));
1645 }
1646
1647 // Create the block instance
1648 $newitemid = $DB->insert_record('block_instances', $data);
1649 // Save the mapping (with restorefiles support)
1650 $this->set_mapping('block_instance', $oldid, $newitemid, true);
1651 // Create the block context
1652 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
1653 // Save the block contexts mapping and sent it to task
1654 $this->set_mapping('context', $oldcontextid, $newcontextid);
1655 $this->task->set_contextid($newcontextid);
1656 $this->task->set_blockid($newitemid);
1657
1658 // Restore block fileareas if declared
1659 $component = 'block_' . $this->task->get_blockname();
1660 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
1661 $this->add_related_files($component, $filearea, null);
1662 }
1663
1664 // Process block positions, creating them or accumulating for final step
1665 foreach($positions as $position) {
1666 $position = (object)$position;
1667 $position->blockinstanceid = $newitemid; // The instance is always the restored one
1668 // If position is for one already mapped (known) contextid
1669 // process it now, creating the position
1670 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
1671 $position->contextid = $newpositionctxid;
1672 // Create the block position
1673 $DB->insert_record('block_positions', $position);
1674
1675 // The position belongs to an unknown context, send it to backup_ids
1676 // to process them as part of the final steps of restore. We send the
1677 // whole $position object there, hence use the low level method.
1678 } else {
1679 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
21e51c86
EL
1680 }
1681 }
1682 }
1683}
394edb7e
EL
1684
1685/**
1686 * Structure step to restore common course_module information
1687 *
1688 * This step will process the module.xml file for one activity, in order to restore
1689 * the corresponding information to the course_modules table, skipping various bits
1690 * of information based on CFG settings (groupings, completion...) in order to fullfill
1691 * all the reqs to be able to create the context to be used by all the rest of steps
1692 * in the activity restore task
1693 */
1694class restore_module_structure_step extends restore_structure_step {
1695
1696 protected function define_structure() {
1697 global $CFG;
1698
1699 $paths = array();
1700
1701 $paths[] = new restore_path_element('module', '/module');
1702 if ($CFG->enableavailability) {
1703 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
1704 }
1705
1706 return $paths;
1707 }
1708
1709 protected function process_module($data) {
1710 global $CFG, $DB;
1711
1712 $data = (object)$data;
1713 $oldid = $data->id;
1714
1715 $data->course = $this->task->get_courseid();
1716 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
aa39be20
EL
1717 // Map section (first try by course_section mapping match. Useful in course and section restores)
1718 $data->section = $this->get_mappingid('course_section', $data->sectionid);
1719 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
1720 $params = array(
1721 'course' => $this->get_courseid(),
1722 'section' => $data->sectionnumber);
1723 $data->section = $DB->get_field('course_sections', 'id', $params);
1724 }
1725 if (!$data->section) { // sectionnumber failed, try to get first section in course
1726 $params = array(
1727 'course' => $this->get_courseid());
1728 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
1729 }
1730 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
1731 $sectionrec = array(
1732 'course' => $this->get_courseid(),
1733 'section' => 0);
1734 $DB->insert_record('course_sections', $sectionrec); // section 0
1735 $sectionrec = array(
1736 'course' => $this->get_courseid(),
1737 'section' => 1);
1738 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
1739 }
394edb7e
EL
1740 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
1741 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
1742 $data->groupmembersonly = 0;
1743 }
1744 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
1745 $data->idnumber = '';
1746 }
5095f325 1747 if (empty($CFG->enablecompletion)) { // completion
394edb7e
EL
1748 $data->completion = 0;
1749 $data->completiongradeitemnumber = null;
1750 $data->completionview = 0;
1751 $data->completionexpected = 0;
1752 } else {
1753 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
1754 }
1755 if (empty($CFG->enableavailability)) {
1756 $data->availablefrom = 0;
1757 $data->availableuntil = 0;
1758 $data->showavailability = 0;
1759 } else {
1760 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
1761 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
1762 }
1763 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
1764
1765 // course_module record ready, insert it
1766 $newitemid = $DB->insert_record('course_modules', $data);
1767 // save mapping
1768 $this->set_mapping('course_module', $oldid, $newitemid);
1769 // set the new course_module id in the task
1770 $this->task->set_moduleid($newitemid);
1771 // we can now create the context safely
1772 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
1773 // set the new context id in the task
1774 $this->task->set_contextid($ctxid);
1775 // update sequence field in course_section
1776 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
1777 $sequence .= ',' . $newitemid;
1778 } else {
1779 $sequence = $newitemid;
1780 }
1781 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
1782 }
1783
1784
1785 protected function process_availability($data) {
394edb7e 1786 $data = (object)$data;
5095f325
EL
1787 // Simply going to store the whole availability record now, we'll process
1788 // all them later in the final task (once all actvivities have been restored)
1789 // Let's call the low level one to be able to store the whole object
1790 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
1791 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
1792 }
1793}
1794
1795/**
1796 * Structure step that will process the user activity completion
1797 * information if all these conditions are met:
1798 * - Target site has completion enabled ($CFG->enablecompletion)
1799 * - Activity includes completion info (file_exists)
1800 */
1801class restore_userscompletion_structure_step extends restore_structure_step {
1802
1803 /**
1804 * To conditionally decide if this step must be executed
1805 * Note the "settings" conditions are evaluated in the
1806 * corresponding task. Here we check for other conditions
1807 * not being restore settings (files, site settings...)
1808 */
1809 protected function execute_condition() {
1810 global $CFG;
1811
1812 // Completion disabled in this site, don't execute
1813 if (empty($CFG->enablecompletion)) {
1814 return false;
1815 }
1816
1817 // No user completion info found, don't execute
1818 $fullpath = $this->task->get_taskbasepath();
1819 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1820 if (!file_exists($fullpath)) {
1821 return false;
1822 }
1823
1824 // Arrived here, execute the step
1825 return true;
1826 }
1827
1828 protected function define_structure() {
1829
1830 $paths = array();
1831
1832 $paths[] = new restore_path_element('completion', '/completions/completion');
1833
1834 return $paths;
1835 }
1836
1837 protected function process_completion($data) {
1838 global $DB;
1839
1840 $data = (object)$data;
1841
1842 $data->coursemoduleid = $this->task->get_moduleid();
1843 $data->userid = $this->get_mappingid('user', $data->userid);
1844 $data->timemodified = $this->apply_date_offset($data->timemodified);
1845
1846 $DB->insert_record('course_modules_completion', $data);
394edb7e
EL
1847 }
1848}
1849
1850/**
1851 * Abstract structure step, parent of all the activity structure steps. Used to suuport
1852 * the main <activity ...> tag and process it. Also provides subplugin support for
1853 * activities.
1854 */
1855abstract class restore_activity_structure_step extends restore_structure_step {
1856
91d11057
EL
1857 protected function add_subplugin_structure($subplugintype, $element) {
1858
1859 global $CFG;
1860
1861 // Check the requested subplugintype is a valid one
1862 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
1863 if (!file_exists($subpluginsfile)) {
1864 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
1865 }
1866 include($subpluginsfile);
1867 if (!array_key_exists($subplugintype, $subplugins)) {
1868 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
1869 }
1870 // Get all the restore path elements, looking across all the subplugin dirs
1871 $subpluginsdirs = get_plugin_list($subplugintype);
1872 foreach ($subpluginsdirs as $name => $subpluginsdir) {
1873 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
1874 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
1875 if (file_exists($restorefile)) {
1876 require_once($restorefile);
1877 $restoresubplugin = new $classname($subplugintype, $name, $this);
1878 // Add subplugin paths to the step
1879 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
1880 }
1881 }
1882 }
1883
1884 /**
1885 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
1886 * have the parent task available for wrapping purposes (get course/context....)
1887 */
1888 public function get_task() {
1889 return $this->task;
394edb7e
EL
1890 }
1891
1892 /**
1893 * Adds support for the 'activity' path that is common to all the activities
1894 * and will be processed globally here
1895 */
1896 protected function prepare_activity_structure($paths) {
1897
1898 $paths[] = new restore_path_element('activity', '/activity');
1899
1900 return $paths;
1901 }
1902
1903 /**
1904 * Process the activity path, informing the task about various ids, needed later
1905 */
1906 protected function process_activity($data) {
1907 $data = (object)$data;
1908 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
1909 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
1910 $this->task->set_old_activityid($data->id); // Save old activityid in task
1911 }
1912
1913 /**
1914 * This must be invoked inmediately after creating the "module" activity record (forum, choice...)
1915 * and will adjust the new activity id (the instance) in various places
1916 */
1917 protected function apply_activity_instance($newitemid) {
1918 global $DB;
1919
1920 $this->task->set_activityid($newitemid); // Save activity id in task
1921 // Apply the id to course_sections->instanceid
1922 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
1923 // Do the mapping for modulename, preparing it for files by oldcontext
1924 $modulename = $this->task->get_modulename();
1925 $oldid = $this->task->get_old_activityid();
1926 $this->set_mapping($modulename, $oldid, $newitemid, true);
1927 }
1928}