Commit | Line | Data |
---|---|---|
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 | /** | |
f9dab4be DM |
19 | * Defines various restore steps that will be used by common tasks in restore |
20 | * | |
21 | * @package core_backup | |
22 | * @subpackage moodle2 | |
23 | * @category backup | |
24 | * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} | |
25 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
482aac65 EL |
26 | */ |
27 | ||
f9dab4be | 28 | defined('MOODLE_INTERNAL') || die(); |
482aac65 EL |
29 | |
30 | /** | |
31 | * delete old directories and conditionally create backup_temp_ids table | |
32 | */ | |
33 | class restore_create_and_clean_temp_stuff extends restore_execution_step { | |
34 | ||
35 | protected function define_execution() { | |
b8bb45b0 | 36 | $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally |
482aac65 EL |
37 | // If the table already exists, it's because restore_prechecks have been executed in the same |
38 | // request (without problems) and it already contains a bunch of preloaded information (users...) | |
39 | // that we aren't going to execute again | |
40 | if ($exists) { // Inform plan about preloaded information | |
41 | $this->task->set_preloaded_information(); | |
42 | } | |
76cfb124 EL |
43 | // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning |
44 | $itemid = $this->task->get_old_contextid(); | |
a689cd1d | 45 | $newitemid = context_course::instance($this->get_courseid())->id; |
76cfb124 | 46 | restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); |
c0440b3f EL |
47 | // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning |
48 | $itemid = $this->task->get_old_system_contextid(); | |
a689cd1d | 49 | $newitemid = context_system::instance()->id; |
c0440b3f | 50 | restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); |
d90e49f2 EL |
51 | // Create the old-course-id to new-course-id mapping, we need that available since the beginning |
52 | $itemid = $this->task->get_old_courseid(); | |
53 | $newitemid = $this->get_courseid(); | |
54 | restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid); | |
55 | ||
482aac65 EL |
56 | } |
57 | } | |
58 | ||
59 | /** | |
60 | * delete the temp dir used by backup/restore (conditionally), | |
61 | * delete old directories and drop temp ids table | |
62 | */ | |
63 | class restore_drop_and_clean_temp_stuff extends restore_execution_step { | |
64 | ||
65 | protected function define_execution() { | |
66 | global $CFG; | |
b8bb45b0 | 67 | restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table |
1cd39657 | 68 | $progress = $this->task->get_progress(); |
69 | $progress->start_progress('Deleting backup dir'); | |
1f3b2356 | 70 | backup_helper::delete_old_backup_dirs(strtotime('-1 week'), $progress); // Delete > 1 week old temp dirs. |
482aac65 | 71 | if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally |
1cd39657 | 72 | backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir |
482aac65 | 73 | } |
1cd39657 | 74 | $progress->end_progress(); |
482aac65 EL |
75 | } |
76 | } | |
77 | ||
0067d939 AD |
78 | /** |
79 | * Restore calculated grade items, grade categories etc | |
80 | */ | |
9a20df96 | 81 | class restore_gradebook_structure_step extends restore_structure_step { |
0067d939 | 82 | |
a0d27102 AD |
83 | /** |
84 | * To conditionally decide if this step must be executed | |
85 | * Note the "settings" conditions are evaluated in the | |
86 | * corresponding task. Here we check for other conditions | |
87 | * not being restore settings (files, site settings...) | |
88 | */ | |
89 | protected function execute_condition() { | |
9a20df96 | 90 | global $CFG, $DB; |
a0d27102 | 91 | |
03c39daa DM |
92 | if ($this->get_courseid() == SITEID) { |
93 | return false; | |
94 | } | |
95 | ||
a0d27102 AD |
96 | // No gradebook info found, don't execute |
97 | $fullpath = $this->task->get_taskbasepath(); | |
98 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
99 | if (!file_exists($fullpath)) { | |
100 | return false; | |
101 | } | |
102 | ||
58328ce8 EL |
103 | // Some module present in backup file isn't available to restore |
104 | // in this site, don't execute | |
105 | if ($this->task->is_missing_modules()) { | |
106 | return false; | |
107 | } | |
108 | ||
109 | // Some activity has been excluded to be restored, don't execute | |
110 | if ($this->task->is_excluding_activities()) { | |
111 | return false; | |
112 | } | |
113 | ||
9a20df96 AD |
114 | // There should only be one grade category (the 1 associated with the course itself) |
115 | // If other categories already exist we're restoring into an existing course. | |
116 | // Restoring categories into a course with an existing category structure is unlikely to go well | |
117 | $category = new stdclass(); | |
118 | $category->courseid = $this->get_courseid(); | |
119 | $catcount = $DB->count_records('grade_categories', (array)$category); | |
120 | if ($catcount>1) { | |
121 | return false; | |
122 | } | |
123 | ||
a0d27102 AD |
124 | // Arrived here, execute the step |
125 | return true; | |
126 | } | |
127 | ||
0067d939 AD |
128 | protected function define_structure() { |
129 | $paths = array(); | |
130 | $userinfo = $this->task->get_setting_value('users'); | |
131 | ||
132 | $paths[] = new restore_path_element('gradebook', '/gradebook'); | |
133 | $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category'); | |
134 | $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item'); | |
135 | if ($userinfo) { | |
136 | $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade'); | |
137 | } | |
138 | $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter'); | |
b8040c83 | 139 | $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting'); |
0067d939 AD |
140 | |
141 | return $paths; | |
142 | } | |
143 | ||
144 | protected function process_gradebook($data) { | |
deb3d5ed MG |
145 | // For non-merge restore types: |
146 | // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup. | |
147 | $target = $this->get_task()->get_target(); | |
148 | if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) { | |
149 | set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null); | |
150 | } | |
fd36588f | 151 | if (!empty($data['calculations_freeze'])) { |
deb3d5ed MG |
152 | if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING || |
153 | $target == backup::TARGET_EXISTING_DELETING) { | |
154 | set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']); | |
155 | } | |
156 | } | |
0067d939 AD |
157 | } |
158 | ||
159 | protected function process_grade_item($data) { | |
160 | global $DB; | |
161 | ||
162 | $data = (object)$data; | |
163 | ||
164 | $oldid = $data->id; | |
165 | $data->course = $this->get_courseid(); | |
166 | ||
167 | $data->courseid = $this->get_courseid(); | |
168 | ||
0067d939 | 169 | if ($data->itemtype=='manual') { |
d46badb1 | 170 | // manual grade items store category id in categoryid |
98529b00 | 171 | $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL); |
05b73370 FW |
172 | // if mapping failed put in course's grade category |
173 | if (NULL == $data->categoryid) { | |
174 | $coursecat = grade_category::fetch_course_category($this->get_courseid()); | |
175 | $data->categoryid = $coursecat->id; | |
176 | } | |
d46badb1 DM |
177 | } else if ($data->itemtype=='course') { |
178 | // course grade item stores their category id in iteminstance | |
179 | $coursecat = grade_category::fetch_course_category($this->get_courseid()); | |
180 | $data->iteminstance = $coursecat->id; | |
181 | } else if ($data->itemtype=='category') { | |
182 | // category grade items store their category id in iteminstance | |
98529b00 | 183 | $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL); |
d46badb1 DM |
184 | } else { |
185 | throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype); | |
0067d939 AD |
186 | } |
187 | ||
98529b00 AD |
188 | $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL); |
189 | $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL); | |
0067d939 AD |
190 | |
191 | $data->locktime = $this->apply_date_offset($data->locktime); | |
192 | $data->timecreated = $this->apply_date_offset($data->timecreated); | |
193 | $data->timemodified = $this->apply_date_offset($data->timemodified); | |
194 | ||
44a25cd2 | 195 | $coursecategory = $newitemid = null; |
0067d939 AD |
196 | //course grade item should already exist so updating instead of inserting |
197 | if($data->itemtype=='course') { | |
0067d939 AD |
198 | //get the ID of the already created grade item |
199 | $gi = new stdclass(); | |
200 | $gi->courseid = $this->get_courseid(); | |
0067d939 | 201 | $gi->itemtype = $data->itemtype; |
98529b00 AD |
202 | |
203 | //need to get the id of the grade_category that was automatically created for the course | |
204 | $category = new stdclass(); | |
205 | $category->courseid = $this->get_courseid(); | |
206 | $category->parent = null; | |
207 | //course category fullname starts out as ? but may be edited | |
208 | //$category->fullname = '?'; | |
209 | $coursecategory = $DB->get_record('grade_categories', (array)$category); | |
210 | $gi->iteminstance = $coursecategory->id; | |
0067d939 AD |
211 | |
212 | $existinggradeitem = $DB->get_record('grade_items', (array)$gi); | |
44a25cd2 AD |
213 | if (!empty($existinggradeitem)) { |
214 | $data->id = $newitemid = $existinggradeitem->id; | |
215 | $DB->update_record('grade_items', $data); | |
216 | } | |
8f27b77b AO |
217 | } else if ($data->itemtype == 'manual') { |
218 | // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists. | |
219 | $gi = array( | |
220 | 'itemtype' => $data->itemtype, | |
221 | 'courseid' => $data->courseid, | |
222 | 'itemname' => $data->itemname, | |
223 | 'categoryid' => $data->categoryid, | |
224 | ); | |
225 | $newitemid = $DB->get_field('grade_items', 'id', $gi); | |
44a25cd2 | 226 | } |
0067d939 | 227 | |
44a25cd2 AD |
228 | if (empty($newitemid)) { |
229 | //in case we found the course category but still need to insert the course grade item | |
230 | if ($data->itemtype=='course' && !empty($coursecategory)) { | |
231 | $data->iteminstance = $coursecategory->id; | |
232 | } | |
034ef761 | 233 | |
0067d939 AD |
234 | $newitemid = $DB->insert_record('grade_items', $data); |
235 | } | |
236 | $this->set_mapping('grade_item', $oldid, $newitemid); | |
237 | } | |
238 | ||
239 | protected function process_grade_grade($data) { | |
240 | global $DB; | |
241 | ||
242 | $data = (object)$data; | |
167eb033 | 243 | $oldid = $data->id; |
3ea13309 | 244 | $olduserid = $data->userid; |
0067d939 AD |
245 | |
246 | $data->itemid = $this->get_new_parentid('grade_item'); | |
247 | ||
3ea13309 EL |
248 | $data->userid = $this->get_mappingid('user', $data->userid, null); |
249 | if (!empty($data->userid)) { | |
250 | $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); | |
a1a2cc59 RT |
251 | $data->locktime = $this->apply_date_offset($data->locktime); |
252 | // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled? | |
253 | $data->overridden = $this->apply_date_offset($data->overridden); | |
254 | $data->timecreated = $this->apply_date_offset($data->timecreated); | |
255 | $data->timemodified = $this->apply_date_offset($data->timemodified); | |
256 | ||
98fed696 FM |
257 | $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid)); |
258 | if ($gradeexists) { | |
259 | $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'"; | |
260 | $this->log($message, backup::LOG_DEBUG); | |
261 | } else { | |
262 | $newitemid = $DB->insert_record('grade_grades', $data); | |
167eb033 | 263 | $this->set_mapping('grade_grades', $oldid, $newitemid); |
98fed696 | 264 | } |
a1a2cc59 | 265 | } else { |
62182e89 | 266 | $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; |
267 | $this->log($message, backup::LOG_DEBUG); | |
a1a2cc59 | 268 | } |
0067d939 | 269 | } |
3ea13309 | 270 | |
0067d939 AD |
271 | protected function process_grade_category($data) { |
272 | global $DB; | |
273 | ||
274 | $data = (object)$data; | |
275 | $oldid = $data->id; | |
276 | ||
277 | $data->course = $this->get_courseid(); | |
278 | $data->courseid = $data->course; | |
279 | ||
280 | $data->timecreated = $this->apply_date_offset($data->timecreated); | |
281 | $data->timemodified = $this->apply_date_offset($data->timemodified); | |
282 | ||
499dbce8 AD |
283 | $newitemid = null; |
284 | //no parent means a course level grade category. That may have been created when the course was created | |
0067d939 | 285 | if(empty($data->parent)) { |
499dbce8 AD |
286 | //parent was being saved as 0 when it should be null |
287 | $data->parent = null; | |
288 | ||
0067d939 AD |
289 | //get the already created course level grade category |
290 | $category = new stdclass(); | |
499dbce8 | 291 | $category->courseid = $this->get_courseid(); |
41f21f92 | 292 | $category->parent = null; |
0067d939 AD |
293 | |
294 | $coursecategory = $DB->get_record('grade_categories', (array)$category); | |
499dbce8 AD |
295 | if (!empty($coursecategory)) { |
296 | $data->id = $newitemid = $coursecategory->id; | |
297 | $DB->update_record('grade_categories', $data); | |
298 | } | |
299 | } | |
0067d939 | 300 | |
47d6e6a7 DW |
301 | // Add a warning about a removed setting. |
302 | if (!empty($data->aggregatesubcats)) { | |
303 | set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1); | |
304 | } | |
305 | ||
499dbce8 AD |
306 | //need to insert a course category |
307 | if (empty($newitemid)) { | |
0067d939 AD |
308 | $newitemid = $DB->insert_record('grade_categories', $data); |
309 | } | |
310 | $this->set_mapping('grade_category', $oldid, $newitemid); | |
0067d939 AD |
311 | } |
312 | protected function process_grade_letter($data) { | |
313 | global $DB; | |
314 | ||
315 | $data = (object)$data; | |
316 | $oldid = $data->id; | |
317 | ||
a689cd1d | 318 | $data->contextid = context_course::instance($this->get_courseid())->id; |
0067d939 | 319 | |
67d4424a DM |
320 | $gradeletter = (array)$data; |
321 | unset($gradeletter['id']); | |
322 | if (!$DB->record_exists('grade_letters', $gradeletter)) { | |
5bc8335c JF |
323 | $newitemid = $DB->insert_record('grade_letters', $data); |
324 | } else { | |
325 | $newitemid = $data->id; | |
326 | } | |
327 | ||
0067d939 AD |
328 | $this->set_mapping('grade_letter', $oldid, $newitemid); |
329 | } | |
b8040c83 AD |
330 | protected function process_grade_setting($data) { |
331 | global $DB; | |
332 | ||
333 | $data = (object)$data; | |
334 | $oldid = $data->id; | |
335 | ||
336 | $data->courseid = $this->get_courseid(); | |
337 | ||
eff864e7 FM |
338 | $target = $this->get_task()->get_target(); |
339 | if ($data->name == 'minmaxtouse' && | |
340 | ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) { | |
341 | // We never restore minmaxtouse during merge. | |
342 | return; | |
343 | } | |
344 | ||
924b8d72 JPG |
345 | if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) { |
346 | $newitemid = $DB->insert_record('grade_settings', $data); | |
347 | } else { | |
348 | $newitemid = $data->id; | |
349 | } | |
350 | ||
eff864e7 FM |
351 | if (!empty($oldid)) { |
352 | // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting. | |
353 | $this->set_mapping('grade_setting', $oldid, $newitemid); | |
354 | } | |
b8040c83 | 355 | } |
0f94550c | 356 | |
7bbf4166 SH |
357 | /** |
358 | * put all activity grade items in the correct grade category and mark all for recalculation | |
359 | */ | |
c4d2c745 AD |
360 | protected function after_execute() { |
361 | global $DB; | |
362 | ||
c4d2c745 AD |
363 | $conditions = array( |
364 | 'backupid' => $this->get_restoreid(), | |
365 | 'itemname' => 'grade_item'//, | |
366 | //'itemid' => $itemid | |
367 | ); | |
368 | $rs = $DB->get_recordset('backup_ids_temp', $conditions); | |
369 | ||
7bbf4166 SH |
370 | // We need this for calculation magic later on. |
371 | $mappings = array(); | |
372 | ||
c4d2c745 AD |
373 | if (!empty($rs)) { |
374 | foreach($rs as $grade_item_backup) { | |
7bbf4166 SH |
375 | |
376 | // Store the oldid with the new id. | |
377 | $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid; | |
378 | ||
0f94550c AD |
379 | $updateobj = new stdclass(); |
380 | $updateobj->id = $grade_item_backup->newitemid; | |
074a765f | 381 | |
0f94550c AD |
382 | //if this is an activity grade item that needs to be put back in its correct category |
383 | if (!empty($grade_item_backup->parentitemid)) { | |
d46badb1 DM |
384 | $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null); |
385 | if (!is_null($oldcategoryid)) { | |
386 | $updateobj->categoryid = $oldcategoryid; | |
387 | $DB->update_record('grade_items', $updateobj); | |
388 | } | |
074a765f | 389 | } else { |
0f94550c AD |
390 | //mark course and category items as needing to be recalculated |
391 | $updateobj->needsupdate=1; | |
d46badb1 | 392 | $DB->update_record('grade_items', $updateobj); |
c4d2c745 | 393 | } |
9a20df96 AD |
394 | } |
395 | } | |
396 | $rs->close(); | |
0f94550c | 397 | |
7bbf4166 SH |
398 | // We need to update the calculations for calculated grade items that may reference old |
399 | // grade item ids using ##gi\d+##. | |
c8fbcaab EL |
400 | // $mappings can be empty, use 0 if so (won't match ever) |
401 | list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0); | |
7bbf4166 SH |
402 | $sql = "SELECT gi.id, gi.calculation |
403 | FROM {grade_items} gi | |
404 | WHERE gi.id {$sql} AND | |
405 | calculation IS NOT NULL"; | |
406 | $rs = $DB->get_recordset_sql($sql, $params); | |
407 | foreach ($rs as $gradeitem) { | |
408 | // Collect all of the used grade item id references | |
409 | if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) { | |
410 | // This calculation doesn't reference any other grade items... EASY! | |
411 | continue; | |
412 | } | |
413 | // For this next bit we are going to do the replacement of id's in two steps: | |
414 | // 1. We will replace all old id references with a special mapping reference. | |
415 | // 2. We will replace all mapping references with id's | |
416 | // Why do we do this? | |
417 | // Because there potentially there will be an overlap of ids within the query and we | |
418 | // we substitute the wrong id.. safest way around this is the two step system | |
419 | $calculationmap = array(); | |
420 | $mapcount = 0; | |
421 | foreach ($matches[1] as $match) { | |
422 | // Check that the old id is known to us, if not it was broken to begin with and will | |
423 | // continue to be broken. | |
424 | if (!array_key_exists($match, $mappings)) { | |
425 | continue; | |
426 | } | |
427 | // Our special mapping key | |
428 | $mapping = '##MAPPING'.$mapcount.'##'; | |
429 | // The old id that exists within the calculation now | |
430 | $oldid = '##gi'.$match.'##'; | |
431 | // The new id that we want to replace the old one with. | |
432 | $newid = '##gi'.$mappings[$match].'##'; | |
433 | // Replace in the special mapping key | |
434 | $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation); | |
435 | // And record the mapping | |
436 | $calculationmap[$mapping] = $newid; | |
437 | $mapcount++; | |
438 | } | |
439 | // Iterate all special mappings for this calculation and replace in the new id's | |
440 | foreach ($calculationmap as $mapping => $newid) { | |
441 | $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation); | |
442 | } | |
443 | // Update the calculation now that its being remapped | |
444 | $DB->update_record('grade_items', $gradeitem); | |
445 | } | |
446 | $rs->close(); | |
447 | ||
a60835c7 | 448 | // Need to correct the grade category path and parent |
9a20df96 AD |
449 | $conditions = array( |
450 | 'courseid' => $this->get_courseid() | |
451 | ); | |
034ef761 | 452 | |
9a20df96 | 453 | $rs = $DB->get_recordset('grade_categories', $conditions); |
a60835c7 TH |
454 | // Get all the parents correct first as grade_category::build_path() loads category parents from the DB |
455 | foreach ($rs as $gc) { | |
456 | if (!empty($gc->parent)) { | |
457 | $grade_category = new stdClass(); | |
458 | $grade_category->id = $gc->id; | |
459 | $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent); | |
460 | $DB->update_record('grade_categories', $grade_category); | |
9a20df96 AD |
461 | } |
462 | } | |
9a20df96 AD |
463 | $rs->close(); |
464 | ||
a60835c7 | 465 | // Now we can rebuild all the paths |
9a20df96 | 466 | $rs = $DB->get_recordset('grade_categories', $conditions); |
a60835c7 TH |
467 | foreach ($rs as $gc) { |
468 | $grade_category = new stdClass(); | |
469 | $grade_category->id = $gc->id; | |
470 | $grade_category->path = grade_category::build_path($gc); | |
471 | $grade_category->depth = substr_count($grade_category->path, '/') - 1; | |
472 | $DB->update_record('grade_categories', $grade_category); | |
c4d2c745 AD |
473 | } |
474 | $rs->close(); | |
98529b00 | 475 | |
cd4061ec FM |
476 | // Check what to do with the minmaxtouse setting. |
477 | $this->check_minmaxtouse(); | |
478 | ||
deb3d5ed MG |
479 | // Freeze gradebook calculations if needed. |
480 | $this->gradebook_calculation_freeze(); | |
481 | ||
a60835c7 | 482 | // Restore marks items as needing update. Update everything now. |
98529b00 | 483 | grade_regrade_final_grades($this->get_courseid()); |
c4d2c745 | 484 | } |
deb3d5ed MG |
485 | |
486 | /** | |
487 | * Freeze gradebook calculation if needed. | |
488 | * | |
489 | * This is similar to various upgrade scripts that check if the freeze is needed. | |
490 | */ | |
491 | protected function gradebook_calculation_freeze() { | |
492 | global $CFG; | |
493 | $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid()); | |
494 | preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches); | |
495 | $backupbuild = (int)$matches[1]; | |
405b90bc AG |
496 | // The function floatval will return a float even if there is text mixed with the release number. |
497 | $backuprelease = floatval($this->get_task()->get_info()->backup_release); | |
156d0486 MG |
498 | |
499 | // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619). | |
500 | if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) { | |
501 | require_once($CFG->libdir . '/db/upgradelib.php'); | |
502 | upgrade_extra_credit_weightoverride($this->get_courseid()); | |
503 | } | |
4d4dcc27 AG |
504 | // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627). |
505 | if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) { | |
506 | require_once($CFG->libdir . '/db/upgradelib.php'); | |
507 | upgrade_calculated_grade_items($this->get_courseid()); | |
508 | } | |
405b90bc AG |
509 | // Courses from before 3.1 (20160511) may have a letter boundary problem and should be checked for this issue. |
510 | // Backups from before and including 2.9 could have a build number that is greater than 20160511 and should | |
511 | // be checked for this problem. | |
512 | if (!$gradebookcalculationsfreeze && ($backupbuild < 20160511 || $backuprelease <= 2.9)) { | |
513 | require_once($CFG->libdir . '/db/upgradelib.php'); | |
514 | upgrade_course_letter_boundary($this->get_courseid()); | |
515 | } | |
516 | ||
deb3d5ed | 517 | } |
cd4061ec FM |
518 | |
519 | /** | |
520 | * Checks what should happen with the course grade setting minmaxtouse. | |
521 | * | |
522 | * This is related to the upgrade step at the time the setting was added. | |
523 | * | |
524 | * @see MDL-48618 | |
525 | * @return void | |
526 | */ | |
527 | protected function check_minmaxtouse() { | |
528 | global $CFG, $DB; | |
529 | require_once($CFG->libdir . '/gradelib.php'); | |
530 | ||
531 | $userinfo = $this->task->get_setting_value('users'); | |
532 | $settingname = 'minmaxtouse'; | |
533 | $courseid = $this->get_courseid(); | |
534 | $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname)); | |
535 | $version28start = 2014111000.00; | |
536 | $version28last = 2014111006.05; | |
537 | $version29start = 2015051100.00; | |
538 | $version29last = 2015060400.02; | |
539 | ||
35af60da | 540 | $target = $this->get_task()->get_target(); |
eff864e7 FM |
541 | if ($minmaxtouse === false && |
542 | ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) { | |
cd4061ec | 543 | // The setting was not found because this setting did not exist at the time the backup was made. |
eff864e7 | 544 | // And we are not restoring as merge, in which case we leave the course as it was. |
cd4061ec FM |
545 | $version = $this->get_task()->get_info()->moodle_version; |
546 | ||
547 | if ($version < $version28start) { | |
548 | // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them. | |
549 | if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) { | |
550 | grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM); | |
551 | } | |
552 | ||
553 | } else if (($version >= $version28start && $version < $version28last) || | |
554 | ($version >= $version29start && $version < $version29last)) { | |
555 | // They should be using grade_grade when the course has inconsistencies. | |
556 | ||
557 | $sql = "SELECT gi.id | |
558 | FROM {grade_items} gi | |
559 | JOIN {grade_grades} gg | |
560 | ON gg.itemid = gi.id | |
561 | WHERE gi.courseid = ? | |
562 | AND (gi.itemtype != ? AND gi.itemtype != ?) | |
563 | AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)"; | |
564 | ||
565 | // The course can only have inconsistencies when we restore the user info, | |
566 | // we do not need to act on existing grades that were not restored as part of this backup. | |
567 | if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) { | |
568 | ||
569 | // Display the notice as we do during upgrade. | |
570 | set_config('show_min_max_grades_changed_' . $courseid, 1); | |
571 | ||
572 | if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) { | |
573 | // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE. | |
574 | // If they are using the site-wide grade_grade setting, we only want to notice them. | |
575 | grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE); | |
576 | } | |
577 | } | |
578 | ||
579 | } else { | |
580 | // This should never happen because from now on minmaxtouse is always saved in backups. | |
581 | } | |
582 | } | |
583 | } | |
0067d939 AD |
584 | } |
585 | ||
167eb033 FM |
586 | /** |
587 | * Step in charge of restoring the grade history of a course. | |
588 | * | |
589 | * The execution conditions are itendical to {@link restore_gradebook_structure_step} because | |
590 | * we do not want to restore the history if the gradebook and its content has not been | |
591 | * restored. At least for now. | |
592 | */ | |
593 | class restore_grade_history_structure_step extends restore_structure_step { | |
594 | ||
595 | protected function execute_condition() { | |
596 | global $CFG, $DB; | |
597 | ||
03c39daa DM |
598 | if ($this->get_courseid() == SITEID) { |
599 | return false; | |
600 | } | |
601 | ||
167eb033 FM |
602 | // No gradebook info found, don't execute. |
603 | $fullpath = $this->task->get_taskbasepath(); | |
604 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
605 | if (!file_exists($fullpath)) { | |
606 | return false; | |
607 | } | |
608 | ||
609 | // Some module present in backup file isn't available to restore in this site, don't execute. | |
610 | if ($this->task->is_missing_modules()) { | |
611 | return false; | |
612 | } | |
613 | ||
614 | // Some activity has been excluded to be restored, don't execute. | |
615 | if ($this->task->is_excluding_activities()) { | |
616 | return false; | |
617 | } | |
618 | ||
619 | // There should only be one grade category (the 1 associated with the course itself). | |
620 | $category = new stdclass(); | |
621 | $category->courseid = $this->get_courseid(); | |
622 | $catcount = $DB->count_records('grade_categories', (array)$category); | |
623 | if ($catcount > 1) { | |
624 | return false; | |
625 | } | |
626 | ||
627 | // Arrived here, execute the step. | |
628 | return true; | |
629 | } | |
630 | ||
631 | protected function define_structure() { | |
632 | $paths = array(); | |
633 | ||
634 | // Settings to use. | |
635 | $userinfo = $this->get_setting_value('users'); | |
636 | $history = $this->get_setting_value('grade_histories'); | |
637 | ||
638 | if ($userinfo && $history) { | |
639 | $paths[] = new restore_path_element('grade_grade', | |
640 | '/grade_history/grade_grades/grade_grade'); | |
641 | } | |
642 | ||
643 | return $paths; | |
644 | } | |
645 | ||
646 | protected function process_grade_grade($data) { | |
647 | global $DB; | |
648 | ||
649 | $data = (object)($data); | |
650 | $olduserid = $data->userid; | |
651 | unset($data->id); | |
652 | ||
653 | $data->userid = $this->get_mappingid('user', $data->userid, null); | |
654 | if (!empty($data->userid)) { | |
655 | // Do not apply the date offsets as this is history. | |
656 | $data->itemid = $this->get_mappingid('grade_item', $data->itemid); | |
657 | $data->oldid = $this->get_mappingid('grade_grades', $data->oldid); | |
658 | $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); | |
659 | $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); | |
660 | $DB->insert_record('grade_grades_history', $data); | |
661 | } else { | |
662 | $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; | |
663 | $this->log($message, backup::LOG_DEBUG); | |
664 | } | |
665 | } | |
666 | ||
667 | } | |
668 | ||
394edb7e EL |
669 | /** |
670 | * decode all the interlinks present in restored content | |
671 | * relying 100% in the restore_decode_processor that handles | |
672 | * both the contents to modify and the rules to be applied | |
673 | */ | |
674 | class restore_decode_interlinks extends restore_execution_step { | |
675 | ||
676 | protected function define_execution() { | |
9f68f2d5 EL |
677 | // Get the decoder (from the plan) |
678 | $decoder = $this->task->get_decoder(); | |
679 | restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules | |
680 | // And launch it, everything will be processed | |
681 | $decoder->execute(); | |
394edb7e EL |
682 | } |
683 | } | |
684 | ||
685 | /** | |
e3c2e1b2 EL |
686 | * first, ensure that we have no gaps in section numbers |
687 | * and then, rebuid the course cache | |
394edb7e EL |
688 | */ |
689 | class restore_rebuild_course_cache extends restore_execution_step { | |
690 | ||
691 | protected function define_execution() { | |
e3c2e1b2 EL |
692 | global $DB; |
693 | ||
694 | // Although there is some sort of auto-recovery of missing sections | |
695 | // present in course/formats... here we check that all the sections | |
696 | // from 0 to MAX(section->section) exist, creating them if necessary | |
697 | $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid())); | |
698 | // Iterate over all sections | |
699 | for ($i = 0; $i <= $maxsection; $i++) { | |
700 | // If the section $i doesn't exist, create it | |
701 | if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) { | |
702 | $sectionrec = array( | |
703 | 'course' => $this->get_courseid(), | |
704 | 'section' => $i); | |
705 | $DB->insert_record('course_sections', $sectionrec); // missing section created | |
706 | } | |
707 | } | |
708 | ||
709 | // Rebuild cache now that all sections are in place | |
394edb7e | 710 | rebuild_course_cache($this->get_courseid()); |
cdb6045d MG |
711 | cache_helper::purge_by_event('changesincourse'); |
712 | cache_helper::purge_by_event('changesincoursecat'); | |
394edb7e EL |
713 | } |
714 | } | |
715 | ||
648a575e EL |
716 | /** |
717 | * Review all the tasks having one after_restore method | |
718 | * executing it to perform some final adjustments of information | |
719 | * not available when the task was executed. | |
720 | */ | |
721 | class restore_execute_after_restore extends restore_execution_step { | |
722 | ||
723 | protected function define_execution() { | |
724 | ||
725 | // Simply call to the execute_after_restore() method of the task | |
726 | // that always is the restore_final_task | |
727 | $this->task->launch_execute_after_restore(); | |
728 | } | |
729 | } | |
730 | ||
b8e455a7 EL |
731 | |
732 | /** | |
733 | * Review all the (pending) block positions in backup_ids, matching by | |
734 | * contextid, creating positions as needed. This is executed by the | |
735 | * final task, once all the contexts have been created | |
736 | */ | |
737 | class restore_review_pending_block_positions extends restore_execution_step { | |
738 | ||
739 | protected function define_execution() { | |
740 | global $DB; | |
741 | ||
742 | // Get all the block_position objects pending to match | |
743 | $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position'); | |
3e7e2ab2 | 744 | $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info'); |
b8e455a7 EL |
745 | // Process block positions, creating them or accumulating for final step |
746 | foreach($rs as $posrec) { | |
3e7e2ab2 RS |
747 | // Get the complete position object out of the info field. |
748 | $position = backup_controller_dbops::decode_backup_temp_info($posrec->info); | |
b8e455a7 EL |
749 | // If position is for one already mapped (known) contextid |
750 | // process it now, creating the position, else nothing to | |
751 | // do, position finally discarded | |
752 | if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) { | |
753 | $position->contextid = $newctx->newitemid; | |
754 | // Create the block position | |
755 | $DB->insert_record('block_positions', $position); | |
756 | } | |
757 | } | |
758 | $rs->close(); | |
759 | } | |
760 | } | |
761 | ||
38674ef9 | 762 | |
763 | /** | |
764 | * Updates the availability data for course modules and sections. | |
765 | * | |
766 | * Runs after the restore of all course modules, sections, and grade items has | |
767 | * completed. This is necessary in order to update IDs that have changed during | |
768 | * restore. | |
769 | * | |
770 | * @package core_backup | |
771 | * @copyright 2014 The Open University | |
772 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
773 | */ | |
774 | class restore_update_availability extends restore_execution_step { | |
775 | ||
776 | protected function define_execution() { | |
777 | global $CFG, $DB; | |
778 | ||
779 | // Note: This code runs even if availability is disabled when restoring. | |
780 | // That will ensure that if you later turn availability on for the site, | |
781 | // there will be no incorrect IDs. (It doesn't take long if the restored | |
782 | // data does not contain any availability information.) | |
783 | ||
784 | // Get modinfo with all data after resetting cache. | |
785 | rebuild_course_cache($this->get_courseid(), true); | |
786 | $modinfo = get_fast_modinfo($this->get_courseid()); | |
787 | ||
5176504d | 788 | // Get the date offset for this restore. |
789 | $dateoffset = $this->apply_date_offset(1) - 1; | |
790 | ||
38674ef9 | 791 | // Update all sections that were restored. |
792 | $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section'); | |
793 | $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid'); | |
794 | $sectionsbyid = null; | |
795 | foreach ($rs as $rec) { | |
796 | if (is_null($sectionsbyid)) { | |
797 | $sectionsbyid = array(); | |
798 | foreach ($modinfo->get_section_info_all() as $section) { | |
799 | $sectionsbyid[$section->id] = $section; | |
800 | } | |
801 | } | |
802 | if (!array_key_exists($rec->newitemid, $sectionsbyid)) { | |
803 | // If the section was not fully restored for some reason | |
804 | // (e.g. due to an earlier error), skip it. | |
805 | $this->get_logger()->process('Section not fully restored: id ' . | |
806 | $rec->newitemid, backup::LOG_WARNING); | |
807 | continue; | |
808 | } | |
809 | $section = $sectionsbyid[$rec->newitemid]; | |
810 | if (!is_null($section->availability)) { | |
811 | $info = new \core_availability\info_section($section); | |
812 | $info->update_after_restore($this->get_restoreid(), | |
5ef6f97f | 813 | $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task); |
38674ef9 | 814 | } |
815 | } | |
816 | $rs->close(); | |
817 | ||
818 | // Update all modules that were restored. | |
819 | $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module'); | |
820 | $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid'); | |
821 | foreach ($rs as $rec) { | |
822 | if (!array_key_exists($rec->newitemid, $modinfo->cms)) { | |
823 | // If the module was not fully restored for some reason | |
824 | // (e.g. due to an earlier error), skip it. | |
825 | $this->get_logger()->process('Module not fully restored: id ' . | |
826 | $rec->newitemid, backup::LOG_WARNING); | |
827 | continue; | |
828 | } | |
829 | $cm = $modinfo->get_cm($rec->newitemid); | |
830 | if (!is_null($cm->availability)) { | |
831 | $info = new \core_availability\info_module($cm); | |
832 | $info->update_after_restore($this->get_restoreid(), | |
5ef6f97f | 833 | $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task); |
38674ef9 | 834 | } |
835 | } | |
836 | $rs->close(); | |
837 | } | |
838 | } | |
839 | ||
840 | ||
5095f325 | 841 | /** |
38674ef9 | 842 | * Process legacy module availability records in backup_ids. |
843 | * | |
844 | * Matches course modules and grade item id once all them have been already restored. | |
845 | * Only if all matchings are satisfied the availability condition will be created. | |
5095f325 | 846 | * At the same time, it is required for the site to have that functionality enabled. |
38674ef9 | 847 | * |
848 | * This step is included only to handle legacy backups (2.6 and before). It does not | |
849 | * do anything for newer backups. | |
850 | * | |
851 | * @copyright 2014 The Open University | |
852 | * @license http://www.gnu.org/copyleft/gpl.html GNU Public License | |
5095f325 EL |
853 | */ |
854 | class restore_process_course_modules_availability extends restore_execution_step { | |
855 | ||
856 | protected function define_execution() { | |
857 | global $CFG, $DB; | |
858 | ||
859 | // Site hasn't availability enabled | |
860 | if (empty($CFG->enableavailability)) { | |
861 | return; | |
862 | } | |
863 | ||
38674ef9 | 864 | // Do both modules and sections. |
865 | foreach (array('module', 'section') as $table) { | |
866 | // Get all the availability objects to process. | |
867 | $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability'); | |
868 | $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info'); | |
869 | // Process availabilities, creating them if everything matches ok. | |
870 | foreach ($rs as $availrec) { | |
871 | $allmatchesok = true; | |
872 | // Get the complete legacy availability object. | |
873 | $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info); | |
874 | ||
875 | // Note: This code used to update IDs, but that is now handled by the | |
876 | // current code (after restore) instead of this legacy code. | |
877 | ||
878 | // Get showavailability option. | |
879 | $thingid = ($table === 'module') ? $availability->coursemoduleid : | |
880 | $availability->coursesectionid; | |
881 | $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), | |
882 | $table . '_showavailability', $thingid); | |
883 | if (!$showrec) { | |
884 | // Should not happen. | |
885 | throw new coding_exception('No matching showavailability record'); | |
5095f325 | 886 | } |
38674ef9 | 887 | $show = $showrec->info->showavailability; |
888 | ||
889 | // The $availability object is now in the format used in the old | |
890 | // system. Interpret this and convert to new system. | |
891 | $currentvalue = $DB->get_field('course_' . $table . 's', 'availability', | |
892 | array('id' => $thingid), MUST_EXIST); | |
893 | $newvalue = \core_availability\info::add_legacy_availability_condition( | |
894 | $currentvalue, $availability, $show); | |
895 | $DB->set_field('course_' . $table . 's', 'availability', $newvalue, | |
896 | array('id' => $thingid)); | |
5095f325 EL |
897 | } |
898 | } | |
899 | $rs->close(); | |
900 | } | |
901 | } | |
902 | ||
903 | ||
482aac65 EL |
904 | /* |
905 | * Execution step that, *conditionally* (if there isn't preloaded information) | |
906 | * will load the inforef files for all the included course/section/activity tasks | |
907 | * to backup_temp_ids. They will be stored with "xxxxref" as itemname | |
908 | */ | |
909 | class restore_load_included_inforef_records extends restore_execution_step { | |
910 | ||
911 | protected function define_execution() { | |
912 | ||
913 | if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do | |
914 | return; | |
915 | } | |
916 | ||
648a575e EL |
917 | // Get all the included tasks |
918 | $tasks = restore_dbops::get_included_tasks($this->get_restoreid()); | |
4fb31ae6 | 919 | $progress = $this->task->get_progress(); |
920 | $progress->start_progress($this->get_name(), count($tasks)); | |
648a575e EL |
921 | foreach ($tasks as $task) { |
922 | // Load the inforef.xml file if exists | |
923 | $inforefpath = $task->get_taskbasepath() . '/inforef.xml'; | |
924 | if (file_exists($inforefpath)) { | |
4fb31ae6 | 925 | // Load each inforef file to temp_ids. |
926 | restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress); | |
648a575e | 927 | } |
482aac65 | 928 | } |
4fb31ae6 | 929 | $progress->end_progress(); |
482aac65 EL |
930 | } |
931 | } | |
932 | ||
76cfb124 | 933 | /* |
b8bb45b0 | 934 | * Execution step that will load all the needed files into backup_files_temp |
76cfb124 EL |
935 | * - info: contains the whole original object (times, names...) |
936 | * (all them being original ids as loaded from xml) | |
937 | */ | |
938 | class restore_load_included_files extends restore_structure_step { | |
939 | ||
940 | protected function define_structure() { | |
941 | ||
942 | $file = new restore_path_element('file', '/files/file'); | |
943 | ||
944 | return array($file); | |
945 | } | |
946 | ||
67233725 | 947 | /** |
4b6b087f | 948 | * Process one <file> element from files.xml |
67233725 | 949 | * |
4b6b087f | 950 | * @param array $data the element data |
67233725 | 951 | */ |
76cfb124 EL |
952 | public function process_file($data) { |
953 | ||
954 | $data = (object)$data; // handy | |
955 | ||
76cfb124 EL |
956 | // load it if needed: |
957 | // - it it is one of the annotated inforef files (course/section/activity/block) | |
41941110 EL |
958 | // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever) |
959 | // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use, | |
960 | // but then we'll need to change it to load plugins itself (because this is executed too early in restore) | |
b8bb45b0 | 961 | $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id); |
2832093f | 962 | $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' || |
41941110 EL |
963 | $data->component == 'grouping' || $data->component == 'grade' || |
964 | $data->component == 'question' || substr($data->component, 0, 5) == 'qtype'); | |
76cfb124 | 965 | if ($isfileref || $iscomponent) { |
b8bb45b0 | 966 | restore_dbops::set_backup_files_record($this->get_restoreid(), $data); |
76cfb124 EL |
967 | } |
968 | } | |
969 | } | |
970 | ||
71a50b13 EL |
971 | /** |
972 | * Execution step that, *conditionally* (if there isn't preloaded information), | |
973 | * will load all the needed roles to backup_temp_ids. They will be stored with | |
974 | * "role" itemname. Also it will perform one automatic mapping to roles existing | |
975 | * in the target site, based in permissions of the user performing the restore, | |
976 | * archetypes and other bits. At the end, each original role will have its associated | |
977 | * target role or 0 if it's going to be skipped. Note we wrap everything over one | |
978 | * restore_dbops method, as far as the same stuff is going to be also executed | |
979 | * by restore prechecks | |
980 | */ | |
981 | class restore_load_and_map_roles extends restore_execution_step { | |
982 | ||
983 | protected function define_execution() { | |
8d4e41f4 | 984 | if ($this->task->get_preloaded_information()) { // if info is already preloaded |
71a50b13 EL |
985 | return; |
986 | } | |
987 | ||
988 | $file = $this->get_basepath() . '/roles.xml'; | |
989 | // Load needed toles to temp_ids | |
990 | restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file); | |
8d4e41f4 | 991 | |
71a50b13 | 992 | // Process roles, mapping/skipping. Any error throws exception |
8d4e41f4 EL |
993 | // Note we pass controller's info because it can contain role mapping information |
994 | // about manual mappings performed by UI | |
995 | 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 |
996 | } |
997 | } | |
998 | ||
482aac65 EL |
999 | /** |
1000 | * Execution step that, *conditionally* (if there isn't preloaded information | |
1001 | * and users have been selected in settings, will load all the needed users | |
1002 | * to backup_temp_ids. They will be stored with "user" itemname and with | |
76cfb124 | 1003 | * their original contextid as paremitemid |
482aac65 EL |
1004 | */ |
1005 | class restore_load_included_users extends restore_execution_step { | |
1006 | ||
1007 | protected function define_execution() { | |
1008 | ||
1009 | if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do | |
1010 | return; | |
1011 | } | |
25d3cf44 | 1012 | if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do |
482aac65 EL |
1013 | return; |
1014 | } | |
1015 | $file = $this->get_basepath() . '/users.xml'; | |
4fb31ae6 | 1016 | // Load needed users to temp_ids. |
1017 | restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress()); | |
482aac65 EL |
1018 | } |
1019 | } | |
1020 | ||
1021 | /** | |
1022 | * Execution step that, *conditionally* (if there isn't preloaded information | |
1023 | * and users have been selected in settings, will process all the needed users | |
1024 | * in order to decide and perform any action with them (create / map / error) | |
1025 | * Note: Any error will cause exception, as far as this is the same processing | |
1026 | * than the one into restore prechecks (that should have stopped process earlier) | |
1027 | */ | |
76cfb124 | 1028 | class restore_process_included_users extends restore_execution_step { |
482aac65 EL |
1029 | |
1030 | protected function define_execution() { | |
1031 | ||
1032 | if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do | |
1033 | return; | |
1034 | } | |
25d3cf44 | 1035 | if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do |
482aac65 EL |
1036 | return; |
1037 | } | |
4fb31ae6 | 1038 | restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), |
1039 | $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress()); | |
482aac65 EL |
1040 | } |
1041 | } | |
1042 | ||
76cfb124 EL |
1043 | /** |
1044 | * Execution step that will create all the needed users as calculated | |
1045 | * by @restore_process_included_users (those having newiteind = 0) | |
1046 | */ | |
1047 | class restore_create_included_users extends restore_execution_step { | |
1048 | ||
1049 | protected function define_execution() { | |
1050 | ||
0e263705 | 1051 | restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), |
1052 | $this->task->get_userid(), $this->task->get_progress()); | |
76cfb124 EL |
1053 | } |
1054 | } | |
1055 | ||
1056 | /** | |
1057 | * Structure step that will create all the needed groups and groupings | |
1058 | * by loading them from the groups.xml file performing the required matches. | |
1059 | * Note group members only will be added if restoring user info | |
1060 | */ | |
1061 | class restore_groups_structure_step extends restore_structure_step { | |
1062 | ||
c0440b3f EL |
1063 | protected function define_structure() { |
1064 | ||
1065 | $paths = array(); // Add paths here | |
1066 | ||
868b086c MS |
1067 | // Do not include group/groupings information if not requested. |
1068 | $groupinfo = $this->get_setting_value('groups'); | |
1069 | if ($groupinfo) { | |
1070 | $paths[] = new restore_path_element('group', '/groups/group'); | |
1071 | $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping'); | |
1072 | $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group'); | |
1073 | } | |
c0440b3f EL |
1074 | return $paths; |
1075 | } | |
1076 | ||
1077 | // Processing functions go here | |
1078 | public function process_group($data) { | |
1079 | global $DB; | |
1080 | ||
1081 | $data = (object)$data; // handy | |
1082 | $data->courseid = $this->get_courseid(); | |
1083 | ||
74b714df ARN |
1084 | // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by |
1085 | // another a group in the same course | |
1086 | $context = context_course::instance($data->courseid); | |
128af106 | 1087 | if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { |
74b714df ARN |
1088 | if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) { |
1089 | unset($data->idnumber); | |
1090 | } | |
1091 | } else { | |
1092 | unset($data->idnumber); | |
1093 | } | |
1094 | ||
c0440b3f | 1095 | $oldid = $data->id; // need this saved for later |
76cfb124 | 1096 | |
c0440b3f EL |
1097 | $restorefiles = false; // Only if we end creating the group |
1098 | ||
1099 | // Search if the group already exists (by name & description) in the target course | |
1100 | $description_clause = ''; | |
1101 | $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name); | |
1102 | if (!empty($data->description)) { | |
1103 | $description_clause = ' AND ' . | |
d84fe4c8 EL |
1104 | $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description'); |
1105 | $params['description'] = $data->description; | |
c0440b3f EL |
1106 | } |
1107 | if (!$groupdb = $DB->get_record_sql("SELECT * | |
1108 | FROM {groups} | |
1109 | WHERE courseid = :courseid | |
1110 | AND name = :grname $description_clause", $params)) { | |
1111 | // group doesn't exist, create | |
1112 | $newitemid = $DB->insert_record('groups', $data); | |
1113 | $restorefiles = true; // We'll restore the files | |
1114 | } else { | |
1115 | // group exists, use it | |
1116 | $newitemid = $groupdb->id; | |
1117 | } | |
1118 | // Save the id mapping | |
1119 | $this->set_mapping('group', $oldid, $newitemid, $restorefiles); | |
e17dbeeb SH |
1120 | // Invalidate the course group data cache just in case. |
1121 | cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid)); | |
c0440b3f EL |
1122 | } |
1123 | ||
c0440b3f | 1124 | public function process_grouping($data) { |
71a50b13 EL |
1125 | global $DB; |
1126 | ||
1127 | $data = (object)$data; // handy | |
1128 | $data->courseid = $this->get_courseid(); | |
1129 | ||
74b714df ARN |
1130 | // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by |
1131 | // another a grouping in the same course | |
1132 | $context = context_course::instance($data->courseid); | |
128af106 | 1133 | if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { |
74b714df ARN |
1134 | if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) { |
1135 | unset($data->idnumber); | |
1136 | } | |
1137 | } else { | |
1138 | unset($data->idnumber); | |
1139 | } | |
1140 | ||
71a50b13 EL |
1141 | $oldid = $data->id; // need this saved for later |
1142 | $restorefiles = false; // Only if we end creating the grouping | |
1143 | ||
1144 | // Search if the grouping already exists (by name & description) in the target course | |
1145 | $description_clause = ''; | |
1146 | $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name); | |
1147 | if (!empty($data->description)) { | |
1148 | $description_clause = ' AND ' . | |
d84fe4c8 EL |
1149 | $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description'); |
1150 | $params['description'] = $data->description; | |
71a50b13 EL |
1151 | } |
1152 | if (!$groupingdb = $DB->get_record_sql("SELECT * | |
1153 | FROM {groupings} | |
1154 | WHERE courseid = :courseid | |
1155 | AND name = :grname $description_clause", $params)) { | |
1156 | // grouping doesn't exist, create | |
1157 | $newitemid = $DB->insert_record('groupings', $data); | |
1158 | $restorefiles = true; // We'll restore the files | |
1159 | } else { | |
1160 | // grouping exists, use it | |
1161 | $newitemid = $groupingdb->id; | |
1162 | } | |
1163 | // Save the id mapping | |
1164 | $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles); | |
e17dbeeb SH |
1165 | // Invalidate the course group data cache just in case. |
1166 | cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid)); | |
c0440b3f EL |
1167 | } |
1168 | ||
1169 | public function process_grouping_group($data) { | |
fdcf4a5f | 1170 | global $CFG; |
51e8d287 | 1171 | |
fdcf4a5f | 1172 | require_once($CFG->dirroot.'/group/lib.php'); |
51e8d287 AG |
1173 | |
1174 | $data = (object)$data; | |
1175 | groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded); | |
c0440b3f EL |
1176 | } |
1177 | ||
1178 | protected function after_execute() { | |
1179 | // Add group related files, matching with "group" mappings | |
1180 | $this->add_related_files('group', 'icon', 'group'); | |
1181 | $this->add_related_files('group', 'description', 'group'); | |
71a50b13 EL |
1182 | // Add grouping related files, matching with "grouping" mappings |
1183 | $this->add_related_files('grouping', 'description', 'grouping'); | |
e17dbeeb SH |
1184 | // Invalidate the course group data. |
1185 | cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid())); | |
c0440b3f EL |
1186 | } |
1187 | ||
1188 | } | |
1189 | ||
7881024e PS |
1190 | /** |
1191 | * Structure step that will create all the needed group memberships | |
1192 | * by loading them from the groups.xml file performing the required matches. | |
1193 | */ | |
1194 | class restore_groups_members_structure_step extends restore_structure_step { | |
1195 | ||
1196 | protected $plugins = null; | |
1197 | ||
1198 | protected function define_structure() { | |
1199 | ||
1200 | $paths = array(); // Add paths here | |
1201 | ||
868b086c | 1202 | if ($this->get_setting_value('groups') && $this->get_setting_value('users')) { |
7881024e PS |
1203 | $paths[] = new restore_path_element('group', '/groups/group'); |
1204 | $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member'); | |
1205 | } | |
1206 | ||
1207 | return $paths; | |
1208 | } | |
1209 | ||
1210 | public function process_group($data) { | |
1211 | $data = (object)$data; // handy | |
1212 | ||
1213 | // HACK ALERT! | |
1214 | // Not much to do here, this groups mapping should be already done from restore_groups_structure_step. | |
1215 | // Let's fake internal state to make $this->get_new_parentid('group') work. | |
1216 | ||
1217 | $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id)); | |
1218 | } | |
1219 | ||
1220 | public function process_member($data) { | |
1221 | global $DB, $CFG; | |
1222 | require_once("$CFG->dirroot/group/lib.php"); | |
1223 | ||
1224 | // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled. | |
1225 | ||
1226 | $data = (object)$data; // handy | |
1227 | ||
1228 | // get parent group->id | |
1229 | $data->groupid = $this->get_new_parentid('group'); | |
1230 | ||
1231 | // map user newitemid and insert if not member already | |
1232 | if ($data->userid = $this->get_mappingid('user', $data->userid)) { | |
1233 | if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) { | |
1234 | // Check the component, if any, exists. | |
1235 | if (empty($data->component)) { | |
1236 | groups_add_member($data->groupid, $data->userid); | |
1237 | ||
1238 | } else if ((strpos($data->component, 'enrol_') === 0)) { | |
1239 | // Deal with enrolment groups - ignore the component and just find out the instance via new id, | |
1240 | // it is possible that enrolment was restored using different plugin type. | |
1241 | if (!isset($this->plugins)) { | |
1242 | $this->plugins = enrol_get_plugins(true); | |
1243 | } | |
1244 | if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { | |
1245 | if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { | |
1246 | if (isset($this->plugins[$instance->enrol])) { | |
1247 | $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid); | |
1248 | } | |
1249 | } | |
1250 | } | |
1251 | ||
1252 | } else { | |
b0d1d941 | 1253 | $dir = core_component::get_component_directory($data->component); |
7881024e PS |
1254 | if ($dir and is_dir($dir)) { |
1255 | if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) { | |
1256 | return; | |
1257 | } | |
1258 | } | |
1259 | // Bad luck, plugin could not restore the data, let's add normal membership. | |
1260 | groups_add_member($data->groupid, $data->userid); | |
1261 | $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead."; | |
7881024e PS |
1262 | $this->log($message, backup::LOG_WARNING); |
1263 | } | |
1264 | } | |
1265 | } | |
1266 | } | |
1267 | } | |
1268 | ||
c0440b3f EL |
1269 | /** |
1270 | * Structure step that will create all the needed scales | |
1271 | * by loading them from the scales.xml | |
c0440b3f EL |
1272 | */ |
1273 | class restore_scales_structure_step extends restore_structure_step { | |
1274 | ||
1275 | protected function define_structure() { | |
1276 | ||
1277 | $paths = array(); // Add paths here | |
1278 | $paths[] = new restore_path_element('scale', '/scales_definition/scale'); | |
1279 | return $paths; | |
1280 | } | |
1281 | ||
1282 | protected function process_scale($data) { | |
1283 | global $DB; | |
1284 | ||
1285 | $data = (object)$data; | |
1286 | ||
1287 | $restorefiles = false; // Only if we end creating the group | |
1288 | ||
1289 | $oldid = $data->id; // need this saved for later | |
1290 | ||
1291 | // Look for scale (by 'scale' both in standard (course=0) and current course | |
1292 | // with priority to standard scales (ORDER clause) | |
1293 | // scale is not course unique, use get_record_sql to suppress warning | |
1294 | // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides | |
1295 | $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc'); | |
1296 | $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale); | |
1297 | if (!$scadb = $DB->get_record_sql("SELECT * | |
1298 | FROM {scale} | |
1299 | WHERE courseid IN (0, :courseid) | |
1300 | AND $compare_scale_clause | |
1301 | ORDER BY courseid", $params, IGNORE_MULTIPLE)) { | |
1302 | // Remap the user if possible, defaut to user performing the restore if not | |
1303 | $userid = $this->get_mappingid('user', $data->userid); | |
ba8bead5 | 1304 | $data->userid = $userid ? $userid : $this->task->get_userid(); |
c0440b3f EL |
1305 | // Remap the course if course scale |
1306 | $data->courseid = $data->courseid ? $this->get_courseid() : 0; | |
1307 | // If global scale (course=0), check the user has perms to create it | |
1308 | // falling to course scale if not | |
a689cd1d | 1309 | $systemctx = context_system::instance(); |
394edb7e | 1310 | if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) { |
c0440b3f EL |
1311 | $data->courseid = $this->get_courseid(); |
1312 | } | |
1313 | // scale doesn't exist, create | |
1314 | $newitemid = $DB->insert_record('scale', $data); | |
1315 | $restorefiles = true; // We'll restore the files | |
1316 | } else { | |
1317 | // scale exists, use it | |
1318 | $newitemid = $scadb->id; | |
1319 | } | |
1320 | // Save the id mapping (with files support at system context) | |
1321 | $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid()); | |
1322 | } | |
1323 | ||
1324 | protected function after_execute() { | |
1325 | // Add scales related files, matching with "scale" mappings | |
1326 | $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid()); | |
1327 | } | |
76cfb124 EL |
1328 | } |
1329 | ||
c0440b3f | 1330 | |
c8730ff0 EL |
1331 | /** |
1332 | * Structure step that will create all the needed outocomes | |
1333 | * by loading them from the outcomes.xml | |
1334 | */ | |
1335 | class restore_outcomes_structure_step extends restore_structure_step { | |
1336 | ||
1337 | protected function define_structure() { | |
1338 | ||
1339 | $paths = array(); // Add paths here | |
1340 | $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome'); | |
1341 | return $paths; | |
1342 | } | |
1343 | ||
1344 | protected function process_outcome($data) { | |
1345 | global $DB; | |
1346 | ||
1347 | $data = (object)$data; | |
1348 | ||
1349 | $restorefiles = false; // Only if we end creating the group | |
1350 | ||
1351 | $oldid = $data->id; // need this saved for later | |
1352 | ||
1353 | // Look for outcome (by shortname both in standard (courseid=null) and current course | |
1354 | // with priority to standard outcomes (ORDER clause) | |
1355 | // outcome is not course unique, use get_record_sql to suppress warning | |
1356 | $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname); | |
1357 | if (!$outdb = $DB->get_record_sql('SELECT * | |
1358 | FROM {grade_outcomes} | |
1359 | WHERE shortname = :shortname | |
1360 | AND (courseid = :courseid OR courseid IS NULL) | |
1361 | ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) { | |
1362 | // Remap the user | |
1363 | $userid = $this->get_mappingid('user', $data->usermodified); | |
ba8bead5 | 1364 | $data->usermodified = $userid ? $userid : $this->task->get_userid(); |
8d4e41f4 EL |
1365 | // Remap the scale |
1366 | $data->scaleid = $this->get_mappingid('scale', $data->scaleid); | |
c8730ff0 EL |
1367 | // Remap the course if course outcome |
1368 | $data->courseid = $data->courseid ? $this->get_courseid() : null; | |
1369 | // If global outcome (course=null), check the user has perms to create it | |
1370 | // falling to course outcome if not | |
a689cd1d | 1371 | $systemctx = context_system::instance(); |
394edb7e | 1372 | if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) { |
c8730ff0 EL |
1373 | $data->courseid = $this->get_courseid(); |
1374 | } | |
1375 | // outcome doesn't exist, create | |
1376 | $newitemid = $DB->insert_record('grade_outcomes', $data); | |
1377 | $restorefiles = true; // We'll restore the files | |
1378 | } else { | |
1379 | // scale exists, use it | |
1380 | $newitemid = $outdb->id; | |
1381 | } | |
1382 | // Set the corresponding grade_outcomes_courses record | |
1383 | $outcourserec = new stdclass(); | |
1384 | $outcourserec->courseid = $this->get_courseid(); | |
1385 | $outcourserec->outcomeid = $newitemid; | |
1386 | if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) { | |
1387 | $DB->insert_record('grade_outcomes_courses', $outcourserec); | |
1388 | } | |
1389 | // Save the id mapping (with files support at system context) | |
1390 | $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid()); | |
1391 | } | |
1392 | ||
1393 | protected function after_execute() { | |
1394 | // Add outcomes related files, matching with "outcome" mappings | |
1395 | $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid()); | |
1396 | } | |
1397 | } | |
1398 | ||
41941110 EL |
1399 | /** |
1400 | * Execution step that, *conditionally* (if there isn't preloaded information | |
1401 | * will load all the question categories and questions (header info only) | |
1402 | * to backup_temp_ids. They will be stored with "question_category" and | |
1403 | * "question" itemnames and with their original contextid and question category | |
1404 | * id as paremitemids | |
1405 | */ | |
1406 | class restore_load_categories_and_questions extends restore_execution_step { | |
1407 | ||
1408 | protected function define_execution() { | |
1409 | ||
1410 | if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do | |
1411 | return; | |
1412 | } | |
1413 | $file = $this->get_basepath() . '/questions.xml'; | |
1414 | restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file); | |
1415 | } | |
1416 | } | |
1417 | ||
1418 | /** | |
1419 | * Execution step that, *conditionally* (if there isn't preloaded information) | |
1420 | * will process all the needed categories and questions | |
1421 | * in order to decide and perform any action with them (create / map / error) | |
1422 | * Note: Any error will cause exception, as far as this is the same processing | |
1423 | * than the one into restore prechecks (that should have stopped process earlier) | |
1424 | */ | |
1425 | class restore_process_categories_and_questions extends restore_execution_step { | |
1426 | ||
1427 | protected function define_execution() { | |
1428 | ||
1429 | if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do | |
1430 | return; | |
1431 | } | |
1432 | restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite()); | |
1433 | } | |
1434 | } | |
1435 | ||
3223cc95 EL |
1436 | /** |
1437 | * Structure step that will read the section.xml creating/updating sections | |
1438 | * as needed, rebuilding course cache and other friends | |
1439 | */ | |
1440 | class restore_section_structure_step extends restore_structure_step { | |
27479b5c | 1441 | /** @var array Cache: Array of id => course format */ |
1442 | private static $courseformats = array(); | |
1443 | ||
1444 | /** | |
1445 | * Resets a static cache of course formats. Required for unit testing. | |
1446 | */ | |
1447 | public static function reset_caches() { | |
1448 | self::$courseformats = array(); | |
1449 | } | |
c8730ff0 | 1450 | |
3223cc95 | 1451 | protected function define_structure() { |
71cbb251 | 1452 | global $CFG; |
ce4dfd27 | 1453 | |
71cbb251 | 1454 | $paths = array(); |
ce4dfd27 | 1455 | |
71cbb251 EL |
1456 | $section = new restore_path_element('section', '/section'); |
1457 | $paths[] = $section; | |
1458 | if ($CFG->enableavailability) { | |
1459 | $paths[] = new restore_path_element('availability', '/section/availability'); | |
e01fbcf7 | 1460 | $paths[] = new restore_path_element('availability_field', '/section/availability_field'); |
ce4dfd27 | 1461 | } |
03604430 | 1462 | $paths[] = new restore_path_element('course_format_options', '/section/course_format_options'); |
ce4dfd27 | 1463 | |
71cbb251 EL |
1464 | // Apply for 'format' plugins optional paths at section level |
1465 | $this->add_plugin_structure('format', $section); | |
ce4dfd27 | 1466 | |
a66e8bb3 SC |
1467 | // Apply for 'local' plugins optional paths at section level |
1468 | $this->add_plugin_structure('local', $section); | |
1469 | ||
71cbb251 | 1470 | return $paths; |
3223cc95 EL |
1471 | } |
1472 | ||
1473 | public function process_section($data) { | |
71cbb251 | 1474 | global $CFG, $DB; |
3223cc95 EL |
1475 | $data = (object)$data; |
1476 | $oldid = $data->id; // We'll need this later | |
1477 | ||
1478 | $restorefiles = false; | |
1479 | ||
1480 | // Look for the section | |
1481 | $section = new stdclass(); | |
1482 | $section->course = $this->get_courseid(); | |
1483 | $section->section = $data->number; | |
1484 | // Section doesn't exist, create it with all the info from backup | |
1485 | if (!$secrec = $DB->get_record('course_sections', (array)$section)) { | |
1486 | $section->name = $data->name; | |
1487 | $section->summary = $data->summary; | |
1488 | $section->summaryformat = $data->summaryformat; | |
1489 | $section->sequence = ''; | |
1490 | $section->visible = $data->visible; | |
71cbb251 | 1491 | if (empty($CFG->enableavailability)) { // Process availability information only if enabled. |
38674ef9 | 1492 | $section->availability = null; |
71cbb251 | 1493 | } else { |
38674ef9 | 1494 | $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null; |
1495 | // Include legacy [<2.7] availability data if provided. | |
1496 | if (is_null($section->availability)) { | |
1497 | $section->availability = \core_availability\info::convert_legacy_fields( | |
1498 | $data, true); | |
1499 | } | |
71cbb251 | 1500 | } |
3223cc95 EL |
1501 | $newitemid = $DB->insert_record('course_sections', $section); |
1502 | $restorefiles = true; | |
1503 | ||
1504 | // Section exists, update non-empty information | |
1505 | } else { | |
1506 | $section->id = $secrec->id; | |
ff5d6f88 | 1507 | if ((string)$secrec->name === '') { |
3223cc95 EL |
1508 | $section->name = $data->name; |
1509 | } | |
1510 | if (empty($secrec->summary)) { | |
1511 | $section->summary = $data->summary; | |
1512 | $section->summaryformat = $data->summaryformat; | |
1513 | $restorefiles = true; | |
1514 | } | |
ce4dfd27 | 1515 | |
38674ef9 | 1516 | // Don't update availability (I didn't see a useful way to define |
1517 | // whether existing or new one should take precedence). | |
ce4dfd27 | 1518 | |
3223cc95 EL |
1519 | $DB->update_record('course_sections', $section); |
1520 | $newitemid = $secrec->id; | |
1521 | } | |
1522 | ||
1523 | // Annotate the section mapping, with restorefiles option if needed | |
1524 | $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles); | |
1525 | ||
a90659d6 EL |
1526 | // set the new course_section id in the task |
1527 | $this->task->set_sectionid($newitemid); | |
1528 | ||
38674ef9 | 1529 | // If there is the legacy showavailability data, store this for later use. |
1530 | // (This data is not present when restoring 'new' backups.) | |
1531 | if (isset($data->showavailability)) { | |
1532 | // Cache the showavailability flag using the backup_ids data field. | |
1533 | restore_dbops::set_backup_ids_record($this->get_restoreid(), | |
1534 | 'section_showavailability', $newitemid, 0, null, | |
1535 | (object)array('showavailability' => $data->showavailability)); | |
1536 | } | |
a90659d6 | 1537 | |
f81f5133 EL |
1538 | // Commented out. We never modify course->numsections as far as that is used |
1539 | // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x) | |
1540 | // Note: We keep the code here, to know about and because of the possibility of making this | |
1541 | // optional based on some setting/attribute in the future | |
3223cc95 | 1542 | // If needed, adjust course->numsections |
f81f5133 EL |
1543 | //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) { |
1544 | // if ($numsections < $section->section) { | |
1545 | // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid())); | |
1546 | // } | |
1547 | //} | |
3223cc95 EL |
1548 | } |
1549 | ||
38674ef9 | 1550 | /** |
1551 | * Process the legacy availability table record. This table does not exist | |
1552 | * in Moodle 2.7+ but we still support restore. | |
1553 | * | |
1554 | * @param stdClass $data Record data | |
1555 | */ | |
71cbb251 | 1556 | public function process_availability($data) { |
71cbb251 | 1557 | $data = (object)$data; |
38674ef9 | 1558 | // Simply going to store the whole availability record now, we'll process |
1559 | // all them later in the final task (once all activities have been restored) | |
1560 | // Let's call the low level one to be able to store the whole object. | |
71cbb251 | 1561 | $data->coursesectionid = $this->task->get_sectionid(); |
38674ef9 | 1562 | restore_dbops::set_backup_ids_record($this->get_restoreid(), |
1563 | 'section_availability', $data->id, 0, null, $data); | |
71cbb251 EL |
1564 | } |
1565 | ||
38674ef9 | 1566 | /** |
1567 | * Process the legacy availability fields table record. This table does not | |
1568 | * exist in Moodle 2.7+ but we still support restore. | |
1569 | * | |
1570 | * @param stdClass $data Record data | |
1571 | */ | |
e01fbcf7 MN |
1572 | public function process_availability_field($data) { |
1573 | global $DB; | |
1574 | $data = (object)$data; | |
1575 | // Mark it is as passed by default | |
1576 | $passed = true; | |
8ab1529d SH |
1577 | $customfieldid = null; |
1578 | ||
1579 | // If a customfield has been used in order to pass we must be able to match an existing | |
1580 | // customfield by name (data->customfield) and type (data->customfieldtype) | |
1581 | if (is_null($data->customfield) xor is_null($data->customfieldtype)) { | |
1582 | // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both. | |
1583 | // If one is null but the other isn't something clearly went wrong and we'll skip this condition. | |
1584 | $passed = false; | |
1585 | } else if (!is_null($data->customfield)) { | |
1586 | $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype); | |
1587 | $customfieldid = $DB->get_field('user_info_field', 'id', $params); | |
1588 | $passed = ($customfieldid !== false); | |
e01fbcf7 | 1589 | } |
8ab1529d | 1590 | |
e01fbcf7 MN |
1591 | if ($passed) { |
1592 | // Create the object to insert into the database | |
141d3c86 SH |
1593 | $availfield = new stdClass(); |
1594 | $availfield->coursesectionid = $this->task->get_sectionid(); | |
1595 | $availfield->userfield = $data->userfield; | |
8ab1529d | 1596 | $availfield->customfieldid = $customfieldid; |
141d3c86 SH |
1597 | $availfield->operator = $data->operator; |
1598 | $availfield->value = $data->value; | |
38674ef9 | 1599 | |
1600 | // Get showavailability option. | |
1601 | $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), | |
1602 | 'section_showavailability', $availfield->coursesectionid); | |
1603 | if (!$showrec) { | |
1604 | // Should not happen. | |
1605 | throw new coding_exception('No matching showavailability record'); | |
1606 | } | |
1607 | $show = $showrec->info->showavailability; | |
1608 | ||
1609 | // The $availfield object is now in the format used in the old | |
1610 | // system. Interpret this and convert to new system. | |
1611 | $currentvalue = $DB->get_field('course_sections', 'availability', | |
1612 | array('id' => $availfield->coursesectionid), MUST_EXIST); | |
1613 | $newvalue = \core_availability\info::add_legacy_availability_field_condition( | |
1614 | $currentvalue, $availfield, $show); | |
1615 | $DB->set_field('course_sections', 'availability', $newvalue, | |
1616 | array('id' => $availfield->coursesectionid)); | |
e01fbcf7 MN |
1617 | } |
1618 | } | |
1619 | ||
03604430 MG |
1620 | public function process_course_format_options($data) { |
1621 | global $DB; | |
4012617f | 1622 | $courseid = $this->get_courseid(); |
27479b5c | 1623 | if (!array_key_exists($courseid, self::$courseformats)) { |
4012617f | 1624 | // It is safe to have a static cache of course formats because format can not be changed after this point. |
27479b5c | 1625 | self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid)); |
4012617f MG |
1626 | } |
1627 | $data = (array)$data; | |
27479b5c | 1628 | if (self::$courseformats[$courseid] === $data['format']) { |
4012617f MG |
1629 | // Import section format options only if both courses (the one that was backed up |
1630 | // and the one we are restoring into) have same formats. | |
1631 | $params = array( | |
1632 | 'courseid' => $this->get_courseid(), | |
1633 | 'sectionid' => $this->task->get_sectionid(), | |
1634 | 'format' => $data['format'], | |
1635 | 'name' => $data['name'] | |
1636 | ); | |
1637 | if ($record = $DB->get_record('course_format_options', $params, 'id, value')) { | |
1638 | // Do not overwrite existing information. | |
1639 | $newid = $record->id; | |
1640 | } else { | |
1641 | $params['value'] = $data['value']; | |
1642 | $newid = $DB->insert_record('course_format_options', $params); | |
1643 | } | |
1644 | $this->set_mapping('course_format_options', $data['id'], $newid); | |
1645 | } | |
03604430 MG |
1646 | } |
1647 | ||
3223cc95 EL |
1648 | protected function after_execute() { |
1649 | // Add section related files, with 'course_section' itemid to match | |
1650 | $this->add_related_files('course', 'section', 'course_section'); | |
1651 | } | |
1652 | } | |
1653 | ||
3223cc95 | 1654 | /** |
482aac65 | 1655 | * Structure step that will read the course.xml file, loading it and performing |
395dae30 EL |
1656 | * various actions depending of the site/restore settings. Note that target |
1657 | * course always exist before arriving here so this step will be updating | |
1658 | * the course record (never inserting) | |
482aac65 EL |
1659 | */ |
1660 | class restore_course_structure_step extends restore_structure_step { | |
9665ecd2 TH |
1661 | /** |
1662 | * @var bool this gets set to true by {@link process_course()} if we are | |
1663 | * restoring an old coures that used the legacy 'module security' feature. | |
1664 | * If so, we have to do more work in {@link after_execute()}. | |
1665 | */ | |
1666 | protected $legacyrestrictmodules = false; | |
1667 | ||
1668 | /** | |
1669 | * @var array Used when {@link $legacyrestrictmodules} is true. This is an | |
1670 | * array with array keys the module names ('forum', 'quiz', etc.). These are | |
1671 | * the modules that are allowed according to the data in the backup file. | |
1672 | * In {@link after_execute()} we then have to prevent adding of all the other | |
1673 | * types of activity. | |
1674 | */ | |
1675 | protected $legacyallowedmodules = array(); | |
482aac65 EL |
1676 | |
1677 | protected function define_structure() { | |
1678 | ||
4fda584f | 1679 | $course = new restore_path_element('course', '/course'); |
482aac65 EL |
1680 | $category = new restore_path_element('category', '/course/category'); |
1681 | $tag = new restore_path_element('tag', '/course/tags/tag'); | |
4fda584f | 1682 | $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module'); |
482aac65 | 1683 | |
4fda584f EL |
1684 | // Apply for 'format' plugins optional paths at course level |
1685 | $this->add_plugin_structure('format', $course); | |
1686 | ||
89213d00 | 1687 | // Apply for 'theme' plugins optional paths at course level |
1688 | $this->add_plugin_structure('theme', $course); | |
1689 | ||
158e9e2a PS |
1690 | // Apply for 'report' plugins optional paths at course level |
1691 | $this->add_plugin_structure('report', $course); | |
1692 | ||
5e0dae12 | 1693 | // Apply for 'course report' plugins optional paths at course level |
1694 | $this->add_plugin_structure('coursereport', $course); | |
1695 | ||
571ae252 DM |
1696 | // Apply for plagiarism plugins optional paths at course level |
1697 | $this->add_plugin_structure('plagiarism', $course); | |
1698 | ||
a66e8bb3 SC |
1699 | // Apply for local plugins optional paths at course level |
1700 | $this->add_plugin_structure('local', $course); | |
1701 | ||
a495d1a1 FM |
1702 | // Apply for admin tool plugins optional paths at course level. |
1703 | $this->add_plugin_structure('tool', $course); | |
1704 | ||
4fda584f | 1705 | return array($course, $category, $tag, $allowed_module); |
482aac65 EL |
1706 | } |
1707 | ||
7f32340b SH |
1708 | /** |
1709 | * Processing functions go here | |
1710 | * | |
1711 | * @global moodledatabase $DB | |
1712 | * @param stdClass $data | |
1713 | */ | |
482aac65 | 1714 | public function process_course($data) { |
395dae30 | 1715 | global $CFG, $DB; |
68bf1ff4 FM |
1716 | $context = context::instance_by_id($this->task->get_contextid()); |
1717 | $userid = $this->task->get_userid(); | |
1718 | $target = $this->get_task()->get_target(); | |
1719 | $isnewcourse = $target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING; | |
1720 | ||
1721 | // When restoring to a new course we can set all the things except for the ID number. | |
1722 | $canchangeidnumber = $isnewcourse || has_capability('moodle/course:changeidnumber', $context, $userid); | |
1723 | $canchangeshortname = $isnewcourse || has_capability('moodle/course:changeshortname', $context, $userid); | |
1724 | $canchangefullname = $isnewcourse || has_capability('moodle/course:changefullname', $context, $userid); | |
1725 | $canchangesummary = $isnewcourse || has_capability('moodle/course:changesummary', $context, $userid); | |
395dae30 EL |
1726 | |
1727 | $data = (object)$data; | |
68bf1ff4 | 1728 | $data->id = $this->get_courseid(); |
785d6603 SH |
1729 | |
1730 | $fullname = $this->get_setting_value('course_fullname'); | |
1731 | $shortname = $this->get_setting_value('course_shortname'); | |
b1eaf633 | 1732 | $startdate = $this->get_setting_value('course_startdate'); |
395dae30 | 1733 | |
68bf1ff4 | 1734 | // Calculate final course names, to avoid dupes. |
395dae30 EL |
1735 | list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname); |
1736 | ||
68bf1ff4 FM |
1737 | if ($canchangefullname) { |
1738 | $data->fullname = $fullname; | |
1739 | } else { | |
1740 | unset($data->fullname); | |
1741 | } | |
1742 | ||
1743 | if ($canchangeshortname) { | |
1744 | $data->shortname = $shortname; | |
1745 | } else { | |
1746 | unset($data->shortname); | |
1747 | } | |
1748 | ||
1749 | if (!$canchangesummary) { | |
1750 | unset($data->summary); | |
1751 | unset($data->summaryformat); | |
1752 | } | |
7d7d82de | 1753 | |
7d908d33 | 1754 | // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by |
1755 | // another course on this site. | |
68bf1ff4 FM |
1756 | if (!empty($data->idnumber) && $canchangeidnumber && $this->task->is_samesite() |
1757 | && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) { | |
7d908d33 | 1758 | // Do not reset idnumber. |
68bf1ff4 FM |
1759 | |
1760 | } else if (!$isnewcourse) { | |
1761 | // Prevent override when restoring as merge. | |
1762 | unset($data->idnumber); | |
1763 | ||
7d7d82de | 1764 | } else { |
7d908d33 | 1765 | $data->idnumber = ''; |
7d7d82de | 1766 | } |
7f32340b | 1767 | |
ee1dc835 EL |
1768 | // Any empty value for course->hiddensections will lead to 0 (default, show collapsed). |
1769 | // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532 | |
1770 | if (empty($data->hiddensections)) { | |
1771 | $data->hiddensections = 0; | |
1772 | } | |
1773 | ||
8149d624 SH |
1774 | // Set legacyrestrictmodules to true if the course was resticting modules. If so |
1775 | // then we will need to process restricted modules after execution. | |
9665ecd2 | 1776 | $this->legacyrestrictmodules = !empty($data->restrictmodules); |
e4f72d14 | 1777 | |
395dae30 EL |
1778 | $data->startdate= $this->apply_date_offset($data->startdate); |
1779 | if ($data->defaultgroupingid) { | |
1780 | $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid); | |
1781 | } | |
5095f325 | 1782 | if (empty($CFG->enablecompletion)) { |
395dae30 EL |
1783 | $data->enablecompletion = 0; |
1784 | $data->completionstartonenrol = 0; | |
1785 | $data->completionnotify = 0; | |
1786 | } | |
1787 | $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search | |
1788 | if (!array_key_exists($data->lang, $languages)) { | |
1789 | $data->lang = ''; | |
1790 | } | |
89213d00 | 1791 | |
395dae30 | 1792 | $themes = get_list_of_themes(); // Get themes for quick search later |
89213d00 | 1793 | if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) { |
395dae30 EL |
1794 | $data->theme = ''; |
1795 | } | |
1796 | ||
3d1808c6 DM |
1797 | // Check if this is an old SCORM course format. |
1798 | if ($data->format == 'scorm') { | |
1799 | $data->format = 'singleactivity'; | |
1800 | $data->activitytype = 'scorm'; | |
1801 | } | |
1802 | ||
395dae30 EL |
1803 | // Course record ready, update it |
1804 | $DB->update_record('course', $data); | |
1805 | ||
d6cd57de MG |
1806 | course_get_format($data)->update_course_format_options($data); |
1807 | ||
4fda584f EL |
1808 | // Role name aliases |
1809 | restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid()); | |
1810 | } | |
1811 | ||
1812 | public function process_category($data) { | |
1813 | // Nothing to do with the category. UI sets it before restore starts | |
1814 | } | |
1815 | ||
1816 | public function process_tag($data) { | |
1817 | global $CFG, $DB; | |
1818 | ||
1819 | $data = (object)$data; | |
1820 | ||
74fa9f76 MG |
1821 | core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(), |
1822 | context_course::instance($this->get_courseid()), $data->rawname); | |
4fda584f EL |
1823 | } |
1824 | ||
1825 | public function process_allowed_module($data) { | |
4fda584f EL |
1826 | $data = (object)$data; |
1827 | ||
9665ecd2 TH |
1828 | // Backwards compatiblity support for the data that used to be in the |
1829 | // course_allowed_modules table. | |
1830 | if ($this->legacyrestrictmodules) { | |
1831 | $this->legacyallowedmodules[$data->modulename] = 1; | |
395dae30 | 1832 | } |
482aac65 EL |
1833 | } |
1834 | ||
395dae30 | 1835 | protected function after_execute() { |
9665ecd2 TH |
1836 | global $DB; |
1837 | ||
395dae30 EL |
1838 | // Add course related files, without itemid to match |
1839 | $this->add_related_files('course', 'summary', null); | |
d1f8c1bd | 1840 | $this->add_related_files('course', 'overviewfiles', null); |
9665ecd2 TH |
1841 | |
1842 | // Deal with legacy allowed modules. | |
1843 | if ($this->legacyrestrictmodules) { | |
1844 | $context = context_course::instance($this->get_courseid()); | |
1845 | ||
1846 | list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities'); | |
1847 | list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config'); | |
1848 | foreach ($managerroleids as $roleid) { | |
1849 | unset($roleids[$roleid]); | |
1850 | } | |
1851 | ||
bd3b3bba | 1852 | foreach (core_component::get_plugin_list('mod') as $modname => $notused) { |
9665ecd2 TH |
1853 | if (isset($this->legacyallowedmodules[$modname])) { |
1854 | // Module is allowed, no worries. | |
1855 | continue; | |
1856 | } | |
1857 | ||
1858 | $capability = 'mod/' . $modname . ':addinstance'; | |
1859 | foreach ($roleids as $roleid) { | |
1860 | assign_capability($capability, CAP_PREVENT, $roleid, $context); | |
1861 | } | |
1862 | } | |
1863 | } | |
395dae30 | 1864 | } |
482aac65 | 1865 | } |
024c288d | 1866 | |
c9deaa8e EM |
1867 | /** |
1868 | * Execution step that will migrate legacy files if present. | |
1869 | */ | |
1870 | class restore_course_legacy_files_step extends restore_execution_step { | |
1871 | public function define_execution() { | |
1872 | global $DB; | |
1873 | ||
1874 | // Do a check for legacy files and skip if there are none. | |
1875 | $sql = 'SELECT count(*) | |
1876 | FROM {backup_files_temp} | |
1877 | WHERE backupid = ? | |
1878 | AND contextid = ? | |
1879 | AND component = ? | |
1880 | AND filearea = ?'; | |
1881 | $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy'); | |
1882 | ||
1883 | if ($DB->count_records_sql($sql, $params)) { | |
1884 | $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid())); | |
1885 | restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course', | |
1886 | 'legacy', $this->task->get_old_contextid(), $this->task->get_userid()); | |
1887 | } | |
1888 | } | |
1889 | } | |
024c288d EL |
1890 | |
1891 | /* | |
1892 | * Structure step that will read the roles.xml file (at course/activity/block levels) | |
7a7b8a1f | 1893 | * containing all the role_assignments and overrides for that context. If corresponding to |
024c288d EL |
1894 | * one mapped role, they will be applied to target context. Will observe the role_assignments |
1895 | * setting to decide if ras are restored. | |
7a7b8a1f PS |
1896 | * |
1897 | * Note: this needs to be executed after all users are enrolled. | |
024c288d EL |
1898 | */ |
1899 | class restore_ras_and_caps_structure_step extends restore_structure_step { | |
7a7b8a1f | 1900 | protected $plugins = null; |
024c288d EL |
1901 | |
1902 | protected function define_structure() { | |
1903 | ||
1904 | $paths = array(); | |
1905 | ||
1906 | // Observe the role_assignments setting | |
1907 | if ($this->get_setting_value('role_assignments')) { | |
1908 | $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment'); | |
1909 | } | |
1910 | $paths[] = new restore_path_element('override', '/roles/role_overrides/override'); | |
1911 | ||
1912 | return $paths; | |
1913 | } | |
1914 | ||
f2a9be5f EL |
1915 | /** |
1916 | * Assign roles | |
1917 | * | |
1918 | * This has to be called after enrolments processing. | |
1919 | * | |
1920 | * @param mixed $data | |
1921 | * @return void | |
1922 | */ | |
024c288d | 1923 | public function process_assignment($data) { |
28b6ff82 EL |
1924 | global $DB; |
1925 | ||
024c288d EL |
1926 | $data = (object)$data; |
1927 | ||
1928 | // Check roleid, userid are one of the mapped ones | |
f2a9be5f EL |
1929 | if (!$newroleid = $this->get_mappingid('role', $data->roleid)) { |
1930 | return; | |
1931 | } | |
1932 | if (!$newuserid = $this->get_mappingid('user', $data->userid)) { | |
1933 | return; | |
1934 | } | |
1935 | if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) { | |
28b6ff82 | 1936 | // Only assign roles to not deleted users |
f2a9be5f EL |
1937 | return; |
1938 | } | |
1939 | if (!$contextid = $this->task->get_contextid()) { | |
1940 | return; | |
1941 | } | |
1942 | ||
1943 | if (empty($data->component)) { | |
1944 | // assign standard manual roles | |
1945 | // TODO: role_assign() needs one userid param to be able to specify our restore userid | |
1946 | role_assign($newroleid, $newuserid, $contextid); | |
1947 | ||
1948 | } else if ((strpos($data->component, 'enrol_') === 0)) { | |
7a7b8a1f PS |
1949 | // Deal with enrolment roles - ignore the component and just find out the instance via new id, |
1950 | // it is possible that enrolment was restored using different plugin type. | |
1951 | if (!isset($this->plugins)) { | |
2fbfdfd0 | 1952 | $this->plugins = enrol_get_plugins(true); |
7a7b8a1f | 1953 | } |
f2a9be5f | 1954 | if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { |
7a7b8a1f | 1955 | if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { |
2fbfdfd0 PS |
1956 | if (isset($this->plugins[$instance->enrol])) { |
1957 | $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid); | |
f2a9be5f EL |
1958 | } |
1959 | } | |
28b6ff82 | 1960 | } |
7881024e PS |
1961 | |
1962 | } else { | |
1963 | $data->roleid = $newroleid; | |
1964 | $data->userid = $newuserid; | |
1965 | $data->contextid = $contextid; | |
b0d1d941 | 1966 | $dir = core_component::get_component_directory($data->component); |
7881024e PS |
1967 | if ($dir and is_dir($dir)) { |
1968 | if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) { | |
1969 | return; | |
1970 | } | |
1971 | } | |
1972 | // Bad luck, plugin could not restore the data, let's add normal membership. | |
1973 | role_assign($data->roleid, $data->userid, $data->contextid); | |
1974 | $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead."; | |
7881024e | 1975 | $this->log($message, backup::LOG_WARNING); |
024c288d EL |
1976 | } |
1977 | } | |
1978 | ||
1979 | public function process_override($data) { | |
1980 | $data = (object)$data; | |
1981 | ||
1982 | // Check roleid is one of the mapped ones | |
1983 | $newroleid = $this->get_mappingid('role', $data->roleid); | |
b8e455a7 EL |
1984 | // If newroleid and context are valid assign it via API (it handles dupes and so on) |
1985 | if ($newroleid && $this->task->get_contextid()) { | |
024c288d | 1986 | // TODO: assign_capability() needs one userid param to be able to specify our restore userid |
b8e455a7 | 1987 | // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ??? |
024c288d EL |
1988 | assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid()); |
1989 | } | |
1990 | } | |
1991 | } | |
1992 | ||
4b75f49a PS |
1993 | /** |
1994 | * If no instances yet add default enrol methods the same way as when creating new course in UI. | |
1995 | */ | |
1996 | class restore_default_enrolments_step extends restore_execution_step { | |
03c39daa | 1997 | |
4b75f49a PS |
1998 | public function define_execution() { |
1999 | global $DB; | |
2000 | ||
03c39daa DM |
2001 | // No enrolments in front page. |
2002 | if ($this->get_courseid() == SITEID) { | |
2003 | return; | |
2004 | } | |
2005 | ||
4b75f49a PS |
2006 | $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST); |
2007 | ||
2008 | if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) { | |
2009 | // Something already added instances, do not add default instances. | |
2010 | $plugins = enrol_get_plugins(true); | |
2011 | foreach ($plugins as $plugin) { | |
2012 | $plugin->restore_sync_course($course); | |
2013 | } | |
2014 | ||
2015 | } else { | |
2016 | // Looks like a newly created course. | |
2017 | enrol_course_updated(true, $course, null); | |
2018 | } | |
2019 | } | |
2020 | } | |
2021 | ||
024c288d EL |
2022 | /** |
2023 | * This structure steps restores the enrol plugins and their underlying | |
2024 | * enrolments, performing all the mappings and/or movements required | |
2025 | */ | |
2026 | class restore_enrolments_structure_step extends restore_structure_step { | |
7a7b8a1f PS |
2027 | protected $enrolsynced = false; |
2028 | protected $plugins = null; | |
2029 | protected $originalstatus = array(); | |
024c288d | 2030 | |
9ab5df6b EL |
2031 | /** |
2032 | * Conditionally decide if this step should be executed. | |
2033 | * | |
2034 | * This function checks the following parameter: | |
2035 | * | |
2036 | * 1. the course/enrolments.xml file exists | |
2037 | * | |
2038 | * @return bool true is safe to execute, false otherwise | |
2039 | */ | |
2040 | protected function execute_condition() { | |
2041 | ||
03c39daa DM |
2042 | if ($this->get_courseid() == SITEID) { |
2043 | return false; | |
2044 | } | |
2045 | ||
9ab5df6b EL |
2046 | // Check it is included in the backup |
2047 | $fullpath = $this->task->get_taskbasepath(); | |
2048 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
2049 | if (!file_exists($fullpath)) { | |
2050 | // Not found, can't restore enrolments info | |
2051 | return false; | |
2052 | } | |
2053 | ||
2054 | return true; | |
2055 | } | |
2056 | ||
024c288d EL |
2057 | protected function define_structure() { |
2058 | ||
f6199295 MP |
2059 | $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol'); |
2060 | $enrolment = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment'); | |
2061 | // Attach local plugin stucture to enrol element. | |
2062 | $this->add_plugin_structure('enrol', $enrol); | |
024c288d | 2063 | |
f6199295 | 2064 | return array($enrol, $enrolment); |
024c288d EL |
2065 | } |
2066 | ||
f2a9be5f EL |
2067 | /** |
2068 | * Create enrolment instances. | |
2069 | * | |
2070 | * This has to be called after creation of roles | |
2071 | * and before adding of role assignments. | |
2072 | * | |
2073 | * @param mixed $data | |
2074 | * @return void | |
2075 | */ | |
024c288d EL |
2076 | public function process_enrol($data) { |
2077 | global $DB; | |
2078 | ||
2079 | $data = (object)$data; | |
7a7b8a1f PS |
2080 | $oldid = $data->id; // We'll need this later. |
2081 | unset($data->id); | |
024c288d | 2082 | |
7a7b8a1f | 2083 | $this->originalstatus[$oldid] = $data->status; |
f2a9be5f | 2084 | |
7a7b8a1f | 2085 | if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) { |
f2a9be5f | 2086 | $this->set_mapping('enrol', $oldid, 0); |
024c288d EL |
2087 | return; |
2088 | } | |
2089 | ||
7a7b8a1f PS |
2090 | if (!isset($this->plugins)) { |
2091 | $this->plugins = enrol_get_plugins(true); | |
024c288d | 2092 | } |
7a7b8a1f PS |
2093 | |
2094 | if (!$this->enrolsynced) { | |
2095 | // Make sure that all plugin may create instances and enrolments automatically | |
2096 | // before the first instance restore - this is suitable especially for plugins | |
2097 | // that synchronise data automatically using course->idnumber or by course categories. | |
2098 | foreach ($this->plugins as $plugin) { | |
2099 | $plugin->restore_sync_course($courserec); | |
2100 | } | |
2101 | $this->enrolsynced = true; | |
f2a9be5f EL |
2102 | } |
2103 | ||
7a7b8a1f PS |
2104 | // Map standard fields - plugin has to process custom fields manually. |
2105 | $data->roleid = $this->get_mappingid('role', $data->roleid); | |
2106 | $data->courseid = $courserec->id; | |
f2a9be5f | 2107 | |
7a7b8a1f PS |
2108 | if ($this->get_setting_value('enrol_migratetomanual')) { |
2109 | unset($data->sortorder); // Remove useless sortorder from <2.4 backups. | |
2110 | if (!enrol_is_enabled('manual')) { | |
2111 | $this->set_mapping('enrol', $oldid, 0); | |
2112 | return; | |
2113 | } | |
2114 | if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) { | |
2115 | $instance = reset($instances); | |
2116 | $this->set_mapping('enrol', $oldid, $instance->id); | |
024c288d | 2117 | } else { |
7a7b8a1f PS |
2118 | if ($data->enrol === 'manual') { |
2119 | $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data); | |
2120 | } else { | |
2121 | $instanceid = $this->plugins['manual']->add_default_instance($courserec); | |
2122 | } | |
2123 | $this->set_mapping('enrol', $oldid, $instanceid); | |
024c288d EL |
2124 | } |
2125 | ||
7a7b8a1f PS |
2126 | } else { |
2127 | if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) { | |
7a7b8a1f | 2128 | $this->set_mapping('enrol', $oldid, 0); |
7881024e | 2129 | $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments"; |
7881024e | 2130 | $this->log($message, backup::LOG_WARNING); |
7a7b8a1f PS |
2131 | return; |
2132 | } | |
2133 | if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) { | |
2134 | // Let's keep the sortorder in old backups. | |
2135 | } else { | |
2136 | // Prevent problems with colliding sortorders in old backups, | |
2137 | // new 2.4 backups do not need sortorder because xml elements are ordered properly. | |
2138 | unset($data->sortorder); | |
2139 | } | |
2140 | // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type. | |
2141 | $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid); | |
024c288d | 2142 | } |
024c288d EL |
2143 | } |
2144 | ||
f2a9be5f | 2145 | /** |
7a7b8a1f | 2146 | * Create user enrolments. |
f2a9be5f EL |
2147 | * |
2148 | * This has to be called after creation of enrolment instances | |
2149 | * and before adding of role assignments. | |
2150 | * | |
7a7b8a1f PS |
2151 | * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards. |
2152 | * | |
f2a9be5f EL |
2153 | * @param mixed $data |
2154 | * @return void | |
2155 | */ | |
024c288d EL |
2156 | public function process_enrolment($data) { |
2157 | global $DB; | |
2158 | ||
7a7b8a1f PS |
2159 | if (!isset($this->plugins)) { |
2160 | $this->plugins = enrol_get_plugins(true); | |
2161 | } | |
2162 | ||
024c288d EL |
2163 | $data = (object)$data; |
2164 | ||
7a7b8a1f | 2165 | // Process only if parent instance have been mapped. |
024c288d | 2166 | if ($enrolid = $this->get_new_parentid('enrol')) { |
7a7b8a1f PS |
2167 | $oldinstancestatus = ENROL_INSTANCE_ENABLED; |
2168 | $oldenrolid = $this->get_old_parentid('enrol'); | |
2169 | if (isset($this->originalstatus[$oldenrolid])) { | |
2170 | $oldinstancestatus = $this->originalstatus[$oldenrolid]; | |
2171 | } | |
f2a9be5f | 2172 | if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { |
7a7b8a1f | 2173 | // And only if user is a mapped one. |
f2a9be5f | 2174 | if ($userid = $this->get_mappingid('user', $data->userid)) { |
7a7b8a1f PS |
2175 | if (isset($this->plugins[$instance->enrol])) { |
2176 | $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus); | |
2177 | } | |
024c288d EL |
2178 | } |
2179 | } | |
2180 | } | |
2181 | } | |
2182 | } | |
21e51c86 EL |
2183 | |
2184 | ||
73d000f3 PS |
2185 | /** |
2186 | * Make sure the user restoring the course can actually access it. | |
2187 | */ | |
2188 | class restore_fix_restorer_access_step extends restore_execution_step { | |
2189 | protected function define_execution() { | |
2190 | global $CFG, $DB; | |
2191 | ||
2192 | if (!$userid = $this->task->get_userid()) { | |
2193 | return; | |
2194 | } | |
2195 | ||
2196 | if (empty($CFG->restorernewroleid)) { | |
2197 | // Bad luck, no fallback role for restorers specified | |
2198 | return; | |
2199 | } | |
2200 | ||
2201 | $courseid = $this->get_courseid(); | |
2202 | $context = context_course::instance($courseid); | |
2203 | ||
2204 | if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { | |
2205 | // Current user may access the course (admin, category manager or restored teacher enrolment usually) | |
2206 | return; | |
2207 | } | |
2208 | ||
2209 | // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled | |
2210 | role_assign($CFG->restorernewroleid, $userid, $context); | |
2211 | ||
2212 | if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { | |
2213 | // Extra role is enough, yay! | |
2214 | return; | |
2215 | } | |
2216 | ||
2217 | // The last chance is to create manual enrol if it does not exist and and try to enrol the current user, | |
2218 | // hopefully admin selected suitable $CFG->restorernewroleid ... | |
2219 | if (!enrol_is_enabled('manual')) { | |
2220 | return; | |
2221 | } | |
2222 | if (!$enrol = enrol_get_plugin('manual')) { | |
2223 | return; | |
2224 | } | |
2225 | if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) { | |
2226 | $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); | |
2227 | $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0)); | |
2228 | $enrol->add_instance($course, $fields); | |
2229 | } | |
2230 | ||
2231 | enrol_try_internal_enrol($courseid, $userid); | |
2232 | } | |
2233 | } | |
2234 | ||
2235 | ||
21e51c86 EL |
2236 | /** |
2237 | * This structure steps restores the filters and their configs | |
2238 | */ | |
2239 | class restore_filters_structure_step extends restore_structure_step { | |
2240 | ||
2241 | protected function define_structure() { | |
2242 | ||
2243 | $paths = array(); | |
2244 | ||
2245 | $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active'); | |
2246 | $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config'); | |
2247 | ||
2248 | return $paths; | |
2249 | } | |
2250 | ||
2251 | public function process_active($data) { | |
2252 | ||
2253 | $data = (object)$data; | |
2254 | ||
0662bd67 PS |
2255 | if (strpos($data->filter, 'filter/') === 0) { |
2256 | $data->filter = substr($data->filter, 7); | |
2257 | ||
2258 | } else if (strpos($data->filter, '/') !== false) { | |
2259 | // Unsupported old filter. | |
2260 | return; | |
2261 | } | |
2262 | ||
21e51c86 EL |
2263 | if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do |
2264 | return; | |
2265 | } | |
2266 | filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active); | |
2267 | } | |
2268 | ||
2269 | public function process_config($data) { | |
2270 | ||
2271 | $data = (object)$data; | |
2272 | ||
0662bd67 PS |
2273 | if (strpos($data->filter, 'filter/') === 0) { |
2274 | $data->filter = substr($data->filter, 7); | |
2275 | ||
2276 | } else if (strpos($data->filter, '/') !== false) { | |
2277 | // Unsupported old filter. | |
2278 | return; | |
2279 | } | |
2280 | ||
21e51c86 EL |
2281 | if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do |
2282 | return; | |
2283 | } | |
2284 | filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value); | |
2285 | } | |
2286 | } | |
2287 | ||
2288 | ||
2289 | /** | |
2290 | * This structure steps restores the comments | |
2291 | * Note: Cannot use the comments API because defaults to USER->id. | |
2292 | * That should change allowing to pass $userid | |
2293 | */ | |
2294 | class restore_comments_structure_step extends restore_structure_step { | |
2295 | ||
2296 | protected function define_structure() { | |
2297 | ||
2298 | $paths = array(); | |
2299 | ||
2300 | $paths[] = new restore_path_element('comment', '/comments/comment'); | |
2301 | ||
2302 | return $paths; | |
2303 | } | |
2304 | ||
2305 | public function process_comment($data) { | |
2306 | global $DB; | |
2307 | ||
2308 | $data = (object)$data; | |
2309 | ||
2310 | // First of all, if the comment has some itemid, ask to the task what to map | |
2311 | $mapping = false; | |
21e51c86 | 2312 | if ($data->itemid) { |
39aa0280 EL |
2313 | $mapping = $this->task->get_comment_mapping_itemname($data->commentarea); |
2314 | $data->itemid = $this->get_mappingid($mapping, $data->itemid); | |
21e51c86 EL |
2315 | } |
2316 | // Only restore the comment if has no mapping OR we have found the matching mapping | |
39aa0280 | 2317 | if (!$mapping || $data->itemid) { |
b8e455a7 EL |
2318 | // Only if user mapping and context |
2319 | $data->userid = $this->get_mappingid('user', $data->userid); | |
2320 | if ($data->userid && $this->task->get_contextid()) { | |
21e51c86 | 2321 | $data->contextid = $this->task->get_contextid(); |
b8e455a7 EL |
2322 | // Only if there is another comment with same context/user/timecreated |
2323 | $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated); | |
2324 | if (!$DB->record_exists('comments', $params)) { | |
2325 | $DB->insert_record('comments', $data); | |
2326 | } | |
2327 | } | |
2328 | } | |
2329 | } | |
2330 | } | |
2331 | ||
2832093f YB |
2332 | /** |
2333 | * This structure steps restores the badges and their configs | |
2334 | */ | |
2335 | class restore_badges_structure_step extends restore_structure_step { | |
2336 | ||
2337 | /** | |
2338 | * Conditionally decide if this step should be executed. | |
2339 | * | |
2340 | * This function checks the following parameters: | |
2341 | * | |
2342 | * 1. Badges and course badges are enabled on the site. | |
2343 | * 2. The course/badges.xml file exists. | |
2344 | * 3. All modules are restorable. | |
2345 | * 4. All modules are marked for restore. | |
2346 | * | |
2347 | * @return bool True is safe to execute, false otherwise | |
2348 | */ | |
2349 | protected function execute_condition() { | |
2350 | global $CFG; | |
2351 | ||
2352 | // First check is badges and course level badges are enabled on this site. | |
2353 | if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) { | |
2354 | // Disabled, don't restore course badges. | |
2355 | return false; | |
2356 | } | |
2357 | ||
2358 | // Check if badges.xml is included in the backup. | |
2359 | $fullpath = $this->task->get_taskbasepath(); | |
2360 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
2361 | if (!file_exists($fullpath)) { | |
2362 | // Not found, can't restore course badges. | |
2363 | return false; | |
2364 | } | |
2365 | ||
2366 | // Check we are able to restore all backed up modules. | |
2367 | if ($this->task->is_missing_modules()) { | |
2368 | return false; | |
2369 | } | |
2370 | ||
2371 | // Finally check all modules within the backup are being restored. | |
2372 | if ($this->task->is_excluding_activities()) { | |
2373 | return false; | |
2374 | } | |
2375 | ||
2376 | return true; | |
2377 | } | |
2378 | ||
2379 | protected function define_structure() { | |
2380 | $paths = array(); | |
2381 | $paths[] = new restore_path_element('badge', '/badges/badge'); | |
2382 | $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion'); | |
2383 | $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter'); | |
bd0d2bdc | 2384 | $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award'); |
2832093f YB |
2385 | |
2386 | return $paths; | |
2387 | } | |
2388 | ||
2389 | public function process_badge($data) { | |
2390 | global $DB, $CFG; | |
2391 | ||
bd0d2bdc | 2392 | require_once($CFG->libdir . '/badgeslib.php'); |
2832093f YB |
2393 | |
2394 | $data = (object)$data; | |
2395 | $data->usercreated = $this->get_mappingid('user', $data->usercreated); | |
927ea484 DC |
2396 | if (empty($data->usercreated)) { |
2397 | $data->usercreated = $this->task->get_userid(); | |
2398 | } | |
2832093f | 2399 | $data->usermodified = $this->get_mappingid('user', $data->usermodified); |
927ea484 DC |
2400 | if (empty($data->usermodified)) { |
2401 | $data->usermodified = $this->task->get_userid(); | |
2402 | } | |
2832093f YB |
2403 | |
2404 | // We'll restore the badge image. | |
2405 | $restorefiles = true; | |
2406 | ||
2407 | $courseid = $this->get_courseid(); | |
2408 | ||
2409 | $params = array( | |
2410 | 'name' => $data->name, | |
2411 | 'description' => $data->description, | |
2832093f YB |
2412 | 'timecreated' => $this->apply_date_offset($data->timecreated), |
2413 | 'timemodified' => $this->apply_date_offset($data->timemodified), | |
2414 | 'usercreated' => $data->usercreated, | |
2415 | 'usermodified' => $data->usermodified, | |
2416 | 'issuername' => $data->issuername, | |
2417 | 'issuerurl' => $data->issuerurl, | |
2418 | 'issuercontact' => $data->issuercontact, | |
2419 | 'expiredate' => $this->apply_date_offset($data->expiredate), | |
2420 | 'expireperiod' => $data->expireperiod, | |
2421 | 'type' => BADGE_TYPE_COURSE, | |
2422 | 'courseid' => $courseid, | |
2423 | 'message' => $data->message, | |
2424 | 'messagesubject' => $data->messagesubject, | |
2425 | 'attachment' => $data->attachment, | |
2426 | 'notification' => $data->notification, | |
2427 | 'status' => BADGE_STATUS_INACTIVE, | |
2428 | 'nextcron' => $this->apply_date_offset($data->nextcron) | |
2429 | ); | |
2430 | ||
2431 | $newid = $DB->insert_record('badge', $params); | |
2432 | $this->set_mapping('badge', $data->id, $newid, $restorefiles); | |
2433 | } | |
2434 | ||
2435 | public function process_criterion($data) { | |
2436 | global $DB; | |
2437 | ||
2438 | $data = (object)$data; | |
2439 | ||
2440 | $params = array( | |
fffeb03f YB |
2441 | 'badgeid' => $this->get_new_parentid('badge'), |
2442 | 'criteriatype' => $data->criteriatype, | |
2443 | 'method' => $data->method, | |
7962f73e EL |
2444 | 'description' => isset($data->description) ? $data->description : '', |
2445 | 'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0, | |
2832093f YB |
2446 | ); |
2447 | $newid = $DB->insert_record('badge_criteria', $params); | |
2448 | $this->set_mapping('criterion', $data->id, $newid); | |
2449 | } | |
2450 | ||
2451 | public function process_parameter($data) { | |
2452 | global $DB, $CFG; | |
bd0d2bdc YB |
2453 | |
2454 | require_once($CFG->libdir . '/badgeslib.php'); | |
2832093f YB |
2455 | |
2456 | $data = (object)$data; | |
2457 | $criteriaid = $this->get_new_parentid('criterion'); | |
2458 | ||
2459 | // Parameter array that will go to database. | |
2460 | $params = array(); | |
2461 | $params['critid'] = $criteriaid; | |
2462 | ||
2463 | $oldparam = explode('_', $data->name); | |
2464 | ||
2465 | if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) { | |
2466 | $module = $this->get_mappingid('course_module', $oldparam[1]); | |
2467 | $params['name'] = $oldparam[0] . '_' . $module; | |
2468 | $params['value'] = $oldparam[0] == 'module' ? $module : $data->value; | |
2469 | } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) { | |
2470 | $params['name'] = $oldparam[0] . '_' . $this->get_courseid(); | |
2471 | $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value; | |
2472 | } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) { | |
bd0d2bdc YB |
2473 | $role = $this->get_mappingid('role', $data->value); |
2474 | if (!empty($role)) { | |
2475 | $params['name'] = 'role_' . $role; | |
2476 | $params['value'] = $role; | |
2477 | } else { | |
2478 | return; | |
2479 | } | |
2832093f YB |
2480 | } |
2481 | ||
2482 | if (!$DB->record_exists('badge_criteria_param', $params)) { | |
2483 | $DB->insert_record('badge_criteria_param', $params); | |
2484 | } | |
2485 | } | |
2486 | ||
bd0d2bdc YB |
2487 | public function process_manual_award($data) { |
2488 | global $DB; | |
2489 | ||
2490 | $data = (object)$data; | |
2491 | $role = $this->get_mappingid('role', $data->issuerrole); | |
2492 | ||
2493 | if (!empty($role)) { | |
2494 | $award = array( | |
2495 | 'badgeid' => $this->get_new_parentid('badge'), | |
2496 | 'recipientid' => $this->get_mappingid('user', $data->recipientid), | |
2497 | 'issuerid' => $this->get_mappingid('user', $data->issuerid), | |
2498 | 'issuerrole' => $role, | |
2499 | 'datemet' => $this->apply_date_offset($data->datemet) | |
2500 | ); | |
927ea484 DC |
2501 | |
2502 | // Skip the manual award if recipient or issuer can not be mapped to. | |
2503 | if (empty($award['recipientid']) || empty($award['issuerid'])) { | |
2504 | return; | |
2505 | } | |
2506 | ||
bd0d2bdc YB |
2507 | $DB->insert_record('badge_manual_award', $award); |
2508 | } | |
2509 | } | |
2510 | ||
2832093f YB |
2511 | protected function after_execute() { |
2512 | // Add related files. | |
2513 | $this->add_related_files('badges', 'badgeimage', 'badge'); | |
2514 | } | |
2515 | } | |
2516 | ||
8331a159 AA |
2517 | /** |
2518 | * This structure steps restores the calendar events | |
2519 | */ | |
2520 | class restore_calendarevents_structure_step extends restore_structure_step { | |
2521 | ||
2522 | protected function define_structure() { | |
2523 | ||
2524 | $paths = array(); | |
2525 | ||
2526 | $paths[] = new restore_path_element('calendarevents', '/events/event'); | |
2527 | ||
2528 | return $paths; | |
2529 | } | |
2530 | ||
2531 | public function process_calendarevents($data) { | |
d983ac63 | 2532 | global $DB, $SITE, $USER; |
8331a159 AA |
2533 | |
2534 | $data = (object)$data; | |
2535 | $oldid = $data->id; | |
2536 | $restorefiles = true; // We'll restore the files | |
d983ac63 | 2537 | // Find the userid and the groupid associated with the event. |
8331a159 AA |
2538 | $data->userid = $this->get_mappingid('user', $data->userid); |
2539 | if ($data->userid === false) { | |
d983ac63 AG |
2540 | // Blank user ID means that we are dealing with module generated events such as quiz starting times. |
2541 | // Use the current user ID for these events. | |
2542 | $data->userid = $USER->id; | |
8331a159 AA |
2543 | } |
2544 | if (!empty($data->groupid)) { | |
2545 | $data->groupid = $this->get_mappingid('group', $data->groupid); | |
2546 | if ($data->groupid === false) { | |
2547 | return; | |
2548 | } | |
2549 | } | |
686ca2f5 AA |
2550 | // Handle events with empty eventtype //MDL-32827 |
2551 | if(empty($data->eventtype)) { | |
2552 | if ($data->courseid == $SITE->id) { // Site event | |
2553 | $data->eventtype = "site"; | |
2554 | } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) { | |
2555 | // Course assingment event | |
2556 | $data->eventtype = "due"; | |
2557 | } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event | |
2558 | $data->eventtype = "course"; | |
2559 | } else if ($data->groupid) { // Group event | |
2560 | $data->eventtype = "group"; | |
2561 | } else if ($data->userid) { // User event | |
2562 | $data->eventtype = "user"; | |
2563 | } else { | |
2564 | return; | |
2565 | } | |
2566 | } | |
8331a159 AA |
2567 | |
2568 | $params = array( | |
2569 | 'name' => $data->name, | |
2570 | 'description' => $data->description, | |
2571 | 'format' => $data->format, | |
2572 | 'courseid' => $this->get_courseid(), | |
2573 | 'groupid' => $data->groupid, | |
2574 | 'userid' => $data->userid, | |
2575 | 'repeatid' => $data->repeatid, | |
2576 | 'modulename' => $data->modulename, | |
2577 | 'eventtype' => $data->eventtype, | |
2578 | 'timestart' => $this->apply_date_offset($data->timestart), | |
2579 | 'timeduration' => $data->timeduration, | |
2580 | 'visible' => $data->visible, | |
2581 | 'uuid' => $data->uuid, | |
2582 | 'sequence' => $data->sequence, | |
2583 | 'timemodified' => $this->apply_date_offset($data->timemodified)); | |
2584 | if ($this->name == 'activity_calendar') { | |
2585 | $params['instance'] = $this->task->get_activityid(); | |
2586 | } else { | |
2587 | $params['instance'] = 0; | |
2588 | } | |
c7b3c10e FM |
2589 | $sql = "SELECT id |
2590 | FROM {event} | |
2591 | WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . " | |
2592 | AND courseid = ? | |
2593 | AND repeatid = ? | |
2594 | AND modulename = ? | |
2595 | AND timestart = ? | |
2596 | AND timeduration = ? | |
2597 | AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255); | |
8331a159 AA |
2598 | $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']); |
2599 | $result = $DB->record_exists_sql($sql, $arg); | |
2600 | if (empty($result)) { | |
2601 | $newitemid = $DB->insert_record('event', $params); | |
bc213518 | 2602 | $this->set_mapping('event', $oldid, $newitemid); |
8331a159 AA |
2603 | $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles); |
2604 | } | |
2605 | ||
2606 | } | |
2607 | protected function after_execute() { | |
8331a159 AA |
2608 | // Add related files |
2609 | $this->add_related_files('calendar', 'event_description', 'event_description'); | |
2610 | } | |
6565d55a | 2611 | } |
8331a159 | 2612 | |
bd39b6f2 SH |
2613 | class restore_course_completion_structure_step extends restore_structure_step { |
2614 | ||
2615 | /** | |
2616 | * Conditionally decide if this step should be executed. | |
2617 | * | |
2618 | * This function checks parameters that are not immediate settings to ensure | |
2619 | * that the enviroment is suitable for the restore of course completion info. | |
2620 | * | |
2621 | * This function checks the following four parameters: | |
2622 | * | |
2623 | * 1. Course completion is enabled on the site | |
2624 | * 2. The backup includes course completion information | |
2625 | * 3. All modules are restorable | |
2626 | * 4. All modules are marked for restore. | |
96e339cc | 2627 | * 5. No completion criteria already exist for the course. |
bd39b6f2 SH |
2628 | * |
2629 | * @return bool True is safe to execute, false otherwise | |
2630 | */ | |
2631 | protected function execute_condition() { | |
96e339cc | 2632 | global $CFG, $DB; |
bd39b6f2 SH |
2633 | |
2634 | // First check course completion is enabled on this site | |
2635 | if (empty($CFG->enablecompletion)) { | |
2636 | // Disabled, don't restore course completion | |
2637 | return false; | |
2638 | } | |
2639 | ||
03c39daa DM |
2640 | // No course completion on the front page. |
2641 | if ($this->get_courseid() == SITEID) { | |
2642 | return false; | |
2643 | } | |
2644 | ||
bd39b6f2 SH |
2645 | // Check it is included in the backup |
2646 | $fullpath = $this->task->get_taskbasepath(); | |
2647 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
2648 | if (!file_exists($fullpath)) { | |
2649 | // Not found, can't restore course completion | |
2650 | return false; | |
2651 | } | |
2652 | ||
2653 | // Check we are able to restore all backed up modules | |
2654 | if ($this->task->is_missing_modules()) { | |
2655 | return false; | |
2656 | } | |
2657 | ||
96e339cc | 2658 | // Check all modules within the backup are being restored. |
bd39b6f2 SH |
2659 | if ($this->task->is_excluding_activities()) { |
2660 | return false; | |
2661 | } | |
2662 | ||
96e339cc EV |
2663 | // Check that no completion criteria is already set for the course. |
2664 | if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) { | |
2665 | return false; | |
2666 | } | |
2667 | ||
bd39b6f2 SH |
2668 | return true; |
2669 | } | |
2670 | ||
2671 | /** | |
2672 | * Define the course completion structure | |
2673 | * | |
2674 | * @return array Array of restore_path_element | |
2675 | */ | |
2676 | protected function define_structure() { | |
2677 | ||
2678 | // To know if we are including user completion info | |
2679 | $userinfo = $this->get_setting_value('userscompletion'); | |
2680 | ||
2681 | $paths = array(); | |
2682 | $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria'); | |
bd39b6f2 SH |
2683 | $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd'); |
2684 | ||
2685 | if ($userinfo) { | |
2686 | $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl'); | |
2687 | $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions'); | |
2688 | } | |
2689 | ||
2690 | return $paths; | |
2691 | ||
2692 | } | |
2693 | ||
2694 | /** | |
2695 | * Process course completion criteria | |
2696 | * | |
2697 | * @global moodle_database $DB | |
2698 | * @param stdClass $data | |
2699 | */ | |
2700 | public function process_course_completion_criteria($data) { | |
2701 | global $DB; | |
2702 | ||
2703 | $data = (object)$data; | |
2704 | $data->course = $this->get_courseid(); | |
2705 | ||
2706 | // Apply the date offset to the time end field | |
2707 | $data->timeend = $this->apply_date_offset($data->timeend); | |
2708 | ||
2709 | // Map the role from the criteria | |
129e786c | 2710 | if (isset($data->role) && $data->role != '') { |
11512101 AB |
2711 | // Newer backups should include roleshortname, which makes this much easier. |
2712 | if (!empty($data->roleshortname)) { | |
2713 | $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname)); | |
2714 | if (!$roleinstanceid) { | |
2715 | $this->log( | |
2716 | 'Could not match the role shortname in course_completion_criteria, so skipping', | |
2717 | backup::LOG_DEBUG | |
2718 | ); | |
2719 | return; | |
129e786c | 2720 | } |
11512101 AB |
2721 | $data->role = $roleinstanceid; |
2722 | } else { | |
2723 | $data->role = $this->get_mappingid('role', $data->role); | |
129e786c | 2724 | } |
bd39b6f2 | 2725 | |
129e786c AB |
2726 | // Check we have an id, otherwise it causes all sorts of bugs. |
2727 | if (!$data->role) { | |
11512101 AB |
2728 | $this->log( |
2729 | 'Could not match role in course_completion_criteria, so skipping', | |
2730 | backup::LOG_DEBUG | |
2731 | ); | |
129e786c AB |
2732 | return; |
2733 | } | |
2734 | } | |
aa548318 | 2735 | |
bd39b6f2 SH |
2736 | // If the completion criteria is for a module we need to map the module instance |
2737 | // to the new module id. | |
2738 | if (!empty($data->moduleinstance) && !empty($data->module)) { | |
2739 | $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance); | |
aa548318 | 2740 | if (empty($data->moduleinstance)) { |
11512101 AB |
2741 | $this->log( |
2742 | 'Could not match the module instance in course_completion_criteria, so skipping', | |
2743 | backup::LOG_DEBUG | |
2744 | ); | |
129e786c | 2745 | return; |
aa548318 | 2746 | } |
bd39b6f2 SH |
2747 | } else { |
2748 | $data->module = null; | |
2749 | $data->moduleinstance = null; | |
2750 | } | |
2751 | ||
2752 | // We backup the course shortname rather than the ID so that we can match back to the course | |
bd39b6f2 SH |
2753 | if (!empty($data->courseinstanceshortname)) { |
2754 | $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname)); | |
2755 | if (!$courseinstanceid) { | |
11512101 AB |
2756 | $this->log( |
2757 | 'Could not match the course instance in course_completion_criteria, so skipping', | |
2758 | backup::LOG_DEBUG | |
2759 | ); | |
129e786c | 2760 | return; |
bd39b6f2 SH |
2761 | } |
2762 | } else { | |
2763 | $courseinstanceid = null; | |
2764 | } | |
2765 | $data->courseinstance = $courseinstanceid; | |
2766 | ||
129e786c AB |
2767 | $params = array( |
2768 | 'course' => $data->course, | |
2769 | 'criteriatype' => $data->criteriatype, | |
2770 | 'enrolperiod' => $data->enrolperiod, | |
2771 | 'courseinstance' => $data->courseinstance, | |
2772 | 'module' => $data->module, | |
2773 | 'moduleinstance' => $data->moduleinstance, | |
2774 | 'timeend' => $data->timeend, | |
2775 | 'gradepass' => $data->gradepass, | |
2776 | 'role' => $data->role | |
2777 | ); | |
2778 | $newid = $DB->insert_record('course_completion_criteria', $params); | |
2779 | $this->set_mapping('course_completion_criteria', $data->id, $newid); | |
bd39b6f2 SH |
2780 | } |
2781 | ||
2782 | /** | |
2783 | * Processes course compltion criteria complete records | |
2784 | * | |
2785 | * @global moodle_database $DB | |
2786 | * @param stdClass $data | |
2787 | */ | |
2788 | public function process_course_completion_crit_compl($data) { | |
2789 | global $DB; | |
2790 | ||
2791 | $data = (object)$data; | |
2792 | ||
2793 | // This may be empty if criteria could not be restored | |
2794 | $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid); | |
034ef761 | 2795 | |
bd39b6f2 SH |
2796 | $data->course = $this->get_courseid(); |
2797 | $data->userid = $this->get_mappingid('user', $data->userid); | |
2798 | ||
2799 | if (!empty($data->criteriaid) && !empty($data->userid)) { | |
2800 | $params = array( | |
2801 | 'userid' => $data->userid, | |
2802 | 'course' => $data->course, | |
2803 | 'criteriaid' => $data->criteriaid, | |
2804 | 'timecompleted' => $this->apply_date_offset($data->timecompleted) | |
2805 | ); | |
2806 | if (isset($data->gradefinal)) { | |
2807 | $params['gradefinal'] = $data->gradefinal; | |
2808 | } | |
2809 | if (isset($data->unenroled)) { | |
2810 | $params['unenroled'] = $data->unenroled; | |
2811 | } | |
bd39b6f2 SH |
2812 | $DB->insert_record('course_completion_crit_compl', $params); |
2813 | } | |
2814 | } | |
2815 | ||
2816 | /** | |
2817 | * Process course completions | |
2818 | * | |
2819 | * @global moodle_database $DB | |
2820 | * @param stdClass $data | |
2821 | */ | |
2822 | public function process_course_completions($data) { | |
2823 | global $DB; | |
2824 | ||
2825 | $data = (object)$data; | |
2826 | ||
2827 | $data->course = $this->get_courseid(); | |
2828 | $data->userid = $this->get_mappingid('user', $data->userid); | |
2829 | ||
2830 | if (!empty($data->userid)) { | |
2831 | $params = array( | |
2832 | 'userid' => $data->userid, | |
2833 | 'course' => $data->course, | |
bd39b6f2 SH |
2834 | 'timeenrolled' => $this->apply_date_offset($data->timeenrolled), |
2835 | 'timestarted' => $this->apply_date_offset($data->timestarted), | |
2836 | 'timecompleted' => $this->apply_date_offset($data->timecompleted), | |
2837 | 'reaggregate' => $data->reaggregate | |
2838 | ); | |
7a6ca49a JJ |
2839 | |
2840 | $existing = $DB->get_record('course_completions', array( | |
2841 | 'userid' => $data->userid, | |
2842 | 'course' => $data->course | |
2843 | )); | |
2844 | ||
2845 | // MDL-46651 - If cron writes out a new record before we get to it | |
2846 | // then we should replace it with the Truth data from the backup. | |
2847 | // This may be obsolete after MDL-48518 is resolved | |
2848 | if ($existing) { | |
2849 | $params['id'] = $existing->id; | |
2850 | $DB->update_record('course_completions', $params); | |
2851 | } else { | |
2852 | $DB->insert_record('course_completions', $params); | |
2853 | } | |
bd39b6f2 SH |
2854 | } |
2855 | } | |
2856 | ||
bd39b6f2 SH |
2857 | /** |
2858 | * Process course completion aggregate methods | |
2859 | * | |
2860 | * @global moodle_database $DB | |
2861 | * @param stdClass $data | |
2862 | */ | |
2863 | public function process_course_completion_aggr_methd($data) { | |
2864 | global $DB; | |
2865 | ||
2866 | $data = (object)$data; | |
2867 | ||
2868 | $data->course = $this->get_courseid(); | |
2869 | ||
4d856332 EL |
2870 | // Only create the course_completion_aggr_methd records if |
2871 | // the target course has not them defined. MDL-28180 | |
2872 | if (!$DB->record_exists('course_completion_aggr_methd', array( | |
2873 | 'course' => $data->course, | |
2874 | 'criteriatype' => $data->criteriatype))) { | |
2875 | $params = array( | |
2876 | 'course' => $data->course, | |
2877 | 'criteriatype' => $data->criteriatype, | |
2878 | 'method' => $data->method, | |
2879 | 'value' => $data->value, | |
2880 | ); | |
2881 | $DB->insert_record('course_completion_aggr_methd', $params); | |
2882 | } | |
bd39b6f2 | 2883 | } |
bd39b6f2 SH |
2884 | } |
2885 | ||
0f66aced EL |
2886 | |
2887 | /** | |
2888 | * This structure step restores course logs (cmid = 0), delegating | |
2889 | * the hard work to the corresponding {@link restore_logs_processor} passing the | |
2890 | * collection of {@link restore_log_rule} rules to be observed as they are defined | |
2891 | * by the task. Note this is only executed based in the 'logs' setting. | |
2892 | * | |
2893 | * NOTE: This is executed by final task, to have all the activities already restored | |
2894 | * | |
2895 | * NOTE: Not all course logs are being restored. For now only 'course' and 'user' | |
2896 | * records are. There are others like 'calendar' and 'upload' that will be handled | |
2897 | * later. | |
2898 | * | |
2899 | * NOTE: All the missing actions (not able to be restored) are sent to logs for | |
2900 | * debugging purposes | |
2901 | */ | |
2902 | class restore_course_logs_structure_step extends restore_structure_step { | |
2903 | ||
2904 | /** | |
2905 | * Conditionally decide if this step should be executed. | |
2906 | * | |
9ab5df6b | 2907 | * This function checks the following parameter: |
0f66aced EL |
2908 | * |
2909 | * 1. the course/logs.xml file exists | |
2910 | * | |
2911 | * @return bool true is safe to execute, false otherwise | |
2912 | */ | |
2913 | protected function execute_condition() { | |
2914 | ||
2915 | // Check it is included in the backup | |
2916 | $fullpath = $this->task->get_taskbasepath(); | |
2917 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
2918 | if (!file_exists($fullpath)) { | |
2919 | // Not found, can't restore course logs | |
2920 | return false; | |
2921 | } | |
2922 | ||
2923 | return true; | |
2924 | } | |
2925 | ||
2926 | protected function define_structure() { | |
2927 | ||
2928 | $paths = array(); | |
2929 | ||
2930 | // Simple, one plain level of information contains them | |
2931 | $paths[] = new restore_path_element('log', '/logs/log'); | |
2932 | ||
2933 | return $paths; | |
2934 | } | |
2935 | ||
2936 | protected function process_log($data) { | |
2937 | global $DB; | |
2938 | ||
2939 | $data = (object)($data); | |
2940 | ||
2941 | $data->time = $this->apply_date_offset($data->time); | |
2942 | $data->userid = $this->get_mappingid('user', $data->userid); | |
2943 | $data->course = $this->get_courseid(); | |
2944 | $data->cmid = 0; | |
2945 | ||
2946 | // For any reason user wasn't remapped ok, stop processing this | |
2947 | if (empty($data->userid)) { | |
2948 | return; | |
2949 | } | |
2950 | ||
2951 | // Everything ready, let's delegate to the restore_logs_processor | |
2952 | ||
2953 | // Set some fixed values that will save tons of DB requests | |
2954 | $values = array( | |
2955 | 'course' => $this->get_courseid()); | |
2956 | // Get instance and process log record | |
2957 | $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data); | |
2958 | ||
2959 | // If we have data, insert it, else something went wrong in the restore_logs_processor | |
2960 | if ($data) { | |
115e8964 MN |
2961 | if (empty($data->url)) { |
2962 | $data->url = ''; | |
2963 | } | |
2964 | if (empty($data->info)) { | |
2965 | $data->info = ''; | |
2966 | } | |
2967 | // Store the data in the legacy log table if we are still using it. | |
2968 | $manager = get_log_manager(); | |
2969 | if (method_exists($manager, 'legacy_add_to_log')) { | |
2970 | $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url, | |
362bc070 | 2971 | $data->info, $data->cmid, $data->userid, $data->ip, $data->time); |
115e8964 | 2972 | } |
0f66aced EL |
2973 | } |
2974 | } | |
2975 | } | |
2976 | ||
2977 | /** | |
2978 | * This structure step restores activity logs, extending {@link restore_course_logs_structure_step} | |
2979 | * sharing its same structure but modifying the way records are handled | |
2980 | */ | |
2981 | class restore_activity_logs_structure_step extends restore_course_logs_structure_step { | |
2982 | ||
2983 | protected function process_log($data) { | |
2984 | global $DB; | |
2985 | ||
2986 | $data = (object)($data); | |
2987 | ||
2988 | $data->time = $this->apply_date_offset($data->time); | |
2989 | $data->userid = $this->get_mappingid('user', $data->userid); | |
2990 | $data->course = $this->get_courseid(); | |
2991 | $data->cmid = $this->task->get_moduleid(); | |
2992 | ||
2993 | // For any reason user wasn't remapped ok, stop processing this | |
2994 | if (empty($data->userid)) { | |
2995 | return; | |
2996 | } | |
2997 | ||
2998 | // Everything ready, let's delegate to the restore_logs_processor | |
2999 | ||
3000 | // Set some fixed values that will save tons of DB requests | |
3001 | $values = array( | |
3002 | 'course' => $this->get_courseid(), | |
3003 | 'course_module' => $this->task->get_moduleid(), | |
3004 | $this->task->get_modulename() => $this->task->get_activityid()); | |
3005 | // Get instance and process log record | |
3006 | $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data); | |
3007 | ||
3008 | // If we have data, insert it, else something went wrong in the restore_logs_processor | |
3009 | if ($data) { | |
115e8964 MN |
3010 | if (empty($data->url)) { |
3011 | $data->url = ''; | |
3012 | } | |
3013 | if (empty($data->info)) { | |
3014 | $data->info = ''; | |
3015 | } | |
3016 | // Store the data in the legacy log table if we are still using it. | |
3017 | $manager = get_log_manager(); | |
3018 | if (method_exists($manager, 'legacy_add_to_log')) { | |
3019 | $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url, | |
362bc070 | 3020 | $data->info, $data->cmid, $data->userid, $data->ip, $data->time); |
115e8964 | 3021 | } |
0f66aced EL |
3022 | } |
3023 | } | |
3024 | } | |
3025 | ||
ea6c5643 EL |
3026 | /** |
3027 | * Structure step in charge of restoring the logstores.xml file for the course logs. | |
3028 | * | |
3029 | * This restore step will rebuild the logs for all the enabled logstore subplugins supporting | |
3030 | * it, for logs belonging to the course level. | |
3031 | */ | |
3032 | class restore_course_logstores_structure_step extends restore_structure_step { | |
3033 | ||
3034 | /** | |
3035 | * Conditionally decide if this step should be executed. | |
3036 | * | |
3037 | * This function checks the following parameter: | |
3038 | * | |
3039 | * 1. the logstores.xml file exists | |
3040 | * | |
3041 | * @return bool true is safe to execute, false otherwise | |
3042 | */ | |
3043 | protected function execute_condition() { | |
3044 | ||
3045 | // Check it is included in the backup. | |
3046 | $fullpath = $this->task->get_taskbasepath(); | |
3047 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
3048 | if (!file_exists($fullpath)) { | |
3049 | // Not found, can't restore logstores.xml information. | |
3050 | return false; | |
3051 | } | |
3052 | ||
3053 | return true; | |
3054 | } | |
3055 | ||
3056 | /** | |
3057 | * Return the elements to be processed on restore of logstores. | |
3058 | * | |
3059 | * @return restore_path_element[] array of elements to be processed on restore. | |
3060 | */ | |
3061 | protected function define_structure() { | |
3062 | ||
3063 | $paths = array(); | |
3064 | ||
3065 | $logstore = new restore_path_element('logstore', '/logstores/logstore'); | |
3066 | $paths[] = $logstore; | |
3067 | ||
3068 | // Add logstore subplugin support to the 'logstore' element. | |
3069 | $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log'); | |
3070 | ||
3071 | return array($logstore); | |
3072 | } | |
3073 | ||
3074 | /** | |
3075 | * Process the 'logstore' element, | |
3076 | * | |
3077 | * Note: This is empty by definition in backup, because stores do not share any | |
3078 | * data between them, so there is nothing to process here. | |
3079 | * | |
3080 | * @param array $data element data | |
3081 | */ | |
3082 | protected function process_logstore($data) { | |
3083 | return; | |
3084 | } | |
3085 | } | |
3086 | ||
3087 | /** | |
3088 | * Structure step in charge of restoring the logstores.xml file for the activity logs. | |
3089 | * | |
3090 | * Note: Activity structure is completely equivalent to the course one, so just extend it. | |
3091 | */ | |
3092 | class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step { | |
3093 | } | |
3094 | ||
8417c3a6 FM |
3095 | /** |
3096 | * Restore course competencies structure step. | |
3097 | */ | |
3098 | class restore_course_competencies_structure_step extends restore_structure_step { | |
3099 | ||
3100 | /** | |
3101 | * Returns the structure. | |
3102 | * | |
3103 | * @return array | |
3104 | */ | |
3105 | protected function define_structure() { | |
e9114a9e | 3106 | $userinfo = $this->get_setting_value('users'); |
8417c3a6 FM |
3107 | $paths = array( |
3108 | new restore_path_element('course_competency', '/course_competencies/competencies/competency'), | |
e9114a9e | 3109 | new restore_path_element('course_competency_settings', '/course_competencies/settings'), |
8417c3a6 | 3110 | ); |
e9114a9e FM |
3111 | if ($userinfo) { |
3112 | $paths[] = new restore_path_element('user_competency_course', | |
3113 | '/course_competencies/user_competencies/user_competency'); | |
3114 | } | |
8417c3a6 FM |
3115 | return $paths; |
3116 | } | |
3117 | ||
3118 | /** | |
3119 | * Process a course competency settings. | |
3120 | * | |
3121 | * @param array $data The data. | |
3122 | */ | |
3123 | public function process_course_competency_settings($data) { | |
3124 | global $DB; | |
8417c3a6 | 3125 | $data = (object) $data; |
e9114a9e FM |
3126 | |
3127 | // We do not restore the course settings during merge. | |
3128 | $target = $this->get_task()->get_target(); | |
3129 | if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) { | |
3130 | return; | |
3131 | } | |
3132 | ||
8417c3a6 | 3133 | $courseid = $this->task->get_courseid(); |
e9114a9e FM |
3134 | $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid', |
3135 | array('courseid' => $courseid)); | |
8417c3a6 | 3136 | |
e9114a9e | 3137 | // Strangely the course settings already exist, let's just leave them as is then. |
8417c3a6 | 3138 | if ($exists) { |
e9114a9e FM |
3139 | $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING); |
3140 | return; | |
8417c3a6 | 3141 | } |
e9114a9e FM |
3142 | |
3143 | $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans); | |
3144 | $settings = new \core_competency\course_competency_settings(0, $data); | |
3145 | $settings->create(); | |
8417c3a6 FM |
3146 | } |
3147 | ||
3148 | /** | |
3149 | * Process a course competency. | |
3150 | * | |
3151 | * @param array $data The data. | |
3152 | */ | |
3153 | public function process_course_competency($data) { | |
3154 | $data = (object) $data; | |
3155 | ||
3156 | // Mapping the competency by ID numbers. | |
3157 | $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber)); | |
3158 | if (!$framework) { | |
3159 | return; | |
3160 | } | |
3161 | $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber, | |
3162 | 'competencyframeworkid' => $framework->get_id())); | |
3163 | if (!$competency) { | |
3164 | return; | |
3165 | } | |
e9114a9e | 3166 | $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get_id()); |
8417c3a6 FM |
3167 | |
3168 | $params = array( | |
3169 | 'competencyid' => $competency->get_id(), | |
3170 | 'courseid' => $this->task->get_courseid() | |
3171 | ); | |
3172 | $query = 'competencyid = :competencyid AND courseid = :courseid'; | |
3173 | $existing = \core_competency\course_competency::record_exists_select($query, $params); | |
3174 | ||
3175 | if (!$existing) { | |
3176 | // Sortorder is ignored by precaution, anyway we should walk through the records in the right order. | |
3177 | $record = (object) $params; | |
3178 | $record->ruleoutcome = $data->ruleoutcome; | |
3179 | $coursecompetency = new \core_competency\course_competency(0, $record); | |
3180 | $coursecompetency->create(); | |
3181 | } | |
3182 | } | |
3183 | ||
e9114a9e FM |
3184 | /** |
3185 | * Process the user competency course. | |
3186 | * | |
3187 | * @param array $data The data. | |
3188 | */ | |
3189 | public function process_user_competency_course($data) { | |
3190 | global $USER, $DB; | |
3191 | $data = (object) $data; | |
3192 | ||
3193 | $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid); | |
3194 | if (!$data->competencyid) { | |
3195 | // This is strange, the competency does not belong to the course. | |
3196 | return; | |
3197 | } else if ($data->grade === null) { | |
3198 | // We do not need to do anything when there is no grade. | |
3199 | return; | |
3200 | } | |
3201 | ||
3202 | $data->userid = $this->get_mappingid('user', $data->userid); | |
3203 | $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST); | |
3204 | ||
3205 | // The method add_evidence also sets the course rating. | |
3206 | \core_competency\api::add_evidence($data->userid, | |
3207 | $data->competencyid, | |
3208 | $this->task->get_contextid(), | |
3209 | \core_competency\evidence::ACTION_OVERRIDE, | |
3210 | 'evidence_courserestored', | |
3211 | 'core_competency', | |
3212 | $shortname, | |
3213 | false, | |
3214 | null, | |
3215 | $data->grade, | |
3216 | $USER->id); | |
3217 | } | |
3218 | ||
8417c3a6 FM |
3219 | /** |
3220 | * Execute conditions. | |
3221 | * | |
3222 | * @return bool | |
3223 | */ | |
3224 | protected function execute_condition() { | |
3225 | ||
45b9207d JP |
3226 | // Do not execute if competencies are not included. |
3227 | if (!$this->get_setting_value('competencies')) { | |
56e1d9ba FM |
3228 | return false; |
3229 | } | |
3230 | ||
8417c3a6 FM |
3231 | // Do not execute if the competencies XML file is not found. |
3232 | $fullpath = $this->task->get_taskbasepath(); | |
3233 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
3234 | if (!file_exists($fullpath)) { | |
3235 | return false; | |
3236 | } | |
3237 | ||
3238 | return true; | |
3239 | } | |
3240 | } | |
3241 | ||
3242 | /** | |
3243 | * Restore activity competencies structure step. | |
3244 | */ | |
3245 | class restore_activity_competencies_structure_step extends restore_structure_step { | |
3246 | ||
3247 | /** | |
3248 | * Defines the structure. | |
3249 | * | |
3250 | * @return array | |
3251 | */ | |
3252 | protected function define_structure() { | |
3253 | $paths = array( | |
3254 | new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency') | |
3255 | ); | |
3256 | return $paths; | |
3257 | } | |
3258 | ||
3259 | /** | |
3260 | * Process a course module competency. | |
3261 | * | |
3262 | * @param array $data The data. | |
3263 | */ | |
3264 | public function process_course_module_competency($data) { | |
3265 | $data = (object) $data; | |
3266 | ||
3267 | // Mapping the competency by ID numbers. | |
3268 | $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber)); | |
3269 | if (!$framework) { | |
3270 | return; | |
3271 | } | |
3272 | $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber, | |
3273 | 'competencyframeworkid' => $framework->get_id())); | |
3274 | if (!$competency) { | |
3275 | return; | |
3276 | } | |
3277 | ||
3278 | $params = array( | |
3279 | 'competencyid' => $competency->get_id(), | |
3280 | 'cmid' => $this->task->get_moduleid() | |
3281 | ); | |
3282 | $query = 'competencyid = :competencyid AND cmid = :cmid'; | |
3283 | $existing = \core_competency\course_module_competency::record_exists_select($query, $params); | |
3284 | ||
3285 | if (!$existing) { | |
3286 | // Sortorder is ignored by precaution, anyway we should walk through the records in the right order. | |
3287 | $record = (object) $params; | |
3288 | $record->ruleoutcome = $data->ruleoutcome; | |
3289 | $coursemodulecompetency = new \core_competency\course_module_competency(0, $record); | |
3290 | $coursemodulecompetency->create(); | |
3291 | } | |
3292 | } | |
3293 | ||
3294 | /** | |
3295 | * Execute conditions. | |
3296 | * | |
3297 | * @return bool | |
3298 | */ | |
3299 | protected function execute_condition() { | |
3300 | ||
45b9207d JP |
3301 | // Do not execute if competencies are not included. |
3302 | if (!$this->get_setting_value('competencies')) { | |
56e1d9ba FM |
3303 | return false; |
3304 | } | |
3305 | ||
8417c3a6 FM |
3306 | // Do not execute if the competencies XML file is not found. |
3307 | $fullpath = $this->task->get_taskbasepath(); | |
3308 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
3309 | if (!file_exists($fullpath)) { | |
3310 | return false; | |
3311 | } | |
3312 | ||
3313 | return true; | |
3314 | } | |
3315 | } | |
37065c2e DM |
3316 | |
3317 | /** | |
3318 | * Defines the restore step for advanced grading methods attached to the activity module | |
3319 | */ | |
3320 | class restore_activity_grading_structure_step extends restore_structure_step { | |
3321 | ||
3319af85 DM |
3322 | /** |
3323 | * This step is executed only if the grading file is present | |
3324 | */ | |
3325 | protected function execute_condition() { | |
3326 | ||
03c39daa DM |
3327 | if ($this->get_courseid() == SITEID) { |
3328 | return false; | |
3329 | } | |
3330 | ||
3319af85 DM |
3331 | $fullpath = $this->task->get_taskbasepath(); |
3332 | $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; | |
3333 | if (!file_exists($fullpath)) { | |
3334 | return false; | |
3335 | } | |
3336 | ||
3337 | return true; | |
3338 | } | |
3339 | ||
3340 | ||
37065c2e DM |
3341 | /** |
3342 | * Declares pat |