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