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