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