MDL-22148 backup - support for manual/self/guest enrolments. Credit goes to Petr.
[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
f2a9be5f
EL
1030 /**
1031 * Assign roles
1032 *
1033 * This has to be called after enrolments processing.
1034 *
1035 * @param mixed $data
1036 * @return void
1037 */
024c288d 1038 public function process_assignment($data) {
28b6ff82
EL
1039 global $DB;
1040
024c288d
EL
1041 $data = (object)$data;
1042
1043 // Check roleid, userid are one of the mapped ones
f2a9be5f
EL
1044 if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
1045 return;
1046 }
1047 if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
1048 return;
1049 }
1050 if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
28b6ff82 1051 // Only assign roles to not deleted users
f2a9be5f
EL
1052 return;
1053 }
1054 if (!$contextid = $this->task->get_contextid()) {
1055 return;
1056 }
1057
1058 if (empty($data->component)) {
1059 // assign standard manual roles
1060 // TODO: role_assign() needs one userid param to be able to specify our restore userid
1061 role_assign($newroleid, $newuserid, $contextid);
1062
1063 } else if ((strpos($data->component, 'enrol_') === 0)) {
1064 // Deal with enrolment roles
1065 if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1066 if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) {
1067 //note: we have to verify component because it might have changed
1068 if ($component === 'enrol_manual') {
1069 // manual is a special case, we do not use components - this owudl happen when converting from other plugin
1070 role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid?
1071 } else {
1072 role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid?
1073 }
1074 }
28b6ff82 1075 }
024c288d
EL
1076 }
1077 }
1078
1079 public function process_override($data) {
1080 $data = (object)$data;
1081
1082 // Check roleid is one of the mapped ones
1083 $newroleid = $this->get_mappingid('role', $data->roleid);
b8e455a7
EL
1084 // If newroleid and context are valid assign it via API (it handles dupes and so on)
1085 if ($newroleid && $this->task->get_contextid()) {
024c288d 1086 // TODO: assign_capability() needs one userid param to be able to specify our restore userid
b8e455a7 1087 // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ???
024c288d
EL
1088 assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
1089 }
1090 }
1091}
1092
1093/**
1094 * This structure steps restores the enrol plugins and their underlying
1095 * enrolments, performing all the mappings and/or movements required
1096 */
1097class restore_enrolments_structure_step extends restore_structure_step {
1098
1099 protected function define_structure() {
1100
1101 $paths = array();
1102
1103 $paths[] = new restore_path_element('enrol', '/enrolments/enrols/enrol');
1104 $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
1105
1106 return $paths;
1107 }
1108
f2a9be5f
EL
1109 /**
1110 * Create enrolment instances.
1111 *
1112 * This has to be called after creation of roles
1113 * and before adding of role assignments.
1114 *
1115 * @param mixed $data
1116 * @return void
1117 */
024c288d
EL
1118 public function process_enrol($data) {
1119 global $DB;
1120
1121 $data = (object)$data;
1122 $oldid = $data->id; // We'll need this later
1123
f2a9be5f
EL
1124 $restoretype = plugin_supports('enrol', $data->enrol, ENROL_RESTORE_TYPE, null);
1125
1126 if ($restoretype !== ENROL_RESTORE_EXACT and $restoretype !== ENROL_RESTORE_NOUSERS) {
1127 // TODO: add complex restore support via custom class
1128 debugging("Skipping '{$data->enrol}' enrolment plugin. Will be implemented before 2.0 release", DEBUG_DEVELOPER);
1129 $this->set_mapping('enrol', $oldid, 0);
024c288d
EL
1130 return;
1131 }
1132
1133 // Perform various checks to decide what to do with the enrol plugin
f2a9be5f
EL
1134 if (!array_key_exists($data->enrol, enrol_get_plugins(false))) {
1135 // TODO: decide if we want to switch to manual enrol - we need UI for this
1136 debugging("Enrol plugin data can not be restored because it is not installed");
1137 $this->set_mapping('enrol', $oldid, 0);
1138 return;
1139
024c288d 1140 }
f2a9be5f
EL
1141 if (!enrol_is_enabled($data->enrol)) {
1142 // TODO: decide if we want to switch to manual enrol - we need UI for this
1143 debugging("Enrol plugin data can not be restored because it is not enabled");
1144 $this->set_mapping('enrol', $oldid, 0);
1145 return;
1146 }
1147
1148 // map standard fields - plugin has to process custom fields from own restore class
1149 $data->roleid = $this->get_mappingid('role', $data->roleid);
1150 //TODO: should we move the enrol start and end date here?
1151
1152 // always add instance, if the course does not support multiple instances it just returns NULL
1153 $enrol = enrol_get_plugin($data->enrol);
1154 $courserec = $DB->get_record('course', array('id' => $this->get_courseid())); // Requires object, uses only id!!
1155 if ($newitemid = $enrol->add_instance($courserec, (array)$data)) {
1156 // ok
1157 } else {
1158 if ($instances = $DB->get_records('enrol', array('courseid'=>$courserec->id, 'enrol'=>$data->enrol))) {
1159 // most probably plugin that supports only one instance
1160 $newitemid = key($instances);
024c288d 1161 } else {
f2a9be5f
EL
1162 debugging('Can not create new enrol instance or reuse existing');
1163 $newitemid = 0;
024c288d 1164 }
f2a9be5f 1165 }
024c288d 1166
f2a9be5f
EL
1167 if ($restoretype === ENROL_RESTORE_NOUSERS) {
1168 // plugin requests to prevent restore of any users
024c288d
EL
1169 $newitemid = 0;
1170 }
f2a9be5f 1171
024c288d
EL
1172 $this->set_mapping('enrol', $oldid, $newitemid);
1173 }
1174
f2a9be5f
EL
1175 /**
1176 * Create user enrolments
1177 *
1178 * This has to be called after creation of enrolment instances
1179 * and before adding of role assignments.
1180 *
1181 * @param mixed $data
1182 * @return void
1183 */
024c288d
EL
1184 public function process_enrolment($data) {
1185 global $DB;
1186
1187 $data = (object)$data;
1188
1189 // Process only if parent instance have been mapped
1190 if ($enrolid = $this->get_new_parentid('enrol')) {
f2a9be5f
EL
1191 if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1192 // And only if user is a mapped one
1193 if ($userid = $this->get_mappingid('user', $data->userid)) {
1194 $enrol = enrol_get_plugin($instance->enrol);
1195 //TODO: do we need specify modifierid?
1196 $enrol->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
1197 //note: roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing above
024c288d
EL
1198 }
1199 }
1200 }
1201 }
1202}
21e51c86
EL
1203
1204
1205/**
1206 * This structure steps restores the filters and their configs
1207 */
1208class restore_filters_structure_step extends restore_structure_step {
1209
1210 protected function define_structure() {
1211
1212 $paths = array();
1213
1214 $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
1215 $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
1216
1217 return $paths;
1218 }
1219
1220 public function process_active($data) {
1221
1222 $data = (object)$data;
1223
1224 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1225 return;
1226 }
1227 filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
1228 }
1229
1230 public function process_config($data) {
1231
1232 $data = (object)$data;
1233
1234 if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
1235 return;
1236 }
1237 filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
1238 }
1239}
1240
1241
1242/**
1243 * This structure steps restores the comments
1244 * Note: Cannot use the comments API because defaults to USER->id.
1245 * That should change allowing to pass $userid
1246 */
1247class restore_comments_structure_step extends restore_structure_step {
1248
1249 protected function define_structure() {
1250
1251 $paths = array();
1252
1253 $paths[] = new restore_path_element('comment', '/comments/comment');
1254
1255 return $paths;
1256 }
1257
1258 public function process_comment($data) {
1259 global $DB;
1260
1261 $data = (object)$data;
1262
1263 // First of all, if the comment has some itemid, ask to the task what to map
1264 $mapping = false;
21e51c86 1265 if ($data->itemid) {
39aa0280
EL
1266 $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
1267 $data->itemid = $this->get_mappingid($mapping, $data->itemid);
21e51c86
EL
1268 }
1269 // Only restore the comment if has no mapping OR we have found the matching mapping
39aa0280 1270 if (!$mapping || $data->itemid) {
b8e455a7
EL
1271 // Only if user mapping and context
1272 $data->userid = $this->get_mappingid('user', $data->userid);
1273 if ($data->userid && $this->task->get_contextid()) {
21e51c86 1274 $data->contextid = $this->task->get_contextid();
b8e455a7
EL
1275 // Only if there is another comment with same context/user/timecreated
1276 $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
1277 if (!$DB->record_exists('comments', $params)) {
1278 $DB->insert_record('comments', $data);
1279 }
1280 }
1281 }
1282 }
1283}
1284
bd39b6f2
SH
1285class restore_course_completion_structure_step extends restore_structure_step {
1286
1287 /**
1288 * Conditionally decide if this step should be executed.
1289 *
1290 * This function checks parameters that are not immediate settings to ensure
1291 * that the enviroment is suitable for the restore of course completion info.
1292 *
1293 * This function checks the following four parameters:
1294 *
1295 * 1. Course completion is enabled on the site
1296 * 2. The backup includes course completion information
1297 * 3. All modules are restorable
1298 * 4. All modules are marked for restore.
1299 *
1300 * @return bool True is safe to execute, false otherwise
1301 */
1302 protected function execute_condition() {
1303 global $CFG;
1304
1305 // First check course completion is enabled on this site
1306 if (empty($CFG->enablecompletion)) {
1307 // Disabled, don't restore course completion
1308 return false;
1309 }
1310
1311 // Check it is included in the backup
1312 $fullpath = $this->task->get_taskbasepath();
1313 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1314 if (!file_exists($fullpath)) {
1315 // Not found, can't restore course completion
1316 return false;
1317 }
1318
1319 // Check we are able to restore all backed up modules
1320 if ($this->task->is_missing_modules()) {
1321 return false;
1322 }
1323
1324 // Finally check all modules within the backup are being restored.
1325 if ($this->task->is_excluding_activities()) {
1326 return false;
1327 }
1328
1329 return true;
1330 }
1331
1332 /**
1333 * Define the course completion structure
1334 *
1335 * @return array Array of restore_path_element
1336 */
1337 protected function define_structure() {
1338
1339 // To know if we are including user completion info
1340 $userinfo = $this->get_setting_value('userscompletion');
1341
1342 $paths = array();
1343 $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
1344 $paths[] = new restore_path_element('course_completion_notify', '/course_completion/course_completion_notify');
1345 $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
1346
1347 if ($userinfo) {
1348 $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
1349 $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
1350 }
1351
1352 return $paths;
1353
1354 }
1355
1356 /**
1357 * Process course completion criteria
1358 *
1359 * @global moodle_database $DB
1360 * @param stdClass $data
1361 */
1362 public function process_course_completion_criteria($data) {
1363 global $DB;
1364
1365 $data = (object)$data;
1366 $data->course = $this->get_courseid();
1367
1368 // Apply the date offset to the time end field
1369 $data->timeend = $this->apply_date_offset($data->timeend);
1370
1371 // Map the role from the criteria
1372 if (!empty($data->role)) {
1373 $data->role = $this->get_mappingid('role', $data->role);
1374 }
1375
aa548318
SH
1376 $skipcriteria = false;
1377
bd39b6f2
SH
1378 // If the completion criteria is for a module we need to map the module instance
1379 // to the new module id.
1380 if (!empty($data->moduleinstance) && !empty($data->module)) {
1381 $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
aa548318
SH
1382 if (empty($data->moduleinstance)) {
1383 $skipcriteria = true;
1384 }
bd39b6f2
SH
1385 } else {
1386 $data->module = null;
1387 $data->moduleinstance = null;
1388 }
1389
1390 // We backup the course shortname rather than the ID so that we can match back to the course
bd39b6f2
SH
1391 if (!empty($data->courseinstanceshortname)) {
1392 $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
1393 if (!$courseinstanceid) {
1394 $skipcriteria = true;
1395 }
1396 } else {
1397 $courseinstanceid = null;
1398 }
1399 $data->courseinstance = $courseinstanceid;
1400
1401 if (!$skipcriteria) {
1402 $params = array(
1403 'course' => $data->course,
1404 'criteriatype' => $data->criteriatype,
1405 'enrolperiod' => $data->enrolperiod,
1406 'courseinstance' => $data->courseinstance,
1407 'module' => $data->module,
1408 'moduleinstance' => $data->moduleinstance,
1409 'timeend' => $data->timeend,
1410 'gradepass' => $data->gradepass,
1411 'role' => $data->role
1412 );
1413 $newid = $DB->insert_record('course_completion_criteria', $params);
1414 $this->set_mapping('course_completion_criteria', $data->id, $newid);
1415 }
1416 }
1417
1418 /**
1419 * Processes course compltion criteria complete records
1420 *
1421 * @global moodle_database $DB
1422 * @param stdClass $data
1423 */
1424 public function process_course_completion_crit_compl($data) {
1425 global $DB;
1426
1427 $data = (object)$data;
1428
1429 // This may be empty if criteria could not be restored
1430 $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
034ef761 1431
bd39b6f2
SH
1432 $data->course = $this->get_courseid();
1433 $data->userid = $this->get_mappingid('user', $data->userid);
1434
1435 if (!empty($data->criteriaid) && !empty($data->userid)) {
1436 $params = array(
1437 'userid' => $data->userid,
1438 'course' => $data->course,
1439 'criteriaid' => $data->criteriaid,
1440 'timecompleted' => $this->apply_date_offset($data->timecompleted)
1441 );
1442 if (isset($data->gradefinal)) {
1443 $params['gradefinal'] = $data->gradefinal;
1444 }
1445 if (isset($data->unenroled)) {
1446 $params['unenroled'] = $data->unenroled;
1447 }
1448 if (isset($data->deleted)) {
1449 $params['deleted'] = $data->deleted;
1450 }
1451 $DB->insert_record('course_completion_crit_compl', $params);
1452 }
1453 }
1454
1455 /**
1456 * Process course completions
1457 *
1458 * @global moodle_database $DB
1459 * @param stdClass $data
1460 */
1461 public function process_course_completions($data) {
1462 global $DB;
1463
1464 $data = (object)$data;
1465
1466 $data->course = $this->get_courseid();
1467 $data->userid = $this->get_mappingid('user', $data->userid);
1468
1469 if (!empty($data->userid)) {
1470 $params = array(
1471 'userid' => $data->userid,
1472 'course' => $data->course,
1473 'deleted' => $data->deleted,
1474 'timenotified' => $this->apply_date_offset($data->timenotified),
1475 'timeenrolled' => $this->apply_date_offset($data->timeenrolled),
1476 'timestarted' => $this->apply_date_offset($data->timestarted),
1477 'timecompleted' => $this->apply_date_offset($data->timecompleted),
1478 'reaggregate' => $data->reaggregate
1479 );
1480 $DB->insert_record('course_completions', $params);
1481 }
1482 }
1483
1484 /**
1485 * Process course completion notification records.
1486 *
1487 * Note: As of Moodle 2.0 this table is not being used however it has been
1488 * left in in the hopes that one day the functionality there will be completed
1489 *
1490 * @global moodle_database $DB
1491 * @param stdClass $data
1492 */
1493 public function process_course_completion_notify($data) {
1494 global $DB;
1495
1496 $data = (object)$data;
1497
1498 $data->course = $this->get_courseid();
1499 if (!empty($data->role)) {
1500 $data->role = $this->get_mappingid('role', $data->role);
1501 }
1502
1503 $params = array(
1504 'course' => $data->course,
1505 'role' => $data->role,
1506 'message' => $data->message,
1507 'timesent' => $this->apply_date_offset($data->timesent),
1508 );
1509 $DB->insert_record('course_completion_notify', $params);
1510 }
1511
1512 /**
1513 * Process course completion aggregate methods
1514 *
1515 * @global moodle_database $DB
1516 * @param stdClass $data
1517 */
1518 public function process_course_completion_aggr_methd($data) {
1519 global $DB;
1520
1521 $data = (object)$data;
1522
1523 $data->course = $this->get_courseid();
1524
1525 $params = array(
1526 'course' => $data->course,
1527 'criteriatype' => $data->criteriatype,
1528 'method' => $data->method,
1529 'value' => $data->value,
1530 );
1531 $DB->insert_record('course_completion_aggr_methd', $params);
1532 }
1533
1534}
1535
9a1cfcbc
EL
1536/**
1537 * This structure step restores the grade items associated with one activity
1538 * All the grade items are made child of the "course" grade item but the original
1539 * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
1540 * the complete gradebook (categories and calculations), that information is
1541 * available there
1542 */
1543class restore_activity_grades_structure_step extends restore_structure_step {
1544
1545 protected function define_structure() {
1546
1547 $paths = array();
1548 $userinfo = $this->get_setting_value('userinfo');
1549
1550 $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
1551 $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
1552 if ($userinfo) {
1553 $paths[] = new restore_path_element('grade_grade',
1554 '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
1555 }
1556 return $paths;
1557 }
1558
1559 protected function process_grade_item($data) {
1560
1561 $data = (object)($data);
1562 $oldid = $data->id; // We'll need these later
1563 $oldparentid = $data->categoryid;
1564
1565 // make sure top course category exists, all grade items will be associated
1566 // to it. Later, if restoring the whole gradebook, categories will be introduced
1567 $coursecat = grade_category::fetch_course_category($this->get_courseid());
1568 $coursecatid = $coursecat->id; // Get the categoryid to be used
1569
1570 unset($data->id);
1571 $data->categoryid = $coursecatid;
1572 $data->courseid = $this->get_courseid();
1573 $data->iteminstance = $this->task->get_activityid();
1574 // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
1575 // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
1576 // so the best is to keep the ones already in the gradebook
1577 // Potential problem: duplicates if same items are restored more than once. :-(
1578 // This needs to be fixed in some way (outcomes & activities with multiple items)
1579 // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
1580 // In any case, verify always for uniqueness
a789ac6f 1581 $data->idnumber = grade_verify_idnumber($data->idnumber, $this->get_courseid()) ? $data->idnumber : null;
9a1cfcbc
EL
1582 $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1583 $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid);
1584 $data->timecreated = $this->apply_date_offset($data->timecreated);
1585 $data->timemodified = $this->apply_date_offset($data->timemodified);
1586
1587 $gradeitem = new grade_item($data);
1588 $gradeitem->insert('restore');
4d787d8a
AD
1589
1590 //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
1591 $gradeitem->sortorder = $data->sortorder;
1592 $gradeitem->update('restore');
1593
dc362c44
EL
1594 // Set mapping, saving the original category id into parentitemid
1595 // gradebook restore (final task) will need it to reorganise items
1596 $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
9a1cfcbc
EL
1597 }
1598
1599 protected function process_grade_grade($data) {
1600 $data = (object)($data);
1601
1602 unset($data->id);
1603 $data->itemid = $this->get_new_parentid('grade_item');
1604 $data->userid = $this->get_mappingid('user', $data->userid);
1605 $data->usermodified = $this->get_mappingid('user', $data->usermodified);
1606 $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
1607 // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled?
1608 $data->overridden = $this->apply_date_offset($data->overridden);
1609
1610 $grade = new grade_grade($data);
1611 $grade->insert('restore');
1612 // no need to save any grade_grade mapping
1613 }
1614
1615 /**
1616 * process activity grade_letters. Note that, while these are possible,
1617 * because grade_letters are contextid based, in proctice, only course
1618 * context letters can be defined. So we keep here this method knowing
1619 * it won't be executed ever. gradebook restore will restore course letters.
1620 */
1621 protected function process_grade_letter($data) {
1622 global $DB;
1623
1624 $data = (object)$data;
1625
1626 $data->contextid = $this->task->get_contextid();
1627 $newitemid = $DB->insert_record('grade_letters', $data);
1628 // no need to save any grade_letter mapping
1629 }
1630}
1631
b8e455a7
EL
1632
1633/**
1634 * This structure steps restores one instance + positions of one block
1635 * Note: Positions corresponding to one existing context are restored
1636 * here, but all the ones having unknown contexts are sent to backup_ids
1637 * for a later chance to be restored at the end (final task)
1638 */
1639class restore_block_instance_structure_step extends restore_structure_step {
1640
1641 protected function define_structure() {
1642
1643 $paths = array();
1644
1645 $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
1646 $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
1647
1648 return $paths;
1649 }
1650
1651 public function process_block($data) {
0f8941e2 1652 global $DB, $CFG;
b8e455a7
EL
1653
1654 $data = (object)$data; // Handy
1655 $oldcontextid = $data->contextid;
1656 $oldid = $data->id;
1657 $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
1658
1659 // Look for the parent contextid
1660 if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
1661 throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
1662 }
1663
767cb7f0 1664 // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
b8e455a7
EL
1665 // If there is already one block of that type in the parent context
1666 // and the block is not multiple, stop processing
767cb7f0
EL
1667 // Use blockslib loader / method executor
1668 if (!block_method_result($data->blockname, 'instance_allow_multiple')) {
0f8941e2
EL
1669 if ($DB->record_exists_sql("SELECT bi.id
1670 FROM {block_instances} bi
1671 JOIN {block} b ON b.name = bi.blockname
1672 WHERE bi.parentcontextid = ?
1673 AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
1674 return false;
1675 }
b8e455a7
EL
1676 }
1677
1678 // If there is already one block of that type in the parent context
1679 // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
1680 // stop processing
1681 $params = array(
1682 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
1683 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
1684 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
1685 if ($birecs = $DB->get_records('block_instances', $params)) {
1686 foreach($birecs as $birec) {
1687 if ($birec->configdata == $data->configdata) {
1688 return false;
1689 }
1690 }
1691 }
1692
1693 // Set task old contextid, blockid and blockname once we know them
1694 $this->task->set_old_contextid($oldcontextid);
1695 $this->task->set_old_blockid($oldid);
1696 $this->task->set_blockname($data->blockname);
1697
1698 // Let's look for anything within configdata neededing processing
1699 // (nulls and uses of legacy file.php)
1700 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1701 $configdata = (array)unserialize(base64_decode($data->configdata));
1702 foreach ($configdata as $attribute => $value) {
1703 if (in_array($attribute, $attrstotransform)) {
1704 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
1705 }
1706 }
1707 $data->configdata = base64_encode(serialize((object)$configdata));
1708 }
1709
1710 // Create the block instance
1711 $newitemid = $DB->insert_record('block_instances', $data);
1712 // Save the mapping (with restorefiles support)
1713 $this->set_mapping('block_instance', $oldid, $newitemid, true);
1714 // Create the block context
1715 $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id;
1716 // Save the block contexts mapping and sent it to task
1717 $this->set_mapping('context', $oldcontextid, $newcontextid);
1718 $this->task->set_contextid($newcontextid);
1719 $this->task->set_blockid($newitemid);
1720
1721 // Restore block fileareas if declared
1722 $component = 'block_' . $this->task->get_blockname();
1723 foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
1724 $this->add_related_files($component, $filearea, null);
1725 }
1726
1727 // Process block positions, creating them or accumulating for final step
1728 foreach($positions as $position) {
1729 $position = (object)$position;
1730 $position->blockinstanceid = $newitemid; // The instance is always the restored one
1731 // If position is for one already mapped (known) contextid
1732 // process it now, creating the position
1733 if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
1734 $position->contextid = $newpositionctxid;
1735 // Create the block position
1736 $DB->insert_record('block_positions', $position);
1737
1738 // The position belongs to an unknown context, send it to backup_ids
1739 // to process them as part of the final steps of restore. We send the
1740 // whole $position object there, hence use the low level method.
1741 } else {
1742 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
21e51c86
EL
1743 }
1744 }
1745 }
1746}
394edb7e
EL
1747
1748/**
1749 * Structure step to restore common course_module information
1750 *
1751 * This step will process the module.xml file for one activity, in order to restore
1752 * the corresponding information to the course_modules table, skipping various bits
1753 * of information based on CFG settings (groupings, completion...) in order to fullfill
1754 * all the reqs to be able to create the context to be used by all the rest of steps
1755 * in the activity restore task
1756 */
1757class restore_module_structure_step extends restore_structure_step {
1758
1759 protected function define_structure() {
1760 global $CFG;
1761
1762 $paths = array();
1763
1764 $paths[] = new restore_path_element('module', '/module');
1765 if ($CFG->enableavailability) {
1766 $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
1767 }
1768
1769 return $paths;
1770 }
1771
1772 protected function process_module($data) {
1773 global $CFG, $DB;
1774
1775 $data = (object)$data;
1776 $oldid = $data->id;
1777
1778 $data->course = $this->task->get_courseid();
1779 $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
aa39be20
EL
1780 // Map section (first try by course_section mapping match. Useful in course and section restores)
1781 $data->section = $this->get_mappingid('course_section', $data->sectionid);
1782 if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
1783 $params = array(
1784 'course' => $this->get_courseid(),
1785 'section' => $data->sectionnumber);
1786 $data->section = $DB->get_field('course_sections', 'id', $params);
1787 }
1788 if (!$data->section) { // sectionnumber failed, try to get first section in course
1789 $params = array(
1790 'course' => $this->get_courseid());
1791 $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
1792 }
1793 if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
1794 $sectionrec = array(
1795 'course' => $this->get_courseid(),
1796 'section' => 0);
1797 $DB->insert_record('course_sections', $sectionrec); // section 0
1798 $sectionrec = array(
1799 'course' => $this->get_courseid(),
1800 'section' => 1);
1801 $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
1802 }
394edb7e
EL
1803 $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping
1804 if (!$CFG->enablegroupmembersonly) { // observe groupsmemberonly
1805 $data->groupmembersonly = 0;
1806 }
1807 if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness
1808 $data->idnumber = '';
1809 }
5095f325 1810 if (empty($CFG->enablecompletion)) { // completion
394edb7e
EL
1811 $data->completion = 0;
1812 $data->completiongradeitemnumber = null;
1813 $data->completionview = 0;
1814 $data->completionexpected = 0;
1815 } else {
1816 $data->completionexpected = $this->apply_date_offset($data->completionexpected);
1817 }
1818 if (empty($CFG->enableavailability)) {
1819 $data->availablefrom = 0;
1820 $data->availableuntil = 0;
1821 $data->showavailability = 0;
1822 } else {
1823 $data->availablefrom = $this->apply_date_offset($data->availablefrom);
1824 $data->availableuntil= $this->apply_date_offset($data->availableuntil);
1825 }
1826 $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
1827
1828 // course_module record ready, insert it
1829 $newitemid = $DB->insert_record('course_modules', $data);
1830 // save mapping
1831 $this->set_mapping('course_module', $oldid, $newitemid);
1832 // set the new course_module id in the task
1833 $this->task->set_moduleid($newitemid);
1834 // we can now create the context safely
1835 $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id;
1836 // set the new context id in the task
1837 $this->task->set_contextid($ctxid);
1838 // update sequence field in course_section
1839 if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
1840 $sequence .= ',' . $newitemid;
1841 } else {
1842 $sequence = $newitemid;
1843 }
1844 $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section));
1845 }
1846
1847
1848 protected function process_availability($data) {
394edb7e 1849 $data = (object)$data;
5095f325
EL
1850 // Simply going to store the whole availability record now, we'll process
1851 // all them later in the final task (once all actvivities have been restored)
1852 // Let's call the low level one to be able to store the whole object
1853 $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
1854 restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
1855 }
1856}
1857
1858/**
1859 * Structure step that will process the user activity completion
1860 * information if all these conditions are met:
1861 * - Target site has completion enabled ($CFG->enablecompletion)
1862 * - Activity includes completion info (file_exists)
1863 */
1864class restore_userscompletion_structure_step extends restore_structure_step {
1865
1866 /**
1867 * To conditionally decide if this step must be executed
1868 * Note the "settings" conditions are evaluated in the
1869 * corresponding task. Here we check for other conditions
1870 * not being restore settings (files, site settings...)
1871 */
1872 protected function execute_condition() {
1873 global $CFG;
1874
1875 // Completion disabled in this site, don't execute
1876 if (empty($CFG->enablecompletion)) {
1877 return false;
1878 }
1879
1880 // No user completion info found, don't execute
1881 $fullpath = $this->task->get_taskbasepath();
1882 $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
1883 if (!file_exists($fullpath)) {
1884 return false;
1885 }
1886
1887 // Arrived here, execute the step
1888 return true;
1889 }
1890
1891 protected function define_structure() {
1892
1893 $paths = array();
1894
1895 $paths[] = new restore_path_element('completion', '/completions/completion');
1896
1897 return $paths;
1898 }
1899
1900 protected function process_completion($data) {
1901 global $DB;
1902
1903 $data = (object)$data;
1904
1905 $data->coursemoduleid = $this->task->get_moduleid();
1906 $data->userid = $this->get_mappingid('user', $data->userid);
1907 $data->timemodified = $this->apply_date_offset($data->timemodified);
1908
1909 $DB->insert_record('course_modules_completion', $data);
394edb7e
EL
1910 }
1911}
1912
1913/**
1914 * Abstract structure step, parent of all the activity structure steps. Used to suuport
1915 * the main <activity ...> tag and process it. Also provides subplugin support for
1916 * activities.
1917 */
1918abstract class restore_activity_structure_step extends restore_structure_step {
1919
91d11057
EL
1920 protected function add_subplugin_structure($subplugintype, $element) {
1921
1922 global $CFG;
1923
1924 // Check the requested subplugintype is a valid one
1925 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
1926 if (!file_exists($subpluginsfile)) {
1927 throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
1928 }
1929 include($subpluginsfile);
1930 if (!array_key_exists($subplugintype, $subplugins)) {
1931 throw new restore_step_exception('incorrect_subplugin_type', $subplugintype);
1932 }
1933 // Get all the restore path elements, looking across all the subplugin dirs
1934 $subpluginsdirs = get_plugin_list($subplugintype);
1935 foreach ($subpluginsdirs as $name => $subpluginsdir) {
1936 $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin';
1937 $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
1938 if (file_exists($restorefile)) {
1939 require_once($restorefile);
1940 $restoresubplugin = new $classname($subplugintype, $name, $this);
1941 // Add subplugin paths to the step
1942 $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element));
1943 }
1944 }
1945 }
1946
1947 /**
1948 * As far as activity restore steps are implementing restore_subplugin stuff, they need to
1949 * have the parent task available for wrapping purposes (get course/context....)
1950 */
1951 public function get_task() {
1952 return $this->task;
394edb7e
EL
1953 }
1954
1955 /**
1956 * Adds support for the 'activity' path that is common to all the activities
1957 * and will be processed globally here
1958 */
1959 protected function prepare_activity_structure($paths) {
1960
1961 $paths[] = new restore_path_element('activity', '/activity');
1962
1963 return $paths;
1964 }
1965
1966 /**
1967 * Process the activity path, informing the task about various ids, needed later
1968 */
1969 protected function process_activity($data) {
1970 $data = (object)$data;
1971 $this->task->set_old_contextid($data->contextid); // Save old contextid in task
1972 $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
1973 $this->task->set_old_activityid($data->id); // Save old activityid in task
1974 }
1975
1976 /**
034ef761 1977 * This must be invoked immediately after creating the "module" activity record (forum, choice...)
394edb7e
EL
1978 * and will adjust the new activity id (the instance) in various places
1979 */
1980 protected function apply_activity_instance($newitemid) {
1981 global $DB;
1982
1983 $this->task->set_activityid($newitemid); // Save activity id in task
1984 // Apply the id to course_sections->instanceid
1985 $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
1986 // Do the mapping for modulename, preparing it for files by oldcontext
1987 $modulename = $this->task->get_modulename();
1988 $oldid = $this->task->get_old_activityid();
1989 $this->set_mapping($modulename, $oldid, $newitemid, true);
1990 }
1991}