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