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