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