MDL-21432 backup - restore sections
[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
482aac65
EL
62 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
63 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
64 backup_helper::delete_backup_dir($this->get_restoreid()); // Empty backup dir
65 }
66 }
67}
68
69/*
70 * Execution step that, *conditionally* (if there isn't preloaded information)
71 * will load the inforef files for all the included course/section/activity tasks
72 * to backup_temp_ids. They will be stored with "xxxxref" as itemname
73 */
74class restore_load_included_inforef_records extends restore_execution_step {
75
76 protected function define_execution() {
77
78 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
79 return;
80 }
81
82 // Get all the included inforef files
83 $files = restore_dbops::get_needed_inforef_files($this->get_restoreid());
84 foreach ($files as $file) {
85 restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $file); // Load each inforef file to temp_ids
86 }
87 }
88}
89
76cfb124 90/*
b8bb45b0 91 * Execution step that will load all the needed files into backup_files_temp
76cfb124
EL
92 * - info: contains the whole original object (times, names...)
93 * (all them being original ids as loaded from xml)
94 */
95class restore_load_included_files extends restore_structure_step {
96
97 protected function define_structure() {
98
99 $file = new restore_path_element('file', '/files/file');
100
101 return array($file);
102 }
103
104 // Processing functions go here
105 public function process_file($data) {
106
107 $data = (object)$data; // handy
108
76cfb124
EL
109 // load it if needed:
110 // - it it is one of the annotated inforef files (course/section/activity/block)
71a50b13 111 // - it is one "user", "group", "grouping" or "grade" component file (that aren't sent to inforef ever)
b8bb45b0 112 $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
71a50b13
EL
113 $iscomponent = ($data->component == 'user' || $data->component == 'group' ||
114 $data->component == 'grouping' || $data->component == 'grade');
76cfb124 115 if ($isfileref || $iscomponent) {
b8bb45b0 116 restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
76cfb124
EL
117 }
118 }
119}
120
71a50b13
EL
121/**
122 * Execution step that, *conditionally* (if there isn't preloaded information),
123 * will load all the needed roles to backup_temp_ids. They will be stored with
124 * "role" itemname. Also it will perform one automatic mapping to roles existing
125 * in the target site, based in permissions of the user performing the restore,
126 * archetypes and other bits. At the end, each original role will have its associated
127 * target role or 0 if it's going to be skipped. Note we wrap everything over one
128 * restore_dbops method, as far as the same stuff is going to be also executed
129 * by restore prechecks
130 */
131class restore_load_and_map_roles extends restore_execution_step {
132
133 protected function define_execution() {
8d4e41f4 134 if ($this->task->get_preloaded_information()) { // if info is already preloaded
71a50b13
EL
135 return;
136 }
137
138 $file = $this->get_basepath() . '/roles.xml';
139 // Load needed toles to temp_ids
140 restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
8d4e41f4 141
71a50b13 142 // Process roles, mapping/skipping. Any error throws exception
8d4e41f4
EL
143 // Note we pass controller's info because it can contain role mapping information
144 // about manual mappings performed by UI
145 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
146 }
147}
148
482aac65
EL
149/**
150 * Execution step that, *conditionally* (if there isn't preloaded information
151 * and users have been selected in settings, will load all the needed users
152 * to backup_temp_ids. They will be stored with "user" itemname and with
76cfb124 153 * their original contextid as paremitemid
482aac65
EL
154 */
155class restore_load_included_users extends restore_execution_step {
156
157 protected function define_execution() {
158
159 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
160 return;
161 }
162 if (!$this->task->get_setting('users')) { // No userinfo being restored, nothing to do
163 return;
164 }
165 $file = $this->get_basepath() . '/users.xml';
166 restore_dbops::load_users_to_tempids($this->get_restoreid(), $file); // Load needed users to temp_ids
167 }
168}
169
170/**
171 * Execution step that, *conditionally* (if there isn't preloaded information
172 * and users have been selected in settings, will process all the needed users
173 * in order to decide and perform any action with them (create / map / error)
174 * Note: Any error will cause exception, as far as this is the same processing
175 * than the one into restore prechecks (that should have stopped process earlier)
176 */
76cfb124 177class restore_process_included_users extends restore_execution_step {
482aac65
EL
178
179 protected function define_execution() {
180
181 if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
182 return;
183 }
184 if (!$this->task->get_setting('users')) { // No userinfo being restored, nothing to do
185 return;
186 }
187 restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
188 }
189}
190
76cfb124
EL
191/**
192 * Execution step that will create all the needed users as calculated
193 * by @restore_process_included_users (those having newiteind = 0)
194 */
195class restore_create_included_users extends restore_execution_step {
196
197 protected function define_execution() {
198
199 restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->get_setting_value('user_files'));
200 }
201}
202
203/**
204 * Structure step that will create all the needed groups and groupings
205 * by loading them from the groups.xml file performing the required matches.
206 * Note group members only will be added if restoring user info
207 */
208class restore_groups_structure_step extends restore_structure_step {
209
c0440b3f
EL
210 protected function define_structure() {
211
212 $paths = array(); // Add paths here
213
214 $paths[] = new restore_path_element('group', '/groups/group');
215 if ($this->get_setting_value('users')) {
216 $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
217 }
218 $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
219 $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
220
221 return $paths;
222 }
223
224 // Processing functions go here
225 public function process_group($data) {
226 global $DB;
227
228 $data = (object)$data; // handy
229 $data->courseid = $this->get_courseid();
230
231 $oldid = $data->id; // need this saved for later
76cfb124 232
c0440b3f
EL
233 $restorefiles = false; // Only if we end creating the group
234
235 // Search if the group already exists (by name & description) in the target course
236 $description_clause = '';
237 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
238 if (!empty($data->description)) {
239 $description_clause = ' AND ' .
240 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
241 $params['desc'] = $data->description;
242 }
243 if (!$groupdb = $DB->get_record_sql("SELECT *
244 FROM {groups}
245 WHERE courseid = :courseid
246 AND name = :grname $description_clause", $params)) {
247 // group doesn't exist, create
248 $newitemid = $DB->insert_record('groups', $data);
249 $restorefiles = true; // We'll restore the files
250 } else {
251 // group exists, use it
252 $newitemid = $groupdb->id;
253 }
254 // Save the id mapping
255 $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
256 }
257
258 public function process_member($data) {
259 global $DB;
260
261 $data = (object)$data; // handy
262
263 // get parent group->id
264 $data->groupid = $this->get_new_parentid('group');
265
266 // map user newitemid and insert if not member already
267 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
268 if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
269 $DB->insert_record('groups_members', $data);
270 }
271 }
272 }
273
274 public function process_grouping($data) {
71a50b13
EL
275 global $DB;
276
277 $data = (object)$data; // handy
278 $data->courseid = $this->get_courseid();
279
280 $oldid = $data->id; // need this saved for later
281 $restorefiles = false; // Only if we end creating the grouping
282
283 // Search if the grouping already exists (by name & description) in the target course
284 $description_clause = '';
285 $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
286 if (!empty($data->description)) {
287 $description_clause = ' AND ' .
288 $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':desc');
289 $params['desc'] = $data->description;
290 }
291 if (!$groupingdb = $DB->get_record_sql("SELECT *
292 FROM {groupings}
293 WHERE courseid = :courseid
294 AND name = :grname $description_clause", $params)) {
295 // grouping doesn't exist, create
296 $newitemid = $DB->insert_record('groupings', $data);
297 $restorefiles = true; // We'll restore the files
298 } else {
299 // grouping exists, use it
300 $newitemid = $groupingdb->id;
301 }
302 // Save the id mapping
303 $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
c0440b3f
EL
304 }
305
306 public function process_grouping_group($data) {
71a50b13
EL
307 global $DB;
308
309 $data = (object)$data;
310
311 $data->groupingid = $this->get_new_parentid('grouping'); // Use new parentid
312 $data->groupid = $this->get_mappingid('group', $data->groupid); // Get from mappings
313 $DB->insert_record('groupings_groups', $data); // No need to set this mapping (no child info nor files)
c0440b3f
EL
314 }
315
316 protected function after_execute() {
317 // Add group related files, matching with "group" mappings
318 $this->add_related_files('group', 'icon', 'group');
319 $this->add_related_files('group', 'description', 'group');
71a50b13
EL
320 // Add grouping related files, matching with "grouping" mappings
321 $this->add_related_files('grouping', 'description', 'grouping');
c0440b3f
EL
322 }
323
324}
325
326/**
327 * Structure step that will create all the needed scales
328 * by loading them from the scales.xml
c0440b3f
EL
329 */
330class restore_scales_structure_step extends restore_structure_step {
331
332 protected function define_structure() {
333
334 $paths = array(); // Add paths here
335 $paths[] = new restore_path_element('scale', '/scales_definition/scale');
336 return $paths;
337 }
338
339 protected function process_scale($data) {
340 global $DB;
341
342 $data = (object)$data;
343
344 $restorefiles = false; // Only if we end creating the group
345
346 $oldid = $data->id; // need this saved for later
347
348 // Look for scale (by 'scale' both in standard (course=0) and current course
349 // with priority to standard scales (ORDER clause)
350 // scale is not course unique, use get_record_sql to suppress warning
351 // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
352 $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc');
353 $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
354 if (!$scadb = $DB->get_record_sql("SELECT *
355 FROM {scale}
356 WHERE courseid IN (0, :courseid)
357 AND $compare_scale_clause
358 ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
359 // Remap the user if possible, defaut to user performing the restore if not
360 $userid = $this->get_mappingid('user', $data->userid);
361 $data->userid = $userid ? $userid : $this->get_userid();
362 // Remap the course if course scale
363 $data->courseid = $data->courseid ? $this->get_courseid() : 0;
364 // If global scale (course=0), check the user has perms to create it
365 // falling to course scale if not
366 $systemctx = get_context_instance(CONTEXT_SYSTEM);
367 if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $data->userid)) {
368 $data->courseid = $this->get_courseid();
369 }
370 // scale doesn't exist, create
371 $newitemid = $DB->insert_record('scale', $data);
372 $restorefiles = true; // We'll restore the files
373 } else {
374 // scale exists, use it
375 $newitemid = $scadb->id;
376 }
377 // Save the id mapping (with files support at system context)
378 $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
379 }
380
381 protected function after_execute() {
382 // Add scales related files, matching with "scale" mappings
383 $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
384 }
76cfb124
EL
385}
386
c0440b3f 387
c8730ff0
EL
388/**
389 * Structure step that will create all the needed outocomes
390 * by loading them from the outcomes.xml
391 */
392class restore_outcomes_structure_step extends restore_structure_step {
393
394 protected function define_structure() {
395
396 $paths = array(); // Add paths here
397 $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
398 return $paths;
399 }
400
401 protected function process_outcome($data) {
402 global $DB;
403
404 $data = (object)$data;
405
406 $restorefiles = false; // Only if we end creating the group
407
408 $oldid = $data->id; // need this saved for later
409
410 // Look for outcome (by shortname both in standard (courseid=null) and current course
411 // with priority to standard outcomes (ORDER clause)
412 // outcome is not course unique, use get_record_sql to suppress warning
413 $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
414 if (!$outdb = $DB->get_record_sql('SELECT *
415 FROM {grade_outcomes}
416 WHERE shortname = :shortname
417 AND (courseid = :courseid OR courseid IS NULL)
418 ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
419 // Remap the user
420 $userid = $this->get_mappingid('user', $data->usermodified);
421 $data->usermodified = $userid ? $userid : $this->get_userid();
8d4e41f4
EL
422 // Remap the scale
423 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
c8730ff0
EL
424 // Remap the course if course outcome
425 $data->courseid = $data->courseid ? $this->get_courseid() : null;
426 // If global outcome (course=null), check the user has perms to create it
427 // falling to course outcome if not
428 $systemctx = get_context_instance(CONTEXT_SYSTEM);
429 if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $data->userid)) {
430 $data->courseid = $this->get_courseid();
431 }
432 // outcome doesn't exist, create
433 $newitemid = $DB->insert_record('grade_outcomes', $data);
434 $restorefiles = true; // We'll restore the files
435 } else {
436 // scale exists, use it
437 $newitemid = $outdb->id;
438 }
439 // Set the corresponding grade_outcomes_courses record
440 $outcourserec = new stdclass();
441 $outcourserec->courseid = $this->get_courseid();
442 $outcourserec->outcomeid = $newitemid;
443 if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
444 $DB->insert_record('grade_outcomes_courses', $outcourserec);
445 }
446 // Save the id mapping (with files support at system context)
447 $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
448 }
449
450 protected function after_execute() {
451 // Add outcomes related files, matching with "outcome" mappings
452 $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
453 }
454}
455
3223cc95
EL
456/**
457 * Structure step that will read the section.xml creating/updating sections
458 * as needed, rebuilding course cache and other friends
459 */
460class restore_section_structure_step extends restore_structure_step {
c8730ff0 461
3223cc95
EL
462 protected function define_structure() {
463 return array(new restore_path_element('section', '/section'));
464 }
465
466 public function process_section($data) {
467 global $DB;
468 $data = (object)$data;
469 $oldid = $data->id; // We'll need this later
470
471 $restorefiles = false;
472
473 // Look for the section
474 $section = new stdclass();
475 $section->course = $this->get_courseid();
476 $section->section = $data->number;
477 // Section doesn't exist, create it with all the info from backup
478 if (!$secrec = $DB->get_record('course_sections', (array)$section)) {
479 $section->name = $data->name;
480 $section->summary = $data->summary;
481 $section->summaryformat = $data->summaryformat;
482 $section->sequence = '';
483 $section->visible = $data->visible;
484 $newitemid = $DB->insert_record('course_sections', $section);
485 $restorefiles = true;
486
487 // Section exists, update non-empty information
488 } else {
489 $section->id = $secrec->id;
490 if (empty($secrec->name)) {
491 $section->name = $data->name;
492 }
493 if (empty($secrec->summary)) {
494 $section->summary = $data->summary;
495 $section->summaryformat = $data->summaryformat;
496 $restorefiles = true;
497 }
498 $DB->update_record('course_sections', $section);
499 $newitemid = $secrec->id;
500 }
501
502 // Annotate the section mapping, with restorefiles option if needed
503 $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
504
505 // If needed, adjust course->numsections
506 if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
507 if ($numsections < $section->section) {
508 $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
509 }
510 }
511 }
512
513 protected function after_execute() {
514 // Add section related files, with 'course_section' itemid to match
515 $this->add_related_files('course', 'section', 'course_section');
516 }
517}
518
519
520/**
482aac65 521 * Structure step that will read the course.xml file, loading it and performing
395dae30
EL
522 * various actions depending of the site/restore settings. Note that target
523 * course always exist before arriving here so this step will be updating
524 * the course record (never inserting)
482aac65
EL
525 */
526class restore_course_structure_step extends restore_structure_step {
527
528 protected function define_structure() {
529
530 $course = new restore_path_element('course', '/course', true); // Grouped
531 $category = new restore_path_element('category', '/course/category');
532 $tag = new restore_path_element('tag', '/course/tags/tag');
533 $allowed = new restore_path_element('allowed', '/course/allowed_modules/module');
534
535 return array($course, $category, $tag, $allowed);
536 }
537
538 // Processing functions go here
539 public function process_course($data) {
395dae30
EL
540 global $CFG, $DB;
541
542 $data = (object)$data;
543 $coursetags = isset($data->tags['tag']) ? $data->tags['tag'] : array();
544 $coursemodules = isset($data->allowed_modules['module']) ? $data->allowed_modules['module'] : array();
545 $oldid = $data->id; // We'll need this later
546 debugging ('review the these lines of process_course() to change to settings once available', DEBUG_DEVELOPER);
547 // TODO: Get fullname, shortname, startdate and category from settings
548 // $fullname = $this->get_setting_value('course_fullname');
549 // $shortname = $this->get_setting_value('course_shortname');
550 // $category = $this->get_setting_value('course_category');
551 // $startdate = $this->get_setting_value('course_startdate');
552 // TODO: Delete this lines once we are getting the vars above from settings
553 $fullname = $this->task->get_info()->original_course_fullname;
554 $shortname= $this->task->get_info()->original_course_shortname;
555 $startdate= $this->task->get_info()->original_course_startdate;
556 $category = get_course_category()->id;
557
558 // Calculate final course names, to avoid dupes
559 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
560
561 // Need to change some fields before updating the course record
562 $data->id = $this->get_courseid();
563 $data->fullname = $fullname;
564 $data->shortname= $shortname;
565 $data->idnumber = '';
566 $data->category = $category;
567 $data->startdate= $this->apply_date_offset($data->startdate);
568 if ($data->defaultgroupingid) {
569 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
570 }
571 if (empty($CFG->enablecompletion) || !$this->get_setting_value('userscompletion')) {
572 $data->enablecompletion = 0;
573 $data->completionstartonenrol = 0;
574 $data->completionnotify = 0;
575 }
576 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
577 if (!array_key_exists($data->lang, $languages)) {
578 $data->lang = '';
579 }
580 $themes = get_list_of_themes(); // Get themes for quick search later
581 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
582 $data->theme = '';
583 }
584
585 // Course record ready, update it
586 $DB->update_record('course', $data);
587
588 // Course tags
589 if (!empty($CFG->usetags) && isset($coursetags)) { // if enabled in server and present in backup
590 $tags = array();
591 foreach ($coursetags as $coursetag) {
592 $coursetag = (object)$coursetag;
593 $tags[] = $coursetag->rawname;
594 }
595 tag_set('course', $this->get_courseid(), $tags);
596 }
597 // Course allowed modules
598 if (!empty($data->restrictmodules) && !empty($coursemodules)) {
599 $available = get_plugin_list('mod');
600 foreach ($coursemodules as $coursemodule) {
601 $mname = $coursemodule['modulename'];
602 if (array_key_exists($mname, $available)) {
603 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
604 $rec = new stdclass();
605 $rec->course = $this->get_courseid();
606 $rec->module = $module->id;
607 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
608 $DB->insert_record('course_allowed_modules', $rec);
609 }
610 }
611 }
612 }
613 }
614 // Role name aliases
615 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
482aac65
EL
616 }
617
395dae30
EL
618 protected function after_execute() {
619 // Add course related files, without itemid to match
620 $this->add_related_files('course', 'summary', null);
621 $this->add_related_files('course', 'legacy', null);
622 }
482aac65 623}
024c288d
EL
624
625
626/*
627 * Structure step that will read the roles.xml file (at course/activity/block levels)
628 * containig all the role_assignments and overrides for that context. If corresponding to
629 * one mapped role, they will be applied to target context. Will observe the role_assignments
630 * setting to decide if ras are restored.
631 * Note: only ras with component == null are restored as far as the any ra with component
632 * is handled by one enrolment plugin, hence it will createt the ras later
633 */
634class restore_ras_and_caps_structure_step extends restore_structure_step {
635
636 protected function define_structure() {
637
638 $paths = array();
639
640 // Observe the role_assignments setting
641 if ($this->get_setting_value('role_assignments')) {
642 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
643 }
644 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
645
646 return $paths;
647 }
648
649 public function process_assignment($data) {
650 $data = (object)$data;
651
652 // Check roleid, userid are one of the mapped ones
653 $newroleid = $this->get_mappingid('role', $data->roleid);
654 $newuserid = $this->get_mappingid('user', $data->userid);
655 // If newroleid and newuserid and component is empty assign via API (handles dupes and friends)
656 if ($newroleid && $newuserid && empty($data->component)) {
657 // TODO: role_assign() needs one userid param to be able to specify our restore userid
658 role_assign($newroleid, $newuserid, $this->task->get_contextid());
659 }
660 }
661
662 public function process_override($data) {
663 $data = (object)$data;
664
665 // Check roleid is one of the mapped ones
666 $newroleid = $this->get_mappingid('role', $data->roleid);
667 // If newroleid is valid assign it via API (it handles dupes and so on)
668 if ($newroleid) {
669 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
670 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
671 }
672 }
673}
674
675/**
676 * This structure steps restores the enrol plugins and their underlying
677 * enrolments, performing all the mappings and/or movements required
678 */
679class restore_enrolments_structure_step extends restore_structure_step {
680
681 protected function define_structure() {
682
683 $paths = array();
684
685 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
686 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
687
688 return $paths;
689 }
690
691 public function process_enrol($data) {
692 global $DB;
693
694 $data = (object)$data;
695 $oldid = $data->id; // We'll need this later
696
697 // TODO: Just one quick process of manual enrol_plugin. Add the rest (complex ones) and fix this
698 if ($data->enrol !== 'manual') {
699 debugging("Skipping '{$data->enrol}' enrolment plugin. Must be implemented", DEBUG_DEVELOPER);
700 return;
701 }
702
703 // Perform various checks to decide what to do with the enrol plugin
704 $installed = array_key_exists($data->enrol, enrol_get_plugins(false));
705 $enabled = enrol_is_enabled($data->enrol);
706 $exists = 0;
707 $roleid = $this->get_mappingid('role', $data->roleid);
708 if ($rec = $DB->get_record('enrol', array('courseid' => $this->get_courseid(), 'enrol' => $data->enrol))) {
709 $exists = $rec->id;
710 }
711 // If installed and enabled, continue processing
712 if ($installed && $enabled) {
713 // If not exists in course and we have a target role mapping
714 if (!$exists && $roleid) {
715 $data->roleid = $roleid;
716 $enrol = enrol_get_plugin($data->enrol);
717 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
718 $newitemid = $enrol->add_instance($courserec, array($data));
719
720 // Already exists, user it for enrolments
721 } else {
722 $newitemid = $exists;
723 }
724
725 // Not installed and enabled, map to 0
726 } else {
727 $newitemid = 0;
728 }
729 // Perform the simple mapping and done
730 $this->set_mapping('enrol', $oldid, $newitemid);
731 }
732
733 public function process_enrolment($data) {
734 global $DB;
735
736 $data = (object)$data;
737
738 // Process only if parent instance have been mapped
739 if ($enrolid = $this->get_new_parentid('enrol')) {
740 // And only if user is a mapped one
741 if ($userid = $this->get_mappingid('user', $data->userid)) {
742 // TODO: Surely need to use API (enrol_user) here, instead of the current low-level impl
743 // TODO: Note enrol_user() sticks to $USER->id (need to add userid param)
744 $enrolment = new stdclass();
745 $enrolment->enrolid = $enrolid;
746 $enrolment->userid = $userid;
747 if (!$DB->record_exists('user_enrolments', (array)$enrolment)) {
748 $enrolment->status = $data->status;
749 $enrolment->timestart = $data->timestart;
750 $enrolment->timeend = $data->timeend;
751 $enrolment->modifierid = $this->task->get_userid();
752 $enrolment->timecreated = time();
753 $enrolment->timemodified = 0;
754 $DB->insert_record('user_enrolments', $enrolment);
755 }
756 }
757 }
758 }
759}
21e51c86
EL
760
761
762/**
763 * This structure steps restores the filters and their configs
764 */
765class restore_filters_structure_step extends restore_structure_step {
766
767 protected function define_structure() {
768
769 $paths = array();
770
771 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
772 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
773
774 return $paths;
775 }
776
777 public function process_active($data) {
778
779 $data = (object)$data;
780
781 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
782 return;
783 }
784 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
785 }
786
787 public function process_config($data) {
788
789 $data = (object)$data;
790
791 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
792 return;
793 }
794 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
795 }
796}
797
798
799/**
800 * This structure steps restores the comments
801 * Note: Cannot use the comments API because defaults to USER->id.
802 * That should change allowing to pass $userid
803 */
804class restore_comments_structure_step extends restore_structure_step {
805
806 protected function define_structure() {
807
808 $paths = array();
809
810 $paths[] = new restore_path_element('comment', '/comments/comment');
811
812 return $paths;
813 }
814
815 public function process_comment($data) {
816 global $DB;
817
818 $data = (object)$data;
819
820 // First of all, if the comment has some itemid, ask to the task what to map
821 $mapping = false;
822 $newitemid = 0;
823 if ($data->itemid) {
824 $mapping = $this->task->get_comment_mapping_itemname();
825 $newitemid = $this->get_mappingid($mapping, $data->itemid);
826 }
827 // Only restore the comment if has no mapping OR we have found the matching mapping
828 if (!$mapping || $newitemid) {
829 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
830 $data->contextid = $this->task->get_contextid();
831 $DB->insert_record('comments', $data);
832 }
833 }
834 }
835}