MDL-21432 backup - restore course/tags/rolenames/files
[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
456
482aac65
EL
457/*
458 * Structure step that will read the course.xml file, loading it and performing
395dae30
EL
459 * various actions depending of the site/restore settings. Note that target
460 * course always exist before arriving here so this step will be updating
461 * the course record (never inserting)
482aac65
EL
462 */
463class restore_course_structure_step extends restore_structure_step {
464
465 protected function define_structure() {
466
467 $course = new restore_path_element('course', '/course', true); // Grouped
468 $category = new restore_path_element('category', '/course/category');
469 $tag = new restore_path_element('tag', '/course/tags/tag');
470 $allowed = new restore_path_element('allowed', '/course/allowed_modules/module');
471
472 return array($course, $category, $tag, $allowed);
473 }
474
475 // Processing functions go here
476 public function process_course($data) {
395dae30
EL
477 global $CFG, $DB;
478
479 $data = (object)$data;
480 $coursetags = isset($data->tags['tag']) ? $data->tags['tag'] : array();
481 $coursemodules = isset($data->allowed_modules['module']) ? $data->allowed_modules['module'] : array();
482 $oldid = $data->id; // We'll need this later
483 debugging ('review the these lines of process_course() to change to settings once available', DEBUG_DEVELOPER);
484 // TODO: Get fullname, shortname, startdate and category from settings
485 // $fullname = $this->get_setting_value('course_fullname');
486 // $shortname = $this->get_setting_value('course_shortname');
487 // $category = $this->get_setting_value('course_category');
488 // $startdate = $this->get_setting_value('course_startdate');
489 // TODO: Delete this lines once we are getting the vars above from settings
490 $fullname = $this->task->get_info()->original_course_fullname;
491 $shortname= $this->task->get_info()->original_course_shortname;
492 $startdate= $this->task->get_info()->original_course_startdate;
493 $category = get_course_category()->id;
494
495 // Calculate final course names, to avoid dupes
496 list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
497
498 // Need to change some fields before updating the course record
499 $data->id = $this->get_courseid();
500 $data->fullname = $fullname;
501 $data->shortname= $shortname;
502 $data->idnumber = '';
503 $data->category = $category;
504 $data->startdate= $this->apply_date_offset($data->startdate);
505 if ($data->defaultgroupingid) {
506 $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
507 }
508 if (empty($CFG->enablecompletion) || !$this->get_setting_value('userscompletion')) {
509 $data->enablecompletion = 0;
510 $data->completionstartonenrol = 0;
511 $data->completionnotify = 0;
512 }
513 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
514 if (!array_key_exists($data->lang, $languages)) {
515 $data->lang = '';
516 }
517 $themes = get_list_of_themes(); // Get themes for quick search later
518 if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
519 $data->theme = '';
520 }
521
522 // Course record ready, update it
523 $DB->update_record('course', $data);
524
525 // Course tags
526 if (!empty($CFG->usetags) && isset($coursetags)) { // if enabled in server and present in backup
527 $tags = array();
528 foreach ($coursetags as $coursetag) {
529 $coursetag = (object)$coursetag;
530 $tags[] = $coursetag->rawname;
531 }
532 tag_set('course', $this->get_courseid(), $tags);
533 }
534 // Course allowed modules
535 if (!empty($data->restrictmodules) && !empty($coursemodules)) {
536 $available = get_plugin_list('mod');
537 foreach ($coursemodules as $coursemodule) {
538 $mname = $coursemodule['modulename'];
539 if (array_key_exists($mname, $available)) {
540 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
541 $rec = new stdclass();
542 $rec->course = $this->get_courseid();
543 $rec->module = $module->id;
544 if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
545 $DB->insert_record('course_allowed_modules', $rec);
546 }
547 }
548 }
549 }
550 }
551 // Role name aliases
552 restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
482aac65
EL
553 }
554
395dae30
EL
555 protected function after_execute() {
556 // Add course related files, without itemid to match
557 $this->add_related_files('course', 'summary', null);
558 $this->add_related_files('course', 'legacy', null);
559 }
482aac65 560}