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