MDL-21432 backup - restore of activity grade items added. Blame MDL-23701 for the...
[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);
482aac65
EL
50 }
51}
52
53/**
54 * delete the temp dir used by backup/restore (conditionally),
55 * delete old directories and drop temp ids table
56 */
57class restore_drop_and_clean_temp_stuff extends restore_execution_step {
58
59 protected function define_execution() {
60 global $CFG;
b8bb45b0 61 restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
b1eaf633 62 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
482aac65 63 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
b1eaf633 64 backup_helper::delete_backup_dir($this->task->get_tempdir()); // Empty restore dir
482aac65
EL
65 }
66 }
67}
68
394edb7e
EL
69/**
70 * decode all the interlinks present in restored content
71 * relying 100% in the restore_decode_processor that handles
72 * both the contents to modify and the rules to be applied
73 */
74class restore_decode_interlinks extends restore_execution_step {
75
76 protected function define_execution() {
77 // Just that
78 $this->task->get_decoder()->execute();
79 }
80}
81
82/**
83 * rebuid the course cache
84 */
85class restore_rebuild_course_cache extends restore_execution_step {
86
87 protected function define_execution() {
88 // Just that
89 rebuild_course_cache($this->get_courseid());
90 }
91}
92
b8e455a7
EL
93
94/**
95 * Review all the (pending) block positions in backup_ids, matching by
96 * contextid, creating positions as needed. This is executed by the
97 * final task, once all the contexts have been created
98 */
99class restore_review_pending_block_positions extends restore_execution_step {
100
101 protected function define_execution() {
102 global $DB;
103
104 // Get all the block_position objects pending to match
105 $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
106 $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid');
107 // Process block positions, creating them or accumulating for final step
108 foreach($rs as $posrec) {
109 // Get the complete position object (stored as info)
110 $position = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'block_position', $posrec->itemid)->info;
111 // If position is for one already mapped (known) contextid
112 // process it now, creating the position, else nothing to
113 // do, position finally discarded
114 if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
115 $position->contextid = $newctx->newitemid;
116 // Create the block position
117 $DB->insert_record('block_positions', $position);
118 }
119 }
120 $rs->close();
121 }
122}
123
482aac65
EL
124/*
125 * Execution step that, *conditionally* (if there isn't preloaded information)
126 * will load the inforef files for all the included course/section/activity tasks
127 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
128 */
129class restore_load_included_inforef_records extends restore_execution_step {
130
131 protected function define_execution() {
132
133 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
134 return;
135 }
136
137 // Get all the included inforef files
138 $files = restore_dbops::get_needed_inforef_files($this->get_restoreid());
139 foreach ($files as $file) {
140 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $file); // Load each inforef file to temp_ids
141 }
142 }
143}
144
76cfb124 145/*
b8bb45b0 146 * Execution step that will load all the needed files into backup_files_temp
76cfb124
EL
147 * - info: contains the whole original object (times, names...)
148 * (all them being original ids as loaded from xml)
149 */
150class restore_load_included_files extends restore_structure_step {
151
152 protected function define_structure() {
153
154 $file = new restore_path_element('file', '/files/file');
155
156 return array($file);
157 }
158
159 // Processing functions go here
160 public function process_file($data) {
161
162 $data = (object)$data; // handy
163
76cfb124
EL
164 // load it if needed:
165 // - it it is one of the annotated inforef files (course/section/activity/block)
71a50b13 166 // - it is one "user", "group", "grouping" or "grade" component file (that aren't sent to inforef ever)
b8bb45b0 167 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
71a50b13
EL
168 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
169 $data->component == 'grouping' || $data->component == 'grade');
76cfb124 170 if ($isfileref || $iscomponent) {
b8bb45b0 171 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
76cfb124
EL
172 }
173 }
174}
175
71a50b13
EL
176/**
177 * Execution step that, *conditionally* (if there isn't preloaded information),
178 * will load all the needed roles to backup_temp_ids. They will be stored with
179 * "role" itemname. Also it will perform one automatic mapping to roles existing
180 * in the target site, based in permissions of the user performing the restore,
181 * archetypes and other bits. At the end, each original role will have its associated
182 * target role or 0 if it's going to be skipped. Note we wrap everything over one
183 * restore_dbops method, as far as the same stuff is going to be also executed
184 * by restore prechecks
185 */
186class restore_load_and_map_roles extends restore_execution_step {
187
188 protected function define_execution() {
8d4e41f4 189 if ($this->task->get_preloaded_information()) { // if info is already preloaded
71a50b13
EL
190 return;
191 }
192
193 $file = $this->get_basepath() . '/roles.xml';
194 // Load needed toles to temp_ids
195 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
8d4e41f4 196
71a50b13 197 // Process roles, mapping/skipping. Any error throws exception
8d4e41f4
EL
198 // Note we pass controller's info because it can contain role mapping information
199 // about manual mappings performed by UI
200 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
201 }
202}
203
482aac65
EL
204/**
205 * Execution step that, *conditionally* (if there isn't preloaded information
206 * and users have been selected in settings, will load all the needed users
207 * to backup_temp_ids. They will be stored with "user" itemname and with
76cfb124 208 * their original contextid as paremitemid
482aac65
EL
209 */
210class restore_load_included_users extends restore_execution_step {
211
212 protected function define_execution() {
213
214 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
215 return;
216 }
25d3cf44 217 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
482aac65
EL
218 return;
219 }
220 $file = $this->get_basepath() . '/users.xml';
221 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
222 }
223}
224
225/**
226 * Execution step that, *conditionally* (if there isn't preloaded information
227 * and users have been selected in settings, will process all the needed users
228 * in order to decide and perform any action with them (create / map / error)
229 * Note: Any error will cause exception, as far as this is the same processing
230 * than the one into restore prechecks (that should have stopped process earlier)
231 */
76cfb124 232class restore_process_included_users extends restore_execution_step {
482aac65
EL
233
234 protected function define_execution() {
235
236 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
237 return;
238 }
25d3cf44 239 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
482aac65
EL
240 return;
241 }
242 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
243 }
244}
245
76cfb124
EL
246/**
247 * Execution step that will create all the needed users as calculated
248 * by @restore_process_included_users (those having newiteind = 0)
249 */
250class restore_create_included_users extends restore_execution_step {
251
252 protected function define_execution() {
253
254 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->get_setting_value('user_files'));
255 }
256}
257
258/**
259 * Structure step that will create all the needed groups and groupings
260 * by loading them from the groups.xml file performing the required matches.
261 * Note group members only will be added if restoring user info
262 */
263class restore_groups_structure_step extends restore_structure_step {
264
c0440b3f
EL
265 protected function define_structure() {
266
267 $paths = array(); // Add paths here
268
269 $paths[] = new restore_path_element('group', '/groups/group');
270 if ($this->get_setting_value('users')) {
271 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
272 }
273 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
274 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
275
276 return $paths;
277 }
278
279 // Processing functions go here
280 public function process_group($data) {
281 global $DB;
282
283 $data = (object)$data; // handy
284 $data->courseid = $this->get_courseid();
285
286 $oldid = $data->id; // need this saved for later
76cfb124 287
c0440b3f
EL
288 $restorefiles = false; // Only if we end creating the group
289
290 // Search if the group already exists (by name & description) in the target course
291 $description_clause = '';
292 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
293 if (!empty($data->description)) {
294 $description_clause = ' AND ' .
295 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
296 $params['desc'] = $data->description;
297 }
298 if (!$groupdb = $DB->get_record_sql("SELECT *
299 FROM {groups}
300 WHERE courseid = :courseid
301 AND name = :grname $description_clause", $params)) {
302 // group doesn't exist, create
303 $newitemid = $DB->insert_record('groups', $data);
304 $restorefiles = true; // We'll restore the files
305 } else {
306 // group exists, use it
307 $newitemid = $groupdb->id;
308 }
309 // Save the id mapping
310 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
311 }
312
313 public function process_member($data) {
314 global $DB;
315
316 $data = (object)$data; // handy
317
318 // get parent group->id
319 $data->groupid = $this->get_new_parentid('group');
320
321 // map user newitemid and insert if not member already
322 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
323 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
324 $DB->insert_record('groups_members', $data);
325 }
326 }
327 }
328
329 public function process_grouping($data) {
71a50b13
EL
330 global $DB;
331
332 $data = (object)$data; // handy
333 $data->courseid = $this->get_courseid();
334
335 $oldid = $data->id; // need this saved for later
336 $restorefiles = false; // Only if we end creating the grouping
337
338 // Search if the grouping already exists (by name & description) in the target course
339 $description_clause = '';
340 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
341 if (!empty($data->description)) {
342 $description_clause = ' AND ' .
343 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
344 $params['desc'] = $data->description;
345 }
346 if (!$groupingdb = $DB->get_record_sql("SELECT *
347 FROM {groupings}
348 WHERE courseid = :courseid
349 AND name = :grname $description_clause", $params)) {
350 // grouping doesn't exist, create
351 $newitemid = $DB->insert_record('groupings', $data);
352 $restorefiles = true; // We'll restore the files
353 } else {
354 // grouping exists, use it
355 $newitemid = $groupingdb->id;
356 }
357 // Save the id mapping
358 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
c0440b3f
EL
359 }
360
361 public function process_grouping_group($data) {
71a50b13
EL
362 global $DB;
363
364 $data = (object)$data;
365
366 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
367 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
368 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
c0440b3f
EL
369 }
370
371 protected function after_execute() {
372 // Add group related files, matching with "group" mappings
373 $this->add_related_files('group', 'icon', 'group');
374 $this->add_related_files('group', 'description', 'group');
71a50b13
EL
375 // Add grouping related files, matching with "grouping" mappings
376 $this->add_related_files('grouping', 'description', 'grouping');
c0440b3f
EL
377 }
378
379}
380
381/**
382 * Structure step that will create all the needed scales
383 * by loading them from the scales.xml
c0440b3f
EL
384 */
385class restore_scales_structure_step extends restore_structure_step {
386
387 protected function define_structure() {
388
389 $paths = array(); // Add paths here
390 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
391 return $paths;
392 }
393
394 protected function process_scale($data) {
395 global $DB;
396
397 $data = (object)$data;
398
399 $restorefiles = false; // Only if we end creating the group
400
401 $oldid = $data->id; // need this saved for later
402
403 // Look for scale (by 'scale' both in standard (course=0) and current course
404 // with priority to standard scales (ORDER clause)
405 // scale is not course unique, use get_record_sql to suppress warning
406 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
407 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
408 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
409 if (!$scadb = $DB->get_record_sql("SELECT *
410 FROM {scale}
411 WHERE courseid IN (0, :courseid)
412 AND $compare_scale_clause
413 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
414 // Remap the user if possible, defaut to user performing the restore if not
415 $userid = $this->get_mappingid('user', $data->userid);
ba8bead5 416 $data->userid = $userid ? $userid : $this->task->get_userid();
c0440b3f
EL
417 // Remap the course if course scale
418 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
419 // If global scale (course=0), check the user has perms to create it
420 // falling to course scale if not
421 $systemctx = get_context_instance(CONTEXT_SYSTEM);
394edb7e 422 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
c0440b3f
EL
423 $data->courseid = $this->get_courseid();
424 }
425 // scale doesn't exist, create
426 $newitemid = $DB->insert_record('scale', $data);
427 $restorefiles = true; // We'll restore the files
428 } else {
429 // scale exists, use it
430 $newitemid = $scadb->id;
431 }
432 // Save the id mapping (with files support at system context)
433 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
434 }
435
436 protected function after_execute() {
437 // Add scales related files, matching with "scale" mappings
438 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
439 }
76cfb124
EL
440}
441
c0440b3f 442
c8730ff0
EL
443/**
444 * Structure step that will create all the needed outocomes
445 * by loading them from the outcomes.xml
446 */
447class restore_outcomes_structure_step extends restore_structure_step {
448
449 protected function define_structure() {
450
451 $paths = array(); // Add paths here
452 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
453 return $paths;
454 }
455
456 protected function process_outcome($data) {
457 global $DB;
458
459 $data = (object)$data;
460
461 $restorefiles = false; // Only if we end creating the group
462
463 $oldid = $data->id; // need this saved for later
464
465 // Look for outcome (by shortname both in standard (courseid=null) and current course
466 // with priority to standard outcomes (ORDER clause)
467 // outcome is not course unique, use get_record_sql to suppress warning
468 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
469 if (!$outdb = $DB->get_record_sql('SELECT *
470 FROM {grade_outcomes}
471 WHERE shortname = :shortname
472 AND (courseid = :courseid OR courseid IS NULL)
473 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
474 // Remap the user
475 $userid = $this->get_mappingid('user', $data->usermodified);
ba8bead5 476 $data->usermodified = $userid ? $userid : $this->task->get_userid();
8d4e41f4
EL
477 // Remap the scale
478 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
c8730ff0
EL
479 // Remap the course if course outcome
480 $data->courseid = $data->courseid ? $this->get_courseid() : null;
481 // If global outcome (course=null), check the user has perms to create it
482 // falling to course outcome if not
483 $systemctx = get_context_instance(CONTEXT_SYSTEM);
394edb7e 484 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
c8730ff0
EL
485 $data->courseid = $this->get_courseid();
486 }
487 // outcome doesn't exist, create
488 $newitemid = $DB->insert_record('grade_outcomes', $data);
489 $restorefiles = true; // We'll restore the files
490 } else {
491 // scale exists, use it
492 $newitemid = $outdb->id;
493 }
494 // Set the corresponding grade_outcomes_courses record
495 $outcourserec = new stdclass();
496 $outcourserec->courseid = $this->get_courseid();
497 $outcourserec->outcomeid = $newitemid;
498 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
499 $DB->insert_record('grade_outcomes_courses', $outcourserec);
500 }
501 // Save the id mapping (with files support at system context)
502 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
503 }
504
505 protected function after_execute() {
506 // Add outcomes related files, matching with "outcome" mappings
507 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
508 }
509}
510
3223cc95
EL
511/**
512 * Structure step that will read the section.xml creating/updating sections
513 * as needed, rebuilding course cache and other friends
514 */
515class restore_section_structure_step extends restore_structure_step {
c8730ff0 516
3223cc95
EL
517 protected function define_structure() {
518 return array(new restore_path_element('section', '/section'));
519 }
520
521 public function process_section($data) {
522 global $DB;
523 $data = (object)$data;
524 $oldid = $data->id; // We'll need this later
525
526 $restorefiles = false;
527
528 // Look for the section
529 $section = new stdclass();
530 $section->course = $this->get_courseid();
531 $section->section = $data->number;
532 // Section doesn't exist, create it with all the info from backup
533 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
534 $section->name = $data->name;
535 $section->summary = $data->summary;
536 $section->summaryformat = $data->summaryformat;
537 $section->sequence = '';
538 $section->visible = $data->visible;
539 $newitemid = $DB->insert_record('course_sections', $section);
540 $restorefiles = true;
541
542 // Section exists, update non-empty information
543 } else {
544 $section->id = $secrec->id;
545 if (empty($secrec->name)) {
546 $section->name = $data->name;
547 }
548 if (empty($secrec->summary)) {
549 $section->summary = $data->summary;
550 $section->summaryformat = $data->summaryformat;
551 $restorefiles = true;
552 }
553 $DB->update_record('course_sections', $section);
554 $newitemid = $secrec->id;
555 }
556
557 // Annotate the section mapping, with restorefiles option if needed
558 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
559
560 // If needed, adjust course->numsections
561 if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
562 if ($numsections < $section->section) {
563 $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
564 }
565 }
566 }
567
568 protected function after_execute() {
569 // Add section related files, with 'course_section' itemid to match
570 $this->add_related_files('course', 'section', 'course_section');
571 }
572}
573
574
575/**
482aac65 576 * Structure step that will read the course.xml file, loading it and performing
395dae30
EL
577 * various actions depending of the site/restore settings. Note that target
578 * course always exist before arriving here so this step will be updating
579 * the course record (never inserting)
482aac65
EL
580 */
581class restore_course_structure_step extends restore_structure_step {
582
583 protected function define_structure() {
584
585 $course = new restore_path_element('course', '/course', true); // Grouped
586 $category = new restore_path_element('category', '/course/category');
587 $tag = new restore_path_element('tag', '/course/tags/tag');
588 $allowed = new restore_path_element('allowed', '/course/allowed_modules/module');
589
590 return array($course, $category, $tag, $allowed);
591 }
592
593 // Processing functions go here
594 public function process_course($data) {
395dae30
EL
595 global $CFG, $DB;
596
597 $data = (object)$data;
598 $coursetags = isset($data->tags['tag']) ? $data->tags['tag'] : array();
599 $coursemodules = isset($data->allowed_modules['module']) ? $data->allowed_modules['module'] : array();
600 $oldid = $data->id; // We'll need this later
785d6603
SH
601
602 $fullname = $this->get_setting_value('course_fullname');
603 $shortname = $this->get_setting_value('course_shortname');
b1eaf633 604 $startdate = $this->get_setting_value('course_startdate');
395dae30
EL
605
606 // Calculate final course names, to avoid dupes
607 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
608
609 // Need to change some fields before updating the course record
610 $data->id = $this->get_courseid();
611 $data->fullname = $fullname;
612 $data->shortname= $shortname;
613 $data->idnumber = '';
785d6603
SH
614 // TODO: Set category from the UI, its not a setting just a param
615 $data->category = get_course_category()->id;
395dae30
EL
616 $data->startdate= $this->apply_date_offset($data->startdate);
617 if ($data->defaultgroupingid) {
618 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
619 }
620 if (empty($CFG->enablecompletion) || !$this->get_setting_value('userscompletion')) {
621 $data->enablecompletion = 0;
622 $data->completionstartonenrol = 0;
623 $data->completionnotify = 0;
624 }
625 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
626 if (!array_key_exists($data->lang, $languages)) {
627 $data->lang = '';
628 }
629 $themes = get_list_of_themes(); // Get themes for quick search later
630 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
631 $data->theme = '';
632 }
633
634 // Course record ready, update it
635 $DB->update_record('course', $data);
636
394edb7e
EL
637 // Set course mapping
638 $this->set_mapping('course', $oldid, $data->id);
639
395dae30
EL
640 // Course tags
641 if (!empty($CFG->usetags) && isset($coursetags)) { // if enabled in server and present in backup
642 $tags = array();
643 foreach ($coursetags as $coursetag) {
644 $coursetag = (object)$coursetag;
645 $tags[] = $coursetag->rawname;
646 }
647 tag_set('course', $this->get_courseid(), $tags);
648 }
649 // Course allowed modules
650 if (!empty($data->restrictmodules) && !empty($coursemodules)) {
651 $available = get_plugin_list('mod');
652 foreach ($coursemodules as $coursemodule) {
653 $mname = $coursemodule['modulename'];
654 if (array_key_exists($mname, $available)) {
655 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
656 $rec = new stdclass();
657 $rec->course = $this->get_courseid();
658 $rec->module = $module->id;
659 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
660 $DB->insert_record('course_allowed_modules', $rec);
661 }
662 }
663 }
664 }
665 }
666 // Role name aliases
667 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
482aac65
EL
668 }
669
395dae30
EL
670 protected function after_execute() {
671 // Add course related files, without itemid to match
672 $this->add_related_files('course', 'summary', null);
673 $this->add_related_files('course', 'legacy', null);
674 }
482aac65 675}
024c288d
EL
676
677
678/*
679 * Structure step that will read the roles.xml file (at course/activity/block levels)
680 * containig all the role_assignments and overrides for that context. If corresponding to
681 * one mapped role, they will be applied to target context. Will observe the role_assignments
682 * setting to decide if ras are restored.
683 * Note: only ras with component == null are restored as far as the any ra with component
684 * is handled by one enrolment plugin, hence it will createt the ras later
685 */
686class restore_ras_and_caps_structure_step extends restore_structure_step {
687
688 protected function define_structure() {
689
690 $paths = array();
691
692 // Observe the role_assignments setting
693 if ($this->get_setting_value('role_assignments')) {
694 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
695 }
696 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
697
698 return $paths;
699 }
700
701 public function process_assignment($data) {
702 $data = (object)$data;
703
704 // Check roleid, userid are one of the mapped ones
705 $newroleid = $this->get_mappingid('role', $data->roleid);
706 $newuserid = $this->get_mappingid('user', $data->userid);
b8e455a7
EL
707 // If newroleid and newuserid and component is empty and context valid assign via API (handles dupes and friends)
708 if ($newroleid && $newuserid && empty($data->component) && $this->task->get_contextid()) {
024c288d
EL
709 // TODO: role_assign() needs one userid param to be able to specify our restore userid
710 role_assign($newroleid, $newuserid, $this->task->get_contextid());
711 }
712 }
713
714 public function process_override($data) {
715 $data = (object)$data;
716
717 // Check roleid is one of the mapped ones
718 $newroleid = $this->get_mappingid('role', $data->roleid);
b8e455a7
EL
719 // If newroleid and context are valid assign it via API (it handles dupes and so on)
720 if ($newroleid && $this->task->get_contextid()) {
024c288d 721 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
b8e455a7 722 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
024c288d
EL
723 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
724 }
725 }
726}
727
728/**
729 * This structure steps restores the enrol plugins and their underlying
730 * enrolments, performing all the mappings and/or movements required
731 */
732class restore_enrolments_structure_step extends restore_structure_step {
733
734 protected function define_structure() {
735
736 $paths = array();
737
738 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
739 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
740
741 return $paths;
742 }
743
744 public function process_enrol($data) {
745 global $DB;
746
747 $data = (object)$data;
748 $oldid = $data->id; // We'll need this later
749
750 // TODO: Just one quick process of manual enrol_plugin. Add the rest (complex ones) and fix this
751 if ($data->enrol !== 'manual') {
752 debugging("Skipping '{$data->enrol}' enrolment plugin. Must be implemented", DEBUG_DEVELOPER);
753 return;
754 }
755
756 // Perform various checks to decide what to do with the enrol plugin
757 $installed = array_key_exists($data->enrol, enrol_get_plugins(false));
758 $enabled = enrol_is_enabled($data->enrol);
759 $exists = 0;
760 $roleid = $this->get_mappingid('role', $data->roleid);
761 if ($rec = $DB->get_record('enrol', array('courseid' => $this->get_courseid(), 'enrol' => $data->enrol))) {
762 $exists = $rec->id;
763 }
764 // If installed and enabled, continue processing
765 if ($installed && $enabled) {
766 // If not exists in course and we have a target role mapping
767 if (!$exists && $roleid) {
768 $data->roleid = $roleid;
769 $enrol = enrol_get_plugin($data->enrol);
770 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
771 $newitemid = $enrol->add_instance($courserec, array($data));
772
773 // Already exists, user it for enrolments
774 } else {
775 $newitemid = $exists;
776 }
777
778 // Not installed and enabled, map to 0
779 } else {
780 $newitemid = 0;
781 }
782 // Perform the simple mapping and done
783 $this->set_mapping('enrol', $oldid, $newitemid);
784 }
785
786 public function process_enrolment($data) {
787 global $DB;
788
789 $data = (object)$data;
790
791 // Process only if parent instance have been mapped
792 if ($enrolid = $this->get_new_parentid('enrol')) {
793 // And only if user is a mapped one
794 if ($userid = $this->get_mappingid('user', $data->userid)) {
795 // TODO: Surely need to use API (enrol_user) here, instead of the current low-level impl
796 // TODO: Note enrol_user() sticks to $USER->id (need to add userid param)
797 $enrolment = new stdclass();
798 $enrolment->enrolid = $enrolid;
799 $enrolment->userid = $userid;
800 if (!$DB->record_exists('user_enrolments', (array)$enrolment)) {
801 $enrolment->status = $data->status;
802 $enrolment->timestart = $data->timestart;
803 $enrolment->timeend = $data->timeend;
804 $enrolment->modifierid = $this->task->get_userid();
805 $enrolment->timecreated = time();
806 $enrolment->timemodified = 0;
807 $DB->insert_record('user_enrolments', $enrolment);
808 }
809 }
810 }
811 }
812}
21e51c86
EL
813
814
815/**
816 * This structure steps restores the filters and their configs
817 */
818class restore_filters_structure_step extends restore_structure_step {
819
820 protected function define_structure() {
821
822 $paths = array();
823
824 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
825 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
826
827 return $paths;
828 }
829
830 public function process_active($data) {
831
832 $data = (object)$data;
833
834 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
835 return;
836 }
837 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
838 }
839
840 public function process_config($data) {
841
842 $data = (object)$data;
843
844 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
845 return;
846 }
847 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
848 }
849}
850
851
852/**
853 * This structure steps restores the comments
854 * Note: Cannot use the comments API because defaults to USER->id.
855 * That should change allowing to pass $userid
856 */
857class restore_comments_structure_step extends restore_structure_step {
858
859 protected function define_structure() {
860
861 $paths = array();
862
863 $paths[] = new restore_path_element('comment', '/comments/comment');
864
865 return $paths;
866 }
867
868 public function process_comment($data) {
869 global $DB;
870
871 $data = (object)$data;
872
873 // First of all, if the comment has some itemid, ask to the task what to map
874 $mapping = false;
21e51c86 875 if ($data->itemid) {
39aa0280
EL
876 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
877 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
21e51c86
EL
878 }
879 // Only restore the comment if has no mapping OR we have found the matching mapping
39aa0280 880 if (!$mapping || $data->itemid) {
b8e455a7
EL
881 // Only if user mapping and context
882 $data->userid = $this->get_mappingid('user', $data->userid);
883 if ($data->userid && $this->task->get_contextid()) {
21e51c86 884 $data->contextid = $this->task->get_contextid();
b8e455a7
EL
885 // Only if there is another comment with same context/user/timecreated
886 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
887 if (!$DB->record_exists('comments', $params)) {
888 $DB->insert_record('comments', $data);
889 }
890 }
891 }
892 }
893}
894
9a1cfcbc
EL
895/**
896 * This structure step restores the grade items associated with one activity
897 * All the grade items are made child of the "course" grade item but the original
898 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
899 * the complete gradebook (categories and calculations), that information is
900 * available there
901 */
902class restore_activity_grades_structure_step extends restore_structure_step {
903
904 protected function define_structure() {
905
906 $paths = array();
907 $userinfo = $this->get_setting_value('userinfo');
908
909 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
910 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
911 if ($userinfo) {
912 $paths[] = new restore_path_element('grade_grade',
913 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
914 }
915 return $paths;
916 }
917
918 protected function process_grade_item($data) {
919
920 $data = (object)($data);
921 $oldid = $data->id; // We'll need these later
922 $oldparentid = $data->categoryid;
923
924 // make sure top course category exists, all grade items will be associated
925 // to it. Later, if restoring the whole gradebook, categories will be introduced
926 $coursecat = grade_category::fetch_course_category($this->get_courseid());
927 $coursecatid = $coursecat->id; // Get the categoryid to be used
928
929 unset($data->id);
930 $data->categoryid = $coursecatid;
931 $data->courseid = $this->get_courseid();
932 $data->iteminstance = $this->task->get_activityid();
933 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
934 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
935 // so the best is to keep the ones already in the gradebook
936 // Potential problem: duplicates if same items are restored more than once. :-(
937 // This needs to be fixed in some way (outcomes & activities with multiple items)
938 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
939 // In any case, verify always for uniqueness
940 $data->idnumber = grade_verify_idnumber($idnumber, $this->get_courseid()) ? $data->idnumber : null;
941 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
942 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
943 $data->timecreated = $this->apply_date_offset($data->timecreated);
944 $data->timemodified = $this->apply_date_offset($data->timemodified);
945
946 $gradeitem = new grade_item($data);
947 $gradeitem->insert('restore');
948 $this->set_mapping('grade_item', $oldid, $gradeitem->id, $oldparentid);
949 }
950
951 protected function process_grade_grade($data) {
952 $data = (object)($data);
953
954 unset($data->id);
955 $data->itemid = $this->get_new_parentid('grade_item');
956 $data->userid = $this->get_mappingid('user', $data->userid);
957 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
958 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
959 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
960 $data->overridden = $this->apply_date_offset($data->overridden);
961
962 $grade = new grade_grade($data);
963 $grade->insert('restore');
964 // no need to save any grade_grade mapping
965 }
966
967 /**
968 * process activity grade_letters. Note that, while these are possible,
969 * because grade_letters are contextid based, in proctice, only course
970 * context letters can be defined. So we keep here this method knowing
971 * it won't be executed ever. gradebook restore will restore course letters.
972 */
973 protected function process_grade_letter($data) {
974 global $DB;
975
976 $data = (object)$data;
977
978 $data->contextid = $this->task->get_contextid();
979 $newitemid = $DB->insert_record('grade_letters', $data);
980 // no need to save any grade_letter mapping
981 }
982}
983
b8e455a7
EL
984
985/**
986 * This structure steps restores one instance + positions of one block
987 * Note: Positions corresponding to one existing context are restored
988 * here, but all the ones having unknown contexts are sent to backup_ids
989 * for a later chance to be restored at the end (final task)
990 */
991class restore_block_instance_structure_step extends restore_structure_step {
992
993 protected function define_structure() {
994
995 $paths = array();
996
997 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
998 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
999
1000 return $paths;
1001 }
1002
1003 public function process_block($data) {
1004 global $DB;
1005
1006 $data = (object)$data; // Handy
1007 $oldcontextid = $data->contextid;
1008 $oldid = $data->id;
1009 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1010
1011 // Look for the parent contextid
1012 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1013 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1014 }
1015
1016 // If there is already one block of that type in the parent context
1017 // and the block is not multiple, stop processing
1018 if ($DB->record_exists_sql("SELECT bi.id
1019 FROM {block_instances} bi
1020 JOIN {block} b ON b.name = bi.blockname
1021 WHERE bi.parentcontextid = ?
1022 AND bi.blockname = ?
1023 AND b.multiple = 0", array($data->parentcontextid, $data->blockname))) {
1024 return false;
1025 }
1026
1027 // If there is already one block of that type in the parent context
1028 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
1029 // stop processing
1030 $params = array(
1031 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
1032 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
1033 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
1034 if ($birecs = $DB->get_records('block_instances', $params)) {
1035 foreach($birecs as $birec) {
1036 if ($birec->configdata == $data->configdata) {
1037 return false;
1038 }
1039 }
1040 }
1041
1042 // Set task old contextid, blockid and blockname once we know them
1043 $this->task->set_old_contextid($oldcontextid);
1044 $this->task->set_old_blockid($oldid);
1045 $this->task->set_blockname($data->blockname);
1046
1047 // Let's look for anything within configdata neededing processing
1048 // (nulls and uses of legacy file.php)
1049 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1050 $configdata = (array)unserialize(base64_decode($data->configdata));
1051 foreach ($configdata as $attribute => $value) {
1052 if (in_array($attribute, $attrstotransform)) {
1053 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
1054 }
1055 }
1056 $data->configdata = base64_encode(serialize((object)$configdata));
1057 }
1058
1059 // Create the block instance
1060 $newitemid = $DB->insert_record('block_instances', $data);
1061 // Save the mapping (with restorefiles support)
1062 $this->set_mapping('block_instance', $oldid, $newitemid, true);
1063 // Create the block context
1064 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
1065 // Save the block contexts mapping and sent it to task
1066 $this->set_mapping('context', $oldcontextid, $newcontextid);
1067 $this->task->set_contextid($newcontextid);
1068 $this->task->set_blockid($newitemid);
1069
1070 // Restore block fileareas if declared
1071 $component = 'block_' . $this->task->get_blockname();
1072 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
1073 $this->add_related_files($component, $filearea, null);
1074 }
1075
1076 // Process block positions, creating them or accumulating for final step
1077 foreach($positions as $position) {
1078 $position = (object)$position;
1079 $position->blockinstanceid = $newitemid; // The instance is always the restored one
1080 // If position is for one already mapped (known) contextid
1081 // process it now, creating the position
1082 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
1083 $position->contextid = $newpositionctxid;
1084 // Create the block position
1085 $DB->insert_record('block_positions', $position);
1086
1087 // The position belongs to an unknown context, send it to backup_ids
1088 // to process them as part of the final steps of restore. We send the
1089 // whole $position object there, hence use the low level method.
1090 } else {
1091 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
21e51c86
EL
1092 }
1093 }
1094 }
1095}
394edb7e
EL
1096
1097/**
1098 * Structure step to restore common course_module information
1099 *
1100 * This step will process the module.xml file for one activity, in order to restore
1101 * the corresponding information to the course_modules table, skipping various bits
1102 * of information based on CFG settings (groupings, completion...) in order to fullfill
1103 * all the reqs to be able to create the context to be used by all the rest of steps
1104 * in the activity restore task
1105 */
1106class restore_module_structure_step extends restore_structure_step {
1107
1108 protected function define_structure() {
1109 global $CFG;
1110
1111 $paths = array();
1112
1113 $paths[] = new restore_path_element('module', '/module');
1114 if ($CFG->enableavailability) {
1115 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
1116 }
1117
1118 return $paths;
1119 }
1120
1121 protected function process_module($data) {
1122 global $CFG, $DB;
1123
1124 $data = (object)$data;
1125 $oldid = $data->id;
1126
1127 $data->course = $this->task->get_courseid();
1128 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
aa39be20
EL
1129 // Map section (first try by course_section mapping match. Useful in course and section restores)
1130 $data->section = $this->get_mappingid('course_section', $data->sectionid);
1131 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
1132 $params = array(
1133 'course' => $this->get_courseid(),
1134 'section' => $data->sectionnumber);
1135 $data->section = $DB->get_field('course_sections', 'id', $params);
1136 }
1137 if (!$data->section) { // sectionnumber failed, try to get first section in course
1138 $params = array(
1139 'course' => $this->get_courseid());
1140 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
1141 }
1142 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
1143 $sectionrec = array(
1144 'course' => $this->get_courseid(),
1145 'section' => 0);
1146 $DB->insert_record('course_sections', $sectionrec); // section 0
1147 $sectionrec = array(
1148 'course' => $this->get_courseid(),
1149 'section' => 1);
1150 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
1151 }
394edb7e
EL
1152 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
1153 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
1154 $data->groupmembersonly = 0;
1155 }
1156 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
1157 $data->idnumber = '';
1158 }
1159 if (empty($CFG->enablecompletion) || !$this->get_setting_value('userscompletion')) { // completion
1160 $data->completion = 0;
1161 $data->completiongradeitemnumber = null;
1162 $data->completionview = 0;
1163 $data->completionexpected = 0;
1164 } else {
1165 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
1166 }
1167 if (empty($CFG->enableavailability)) {
1168 $data->availablefrom = 0;
1169 $data->availableuntil = 0;
1170 $data->showavailability = 0;
1171 } else {
1172 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
1173 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
1174 }
1175 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
1176
1177 // course_module record ready, insert it
1178 $newitemid = $DB->insert_record('course_modules', $data);
1179 // save mapping
1180 $this->set_mapping('course_module', $oldid, $newitemid);
1181 // set the new course_module id in the task
1182 $this->task->set_moduleid($newitemid);
1183 // we can now create the context safely
1184 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
1185 // set the new context id in the task
1186 $this->task->set_contextid($ctxid);
1187 // update sequence field in course_section
1188 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
1189 $sequence .= ',' . $newitemid;
1190 } else {
1191 $sequence = $newitemid;
1192 }
1193 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
1194 }
1195
1196
1197 protected function process_availability($data) {
1198 // TODO: Process module availavility records
1199 $data = (object)$data;
1200 }
1201}
1202
1203/**
1204 * Abstract structure step, parent of all the activity structure steps. Used to suuport
1205 * the main <activity ...> tag and process it. Also provides subplugin support for
1206 * activities.
1207 */
1208abstract class restore_activity_structure_step extends restore_structure_step {
1209
91d11057
EL
1210 protected function add_subplugin_structure($subplugintype, $element) {
1211
1212 global $CFG;
1213
1214 // Check the requested subplugintype is a valid one
1215 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
1216 if (!file_exists($subpluginsfile)) {
1217 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
1218 }
1219 include($subpluginsfile);
1220 if (!array_key_exists($subplugintype, $subplugins)) {
1221 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
1222 }
1223 // Get all the restore path elements, looking across all the subplugin dirs
1224 $subpluginsdirs = get_plugin_list($subplugintype);
1225 foreach ($subpluginsdirs as $name => $subpluginsdir) {
1226 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
1227 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
1228 if (file_exists($restorefile)) {
1229 require_once($restorefile);
1230 $restoresubplugin = new $classname($subplugintype, $name, $this);
1231 // Add subplugin paths to the step
1232 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
1233 }
1234 }
1235 }
1236
1237 /**
1238 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
1239 * have the parent task available for wrapping purposes (get course/context....)
1240 */
1241 public function get_task() {
1242 return $this->task;
394edb7e
EL
1243 }
1244
1245 /**
1246 * Adds support for the 'activity' path that is common to all the activities
1247 * and will be processed globally here
1248 */
1249 protected function prepare_activity_structure($paths) {
1250
1251 $paths[] = new restore_path_element('activity', '/activity');
1252
1253 return $paths;
1254 }
1255
1256 /**
1257 * Process the activity path, informing the task about various ids, needed later
1258 */
1259 protected function process_activity($data) {
1260 $data = (object)$data;
1261 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
1262 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
1263 $this->task->set_old_activityid($data->id); // Save old activityid in task
1264 }
1265
1266 /**
1267 * This must be invoked inmediately after creating the "module" activity record (forum, choice...)
1268 * and will adjust the new activity id (the instance) in various places
1269 */
1270 protected function apply_activity_instance($newitemid) {
1271 global $DB;
1272
1273 $this->task->set_activityid($newitemid); // Save activity id in task
1274 // Apply the id to course_sections->instanceid
1275 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
1276 // Do the mapping for modulename, preparing it for files by oldcontext
1277 $modulename = $this->task->get_modulename();
1278 $oldid = $this->task->get_old_activityid();
1279 $this->set_mapping($modulename, $oldid, $newitemid, true);
1280 }
1281}