MDL-23503 restore without users - fixed two incorrect function calls
[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
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 }
25d3cf44 162 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
482aac65
EL
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 }
25d3cf44 184 if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
482aac65
EL
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);
ba8bead5 361 $data->userid = $userid ? $userid : $this->task->get_userid();
c0440b3f
EL
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);
ba8bead5 421 $data->usermodified = $userid ? $userid : $this->task->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
785d6603
SH
546
547 $fullname = $this->get_setting_value('course_fullname');
548 $shortname = $this->get_setting_value('course_shortname');
b1eaf633 549 $startdate = $this->get_setting_value('course_startdate');
395dae30
EL
550
551 // Calculate final course names, to avoid dupes
552 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
553
554 // Need to change some fields before updating the course record
555 $data->id = $this->get_courseid();
556 $data->fullname = $fullname;
557 $data->shortname= $shortname;
558 $data->idnumber = '';
785d6603
SH
559 // TODO: Set category from the UI, its not a setting just a param
560 $data->category = get_course_category()->id;
395dae30
EL
561 $data->startdate= $this->apply_date_offset($data->startdate);
562 if ($data->defaultgroupingid) {
563 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
564 }
565 if (empty($CFG->enablecompletion) || !$this->get_setting_value('userscompletion')) {
566 $data->enablecompletion = 0;
567 $data->completionstartonenrol = 0;
568 $data->completionnotify = 0;
569 }
570 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
571 if (!array_key_exists($data->lang, $languages)) {
572 $data->lang = '';
573 }
574 $themes = get_list_of_themes(); // Get themes for quick search later
575 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
576 $data->theme = '';
577 }
578
579 // Course record ready, update it
580 $DB->update_record('course', $data);
581
582 // Course tags
583 if (!empty($CFG->usetags) && isset($coursetags)) { // if enabled in server and present in backup
584 $tags = array();
585 foreach ($coursetags as $coursetag) {
586 $coursetag = (object)$coursetag;
587 $tags[] = $coursetag->rawname;
588 }
589 tag_set('course', $this->get_courseid(), $tags);
590 }
591 // Course allowed modules
592 if (!empty($data->restrictmodules) && !empty($coursemodules)) {
593 $available = get_plugin_list('mod');
594 foreach ($coursemodules as $coursemodule) {
595 $mname = $coursemodule['modulename'];
596 if (array_key_exists($mname, $available)) {
597 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
598 $rec = new stdclass();
599 $rec->course = $this->get_courseid();
600 $rec->module = $module->id;
601 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
602 $DB->insert_record('course_allowed_modules', $rec);
603 }
604 }
605 }
606 }
607 }
608 // Role name aliases
609 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
482aac65
EL
610 }
611
395dae30
EL
612 protected function after_execute() {
613 // Add course related files, without itemid to match
614 $this->add_related_files('course', 'summary', null);
615 $this->add_related_files('course', 'legacy', null);
616 }
482aac65 617}
024c288d
EL
618
619
620/*
621 * Structure step that will read the roles.xml file (at course/activity/block levels)
622 * containig all the role_assignments and overrides for that context. If corresponding to
623 * one mapped role, they will be applied to target context. Will observe the role_assignments
624 * setting to decide if ras are restored.
625 * Note: only ras with component == null are restored as far as the any ra with component
626 * is handled by one enrolment plugin, hence it will createt the ras later
627 */
628class restore_ras_and_caps_structure_step extends restore_structure_step {
629
630 protected function define_structure() {
631
632 $paths = array();
633
634 // Observe the role_assignments setting
635 if ($this->get_setting_value('role_assignments')) {
636 $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
637 }
638 $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
639
640 return $paths;
641 }
642
643 public function process_assignment($data) {
644 $data = (object)$data;
645
646 // Check roleid, userid are one of the mapped ones
647 $newroleid = $this->get_mappingid('role', $data->roleid);
648 $newuserid = $this->get_mappingid('user', $data->userid);
649 // If newroleid and newuserid and component is empty assign via API (handles dupes and friends)
650 if ($newroleid && $newuserid && empty($data->component)) {
651 // TODO: role_assign() needs one userid param to be able to specify our restore userid
652 role_assign($newroleid, $newuserid, $this->task->get_contextid());
653 }
654 }
655
656 public function process_override($data) {
657 $data = (object)$data;
658
659 // Check roleid is one of the mapped ones
660 $newroleid = $this->get_mappingid('role', $data->roleid);
661 // If newroleid is valid assign it via API (it handles dupes and so on)
662 if ($newroleid) {
663 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
664 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
665 }
666 }
667}
668
669/**
670 * This structure steps restores the enrol plugins and their underlying
671 * enrolments, performing all the mappings and/or movements required
672 */
673class restore_enrolments_structure_step extends restore_structure_step {
674
675 protected function define_structure() {
676
677 $paths = array();
678
679 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
680 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
681
682 return $paths;
683 }
684
685 public function process_enrol($data) {
686 global $DB;
687
688 $data = (object)$data;
689 $oldid = $data->id; // We'll need this later
690
691 // TODO: Just one quick process of manual enrol_plugin. Add the rest (complex ones) and fix this
692 if ($data->enrol !== 'manual') {
693 debugging("Skipping '{$data->enrol}' enrolment plugin. Must be implemented", DEBUG_DEVELOPER);
694 return;
695 }
696
697 // Perform various checks to decide what to do with the enrol plugin
698 $installed = array_key_exists($data->enrol, enrol_get_plugins(false));
699 $enabled = enrol_is_enabled($data->enrol);
700 $exists = 0;
701 $roleid = $this->get_mappingid('role', $data->roleid);
702 if ($rec = $DB->get_record('enrol', array('courseid' => $this->get_courseid(), 'enrol' => $data->enrol))) {
703 $exists = $rec->id;
704 }
705 // If installed and enabled, continue processing
706 if ($installed && $enabled) {
707 // If not exists in course and we have a target role mapping
708 if (!$exists && $roleid) {
709 $data->roleid = $roleid;
710 $enrol = enrol_get_plugin($data->enrol);
711 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
712 $newitemid = $enrol->add_instance($courserec, array($data));
713
714 // Already exists, user it for enrolments
715 } else {
716 $newitemid = $exists;
717 }
718
719 // Not installed and enabled, map to 0
720 } else {
721 $newitemid = 0;
722 }
723 // Perform the simple mapping and done
724 $this->set_mapping('enrol', $oldid, $newitemid);
725 }
726
727 public function process_enrolment($data) {
728 global $DB;
729
730 $data = (object)$data;
731
732 // Process only if parent instance have been mapped
733 if ($enrolid = $this->get_new_parentid('enrol')) {
734 // And only if user is a mapped one
735 if ($userid = $this->get_mappingid('user', $data->userid)) {
736 // TODO: Surely need to use API (enrol_user) here, instead of the current low-level impl
737 // TODO: Note enrol_user() sticks to $USER->id (need to add userid param)
738 $enrolment = new stdclass();
739 $enrolment->enrolid = $enrolid;
740 $enrolment->userid = $userid;
741 if (!$DB->record_exists('user_enrolments', (array)$enrolment)) {
742 $enrolment->status = $data->status;
743 $enrolment->timestart = $data->timestart;
744 $enrolment->timeend = $data->timeend;
745 $enrolment->modifierid = $this->task->get_userid();
746 $enrolment->timecreated = time();
747 $enrolment->timemodified = 0;
748 $DB->insert_record('user_enrolments', $enrolment);
749 }
750 }
751 }
752 }
753}
21e51c86
EL
754
755
756/**
757 * This structure steps restores the filters and their configs
758 */
759class restore_filters_structure_step extends restore_structure_step {
760
761 protected function define_structure() {
762
763 $paths = array();
764
765 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
766 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
767
768 return $paths;
769 }
770
771 public function process_active($data) {
772
773 $data = (object)$data;
774
775 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
776 return;
777 }
778 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
779 }
780
781 public function process_config($data) {
782
783 $data = (object)$data;
784
785 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
786 return;
787 }
788 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
789 }
790}
791
792
793/**
794 * This structure steps restores the comments
795 * Note: Cannot use the comments API because defaults to USER->id.
796 * That should change allowing to pass $userid
797 */
798class restore_comments_structure_step extends restore_structure_step {
799
800 protected function define_structure() {
801
802 $paths = array();
803
804 $paths[] = new restore_path_element('comment', '/comments/comment');
805
806 return $paths;
807 }
808
809 public function process_comment($data) {
810 global $DB;
811
812 $data = (object)$data;
813
814 // First of all, if the comment has some itemid, ask to the task what to map
815 $mapping = false;
816 $newitemid = 0;
817 if ($data->itemid) {
818 $mapping = $this->task->get_comment_mapping_itemname();
819 $newitemid = $this->get_mappingid($mapping, $data->itemid);
820 }
821 // Only restore the comment if has no mapping OR we have found the matching mapping
822 if (!$mapping || $newitemid) {
823 if ($data->userid = $this->get_mappingid('user', $data->userid)) {
824 $data->contextid = $this->task->get_contextid();
825 $DB->insert_record('comments', $data);
826 }
827 }
828 }
829}