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