Commit | Line | Data |
---|---|---|
fbc2778d 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-dbops | |
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 | * Base abstract class for all the helper classes providing DB operations | |
27 | * | |
28 | * TODO: Finish phpdocs | |
29 | */ | |
482aac65 | 30 | abstract class restore_dbops { |
e7b24943 RT |
31 | /** |
32 | * Keep cache of backup records. | |
33 | * @var array | |
34 | * @todo MDL-25290 static should be replaced with MUC code. | |
35 | */ | |
36 | private static $backupidscache = array(); | |
37 | /** | |
38 | * Keep track of backup ids which are cached. | |
39 | * @var array | |
40 | * @todo MDL-25290 static should be replaced with MUC code. | |
41 | */ | |
42 | private static $backupidsexist = array(); | |
43 | /** | |
44 | * Count is expensive, so manually keeping track of | |
45 | * backupidscache, to avoid memory issues. | |
46 | * @var int | |
47 | * @todo MDL-25290 static should be replaced with MUC code. | |
48 | */ | |
49 | private static $backupidscachesize = 2048; | |
50 | /** | |
51 | * Count is expensive, so manually keeping track of | |
52 | * backupidsexist, to avoid memory issues. | |
53 | * @var int | |
54 | * @todo MDL-25290 static should be replaced with MUC code. | |
55 | */ | |
56 | private static $backupidsexistsize = 10240; | |
57 | /** | |
58 | * Slice backupids cache to add more data. | |
59 | * @var int | |
60 | * @todo MDL-25290 static should be replaced with MUC code. | |
61 | */ | |
62 | private static $backupidsslice = 512; | |
482aac65 EL |
63 | |
64 | /** | |
648a575e EL |
65 | * Return one array containing all the tasks that have been included |
66 | * in the restore process. Note that these tasks aren't built (they | |
67 | * haven't steps nor ids data available) | |
482aac65 | 68 | */ |
648a575e | 69 | public static function get_included_tasks($restoreid) { |
482aac65 EL |
70 | $rc = restore_controller_dbops::load_controller($restoreid); |
71 | $tasks = $rc->get_plan()->get_tasks(); | |
648a575e EL |
72 | $includedtasks = array(); |
73 | foreach ($tasks as $key => $task) { | |
482aac65 EL |
74 | // Calculate if the task is being included |
75 | $included = false; | |
76 | // blocks, based in blocks setting and parent activity/course | |
77 | if ($task instanceof restore_block_task) { | |
4a15bb76 | 78 | if (!$task->get_setting_value('blocks')) { // Blocks not included, continue |
482aac65 EL |
79 | continue; |
80 | } | |
81 | $parent = basename(dirname(dirname($task->get_taskbasepath()))); | |
82 | if ($parent == 'course') { // Parent is course, always included if present | |
83 | $included = true; | |
84 | ||
85 | } else { // Look for activity_included setting | |
86 | $included = $task->get_setting_value($parent . '_included'); | |
87 | } | |
88 | ||
89 | // ativities, based on included setting | |
90 | } else if ($task instanceof restore_activity_task) { | |
91 | $included = $task->get_setting_value('included'); | |
92 | ||
93 | // sections, based on included setting | |
94 | } else if ($task instanceof restore_section_task) { | |
95 | $included = $task->get_setting_value('included'); | |
96 | ||
97 | // course always included if present | |
98 | } else if ($task instanceof restore_course_task) { | |
99 | $included = true; | |
100 | } | |
101 | ||
648a575e | 102 | // If included, add it |
482aac65 | 103 | if ($included) { |
648a575e | 104 | $includedtasks[] = $task; |
482aac65 EL |
105 | } |
106 | } | |
648a575e | 107 | return $includedtasks; |
482aac65 EL |
108 | } |
109 | ||
110 | /** | |
111 | * Load one inforef.xml file to backup_ids table for future reference | |
112 | */ | |
113 | public static function load_inforef_to_tempids($restoreid, $inforeffile) { | |
114 | ||
115 | if (!file_exists($inforeffile)) { // Shouldn't happen ever, but... | |
116 | throw new backup_helper_exception('missing_inforef_xml_file', $inforeffile); | |
117 | } | |
118 | // Let's parse, custom processor will do its work, sending info to DB | |
119 | $xmlparser = new progressive_parser(); | |
120 | $xmlparser->set_file($inforeffile); | |
121 | $xmlprocessor = new restore_inforef_parser_processor($restoreid); | |
122 | $xmlparser->set_processor($xmlprocessor); | |
123 | $xmlparser->process(); | |
124 | } | |
125 | ||
71a50b13 EL |
126 | /** |
127 | * Load the needed role.xml file to backup_ids table for future reference | |
128 | */ | |
129 | public static function load_roles_to_tempids($restoreid, $rolesfile) { | |
130 | ||
131 | if (!file_exists($rolesfile)) { // Shouldn't happen ever, but... | |
132 | throw new backup_helper_exception('missing_roles_xml_file', $rolesfile); | |
133 | } | |
134 | // Let's parse, custom processor will do its work, sending info to DB | |
135 | $xmlparser = new progressive_parser(); | |
136 | $xmlparser->set_file($rolesfile); | |
137 | $xmlprocessor = new restore_roles_parser_processor($restoreid); | |
138 | $xmlparser->set_processor($xmlprocessor); | |
139 | $xmlparser->process(); | |
140 | } | |
141 | ||
142 | /** | |
143 | * Precheck the loaded roles, return empty array if everything is ok, and | |
144 | * array with 'errors', 'warnings' elements (suitable to be used by restore_prechecks) | |
8d4e41f4 EL |
145 | * with any problem found. At the same time, store all the mapping into backup_ids_temp |
146 | * and also put the information into $rolemappings (controller->info), so it can be reworked later by | |
147 | * post-precheck stages while at the same time accept modified info in the same object coming from UI | |
71a50b13 | 148 | */ |
8d4e41f4 EL |
149 | public static function precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings) { |
150 | global $DB; | |
151 | ||
152 | $problems = array(); // To store warnings/errors | |
153 | ||
154 | // Get loaded roles from backup_ids | |
155 | $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid'); | |
156 | foreach ($rs as $recrole) { | |
157 | // If the rolemappings->modified flag is set, that means that we are coming from | |
158 | // manually modified mappings (by UI), so accept those mappings an put them to backup_ids | |
159 | if ($rolemappings->modified) { | |
160 | $target = $rolemappings->mappings[$recrole->itemid]->targetroleid; | |
161 | self::set_backup_ids_record($restoreid, 'role', $recrole->itemid, $target); | |
162 | ||
163 | // Else, we haven't any info coming from UI, let's calculate the mappings, matching | |
164 | // in multiple ways and checking permissions. Note mapping to 0 means "skip" | |
165 | } else { | |
166 | $role = (object)self::get_backup_ids_record($restoreid, 'role', $recrole->itemid)->info; | |
167 | $match = self::get_best_assignable_role($role, $courseid, $userid, $samesite); | |
168 | // Send match to backup_ids | |
169 | self::set_backup_ids_record($restoreid, 'role', $recrole->itemid, $match); | |
170 | // Build the rolemappings element for controller | |
171 | unset($role->id); | |
172 | unset($role->nameincourse); | |
173 | unset($role->nameincourse); | |
174 | $role->targetroleid = $match; | |
175 | $rolemappings->mappings[$recrole->itemid] = $role; | |
176 | // Prepare warning if no match found | |
177 | if (!$match) { | |
178 | $problems['warnings'][] = get_string('cannotfindassignablerole', 'backup', $role->name); | |
179 | } | |
180 | } | |
181 | } | |
182 | $rs->close(); | |
183 | return $problems; | |
184 | } | |
185 | ||
e7b24943 RT |
186 | /** |
187 | * Return cached backup id's | |
188 | * | |
189 | * @param int $restoreid id of backup | |
190 | * @param string $itemname name of the item | |
191 | * @param int $itemid id of item | |
192 | * @return array backup id's | |
193 | * @todo MDL-25290 replace static backupids* with MUC code | |
194 | */ | |
7f98b12f TL |
195 | protected static function get_backup_ids_cached($restoreid, $itemname, $itemid) { |
196 | global $DB; | |
197 | ||
198 | $key = "$itemid $itemname $restoreid"; | |
199 | ||
e7b24943 RT |
200 | // If record exists in cache then return. |
201 | if (isset(self::$backupidsexist[$key]) && isset(self::$backupidscache[$key])) { | |
202 | // Return a copy of cached data, to avoid any alterations in cached data. | |
203 | return clone self::$backupidscache[$key]; | |
7f98b12f TL |
204 | } |
205 | ||
e7b24943 RT |
206 | // Clean cache, if it's full. |
207 | if (self::$backupidscachesize <= 0) { | |
208 | // Remove some records, to keep memory in limit. | |
209 | self::$backupidscache = array_slice(self::$backupidscache, self::$backupidsslice, null, true); | |
210 | self::$backupidscachesize = self::$backupidscachesize + self::$backupidsslice; | |
211 | } | |
212 | if (self::$backupidsexistsize <= 0) { | |
213 | self::$backupidsexist = array_slice(self::$backupidsexist, self::$backupidsslice, null, true); | |
214 | self::$backupidsexistsize = self::$backupidsexistsize + self::$backupidsslice; | |
7f98b12f TL |
215 | } |
216 | ||
e7b24943 | 217 | // Retrive record from database. |
7f98b12f TL |
218 | $record = array( |
219 | 'backupid' => $restoreid, | |
220 | 'itemname' => $itemname, | |
221 | 'itemid' => $itemid | |
222 | ); | |
e7b24943 RT |
223 | if ($dbrec = $DB->get_record('backup_ids_temp', $record)) { |
224 | self::$backupidsexist[$key] = $dbrec->id; | |
225 | self::$backupidscache[$key] = $dbrec; | |
226 | self::$backupidscachesize--; | |
227 | self::$backupidsexistsize--; | |
228 | return $dbrec; | |
229 | } else { | |
230 | return false; | |
7f98b12f | 231 | } |
7f98b12f TL |
232 | } |
233 | ||
e7b24943 RT |
234 | /** |
235 | * Cache backup ids' | |
236 | * | |
237 | * @param int $restoreid id of backup | |
238 | * @param string $itemname name of the item | |
239 | * @param int $itemid id of item | |
240 | * @param array $extrarecord extra record which needs to be updated | |
241 | * @return void | |
242 | * @todo MDL-25290 replace static BACKUP_IDS_* with MUC code | |
243 | */ | |
7f98b12f TL |
244 | protected static function set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord) { |
245 | global $DB; | |
246 | ||
247 | $key = "$itemid $itemname $restoreid"; | |
248 | ||
e7b24943 RT |
249 | $record = array( |
250 | 'backupid' => $restoreid, | |
251 | 'itemname' => $itemname, | |
252 | 'itemid' => $itemid, | |
253 | ); | |
254 | ||
255 | // If record is not cached then add one. | |
256 | if (!isset(self::$backupidsexist[$key])) { | |
257 | // If we have this record in db, then just update this. | |
258 | if ($existingrecord = $DB->get_record('backup_ids_temp', $record)) { | |
259 | self::$backupidsexist[$key] = $existingrecord->id; | |
260 | self::$backupidsexistsize--; | |
261 | self::update_backup_cached_record($record, $extrarecord, $key, $existingrecord); | |
262 | } else { | |
263 | // Add new record to cache and db. | |
264 | $recorddefault = array ( | |
265 | 'newitemid' => 0, | |
266 | 'parentitemid' => null, | |
267 | 'info' => null); | |
268 | $record = array_merge($record, $recorddefault, $extrarecord); | |
269 | $record['id'] = $DB->insert_record('backup_ids_temp', $record); | |
270 | self::$backupidsexist[$key] = $record['id']; | |
271 | self::$backupidsexistsize--; | |
272 | if (self::$backupidscachesize > 0) { | |
273 | // Cache new records if we haven't got many yet. | |
274 | self::$backupidscache[$key] = (object) $record; | |
275 | self::$backupidscachesize--; | |
276 | } | |
7f98b12f TL |
277 | } |
278 | } else { | |
e7b24943 RT |
279 | self::update_backup_cached_record($record, $extrarecord, $key); |
280 | } | |
281 | } | |
282 | ||
283 | /** | |
284 | * Updates existing backup record | |
285 | * | |
286 | * @param array $record record which needs to be updated | |
287 | * @param array $extrarecord extra record which needs to be updated | |
288 | * @param string $key unique key which is used to identify cached record | |
289 | * @param stdClass $existingrecord (optional) existing record | |
290 | */ | |
291 | protected static function update_backup_cached_record($record, $extrarecord, $key, $existingrecord = null) { | |
292 | global $DB; | |
293 | // Update only if extrarecord is not empty. | |
294 | if (!empty($extrarecord)) { | |
295 | $extrarecord['id'] = self::$backupidsexist[$key]; | |
296 | $DB->update_record('backup_ids_temp', $extrarecord); | |
297 | // Update existing cache or add new record to cache. | |
298 | if (isset(self::$backupidscache[$key])) { | |
299 | $record = array_merge((array)self::$backupidscache[$key], $extrarecord); | |
300 | self::$backupidscache[$key] = (object) $record; | |
301 | } else if (self::$backupidscachesize > 0) { | |
302 | if ($existingrecord) { | |
303 | self::$backupidscache[$key] = $existingrecord; | |
304 | } else { | |
305 | // Retrive record from database and cache updated records. | |
306 | self::$backupidscache[$key] = $DB->get_record('backup_ids_temp', $record); | |
7f98b12f | 307 | } |
e7b24943 RT |
308 | $record = array_merge((array)self::$backupidscache[$key], $extrarecord); |
309 | self::$backupidscache[$key] = (object) $record; | |
310 | self::$backupidscachesize--; | |
7f98b12f TL |
311 | } |
312 | } | |
313 | } | |
314 | ||
f0852f47 EL |
315 | /** |
316 | * Reset the ids caches completely | |
317 | * | |
318 | * Any destructive operation (partial delete, truncate, drop or recreate) performed | |
319 | * with the backup_ids table must cause the backup_ids caches to be | |
320 | * invalidated by calling this method. See MDL-33630. | |
321 | * | |
322 | * Note that right now, the only operation of that type is the recreation | |
323 | * (drop & restore) of the table that may happen once the prechecks have ended. All | |
324 | * the rest of operations are always routed via {@link set_backup_ids_record()}, 1 by 1, | |
325 | * keeping the caches on sync. | |
326 | * | |
327 | * @todo MDL-25290 static should be replaced with MUC code. | |
328 | */ | |
329 | public static function reset_backup_ids_cached() { | |
330 | // Reset the ids cache. | |
331 | $cachetoadd = count(self::$backupidscache); | |
332 | self::$backupidscache = array(); | |
333 | self::$backupidscachesize = self::$backupidscachesize + $cachetoadd; | |
334 | // Reset the exists cache. | |
335 | $existstoadd = count(self::$backupidsexist); | |
336 | self::$backupidsexist = array(); | |
337 | self::$backupidsexistsize = self::$backupidsexistsize + $existstoadd; | |
338 | } | |
339 | ||
8d4e41f4 EL |
340 | /** |
341 | * Given one role, as loaded from XML, perform the best possible matching against the assignable | |
342 | * roles, using different fallback alternatives (shortname, archetype, editingteacher => teacher, defaultcourseroleid) | |
343 | * returning the id of the best matching role or 0 if no match is found | |
344 | */ | |
345 | protected static function get_best_assignable_role($role, $courseid, $userid, $samesite) { | |
346 | global $CFG, $DB; | |
347 | ||
348 | // Gather various information about roles | |
349 | $coursectx = get_context_instance(CONTEXT_COURSE, $courseid); | |
350 | $allroles = $DB->get_records('role'); | |
351 | $assignablerolesshortname = get_assignable_roles($coursectx, ROLENAME_SHORT, false, $userid); | |
352 | ||
353 | // Note: under 1.9 we had one function restore_samerole() that performed one complete | |
354 | // matching of roles (all caps) and if match was found the mapping was availabe bypassing | |
355 | // any assignable_roles() security. IMO that was wrong and we must not allow such | |
356 | // mappings anymore. So we have left that matching strategy out in 2.0 | |
357 | ||
358 | // Empty assignable roles, mean no match possible | |
359 | if (empty($assignablerolesshortname)) { | |
360 | return 0; | |
361 | } | |
362 | ||
363 | // Match by shortname | |
364 | if ($match = array_search($role->shortname, $assignablerolesshortname)) { | |
365 | return $match; | |
366 | } | |
367 | ||
368 | // Match by archetype | |
369 | list($in_sql, $in_params) = $DB->get_in_or_equal(array_keys($assignablerolesshortname)); | |
370 | $params = array_merge(array($role->archetype), $in_params); | |
371 | if ($rec = $DB->get_record_select('role', "archetype = ? AND id $in_sql", $params, 'id', IGNORE_MULTIPLE)) { | |
372 | return $rec->id; | |
373 | } | |
374 | ||
375 | // Match editingteacher to teacher (happens a lot, from 1.9) | |
376 | if ($role->shortname == 'editingteacher' && in_array('teacher', $assignablerolesshortname)) { | |
377 | return array_search('teacher', $assignablerolesshortname); | |
378 | } | |
379 | ||
380 | // No match, return 0 | |
381 | return 0; | |
71a50b13 EL |
382 | } |
383 | ||
8d4e41f4 | 384 | |
71a50b13 EL |
385 | /** |
386 | * Process the loaded roles, looking for their best mapping or skipping | |
387 | * Any error will cause exception. Note this is one wrapper over | |
388 | * precheck_included_roles, that contains all the logic, but returns | |
389 | * errors/warnings instead and is executed as part of the restore prechecks | |
390 | */ | |
8d4e41f4 | 391 | public static function process_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings) { |
71a50b13 EL |
392 | global $DB; |
393 | ||
394 | // Just let precheck_included_roles() to do all the hard work | |
8d4e41f4 | 395 | $problems = self::precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings); |
71a50b13 EL |
396 | |
397 | // With problems of type error, throw exception, shouldn't happen if prechecks executed | |
398 | if (array_key_exists('errors', $problems)) { | |
399 | throw new restore_dbops_exception('restore_problems_processing_roles', null, implode(', ', $problems['errors'])); | |
400 | } | |
401 | } | |
402 | ||
482aac65 EL |
403 | /** |
404 | * Load the needed users.xml file to backup_ids table for future reference | |
405 | */ | |
406 | public static function load_users_to_tempids($restoreid, $usersfile) { | |
407 | ||
408 | if (!file_exists($usersfile)) { // Shouldn't happen ever, but... | |
2df0f295 | 409 | throw new backup_helper_exception('missing_users_xml_file', $usersfile); |
482aac65 EL |
410 | } |
411 | // Let's parse, custom processor will do its work, sending info to DB | |
412 | $xmlparser = new progressive_parser(); | |
413 | $xmlparser->set_file($usersfile); | |
414 | $xmlprocessor = new restore_users_parser_processor($restoreid); | |
415 | $xmlparser->set_processor($xmlprocessor); | |
416 | $xmlparser->process(); | |
417 | } | |
418 | ||
41941110 EL |
419 | /** |
420 | * Load the needed questions.xml file to backup_ids table for future reference | |
421 | */ | |
422 | public static function load_categories_and_questions_to_tempids($restoreid, $questionsfile) { | |
423 | ||
424 | if (!file_exists($questionsfile)) { // Shouldn't happen ever, but... | |
425 | throw new backup_helper_exception('missing_questions_xml_file', $questionsfile); | |
426 | } | |
427 | // Let's parse, custom processor will do its work, sending info to DB | |
428 | $xmlparser = new progressive_parser(); | |
429 | $xmlparser->set_file($questionsfile); | |
430 | $xmlprocessor = new restore_questions_parser_processor($restoreid); | |
431 | $xmlparser->set_processor($xmlprocessor); | |
432 | $xmlparser->process(); | |
433 | } | |
434 | ||
435 | /** | |
436 | * Check all the included categories and questions, deciding the action to perform | |
437 | * for each one (mapping / creation) and returning one array of problems in case | |
438 | * something is wrong. | |
439 | * | |
440 | * There are some basic rules that the method below will always try to enforce: | |
441 | * | |
442 | * Rule1: Targets will be, always, calculated for *whole* question banks (a.k.a. contexid source), | |
443 | * so, given 2 question categories belonging to the same bank, their target bank will be | |
444 | * always the same. If not, we can be incurring into "fragmentation", leading to random/cloze | |
445 | * problems (qtypes having "child" questions). | |
446 | * | |
447 | * Rule2: The 'moodle/question:managecategory' and 'moodle/question:add' capabilities will be | |
448 | * checked before creating any category/question respectively and, if the cap is not allowed | |
449 | * into upper contexts (system, coursecat)) but in lower ones (course), the *whole* question bank | |
450 | * will be created there. | |
451 | * | |
452 | * Rule3: Coursecat question banks not existing in the target site will be created as course | |
453 | * (lower ctx) question banks, never as "guessed" coursecat question banks base on depth or so. | |
454 | * | |
455 | * Rule4: System question banks will be created at system context if user has perms to do so. Else they | |
456 | * will created as course (lower ctx) question banks (similary to rule3). In other words, course ctx | |
457 | * if always a fallback for system and coursecat question banks. | |
458 | * | |
459 | * Also, there are some notes to clarify the scope of this method: | |
460 | * | |
461 | * Note1: This method won't create any question category nor question at all. It simply will calculate | |
462 | * which actions (create/map) must be performed for each element and where, validating that all those | |
463 | * actions are doable by the user executing the restore operation. Any problem found will be | |
464 | * returned in the problems array, causing the restore process to stop with error. | |
465 | * | |
466 | * Note2: To decide if one question bank (all its question categories and questions) is going to be remapped, | |
467 | * then all the categories and questions must exist in the same target bank. If able to do so, missing | |
468 | * qcats and qs will be created (rule2). But if, at the end, something is missing, the whole question bank | |
469 | * will be recreated at course ctx (rule1), no matter if that duplicates some categories/questions. | |
470 | * | |
471 | * Note3: We'll be using the newitemid column in the temp_ids table to store the action to be performed | |
472 | * with each question category and question. newitemid = 0 means the qcat/q needs to be created and | |
473 | * any other value means the qcat/q is mapped. Also, for qcats, parentitemid will contain the target | |
474 | * context where the categories have to be created (but for module contexts where we'll keep the old | |
475 | * one until the activity is created) | |
476 | * | |
477 | * Note4: All these "actions" will be "executed" later by {@link restore_create_categories_and_questions} | |
478 | */ | |
479 | public static function precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite) { | |
480 | ||
481 | $problems = array(); | |
482 | ||
483 | // TODO: Check all qs, looking their qtypes are restorable | |
484 | ||
485 | // Precheck all qcats and qs looking for target contexts / warnings / errors | |
486 | list($syserr, $syswarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_SYSTEM); | |
487 | list($caterr, $catwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_COURSECAT); | |
488 | list($couerr, $couwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_COURSE); | |
489 | list($moderr, $modwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_MODULE); | |
490 | ||
491 | // Acummulate and handle errors and warnings | |
492 | $errors = array_merge($syserr, $caterr, $couerr, $moderr); | |
493 | $warnings = array_merge($syswarn, $catwarn, $couwarn, $modwarn); | |
494 | if (!empty($errors)) { | |
495 | $problems['errors'] = $errors; | |
496 | } | |
497 | if (!empty($warnings)) { | |
498 | $problems['warnings'] = $warnings; | |
499 | } | |
500 | return $problems; | |
501 | } | |
502 | ||
503 | /** | |
504 | * This function will process all the question banks present in restore | |
505 | * at some contextlevel (from CONTEXT_SYSTEM to CONTEXT_MODULE), finding | |
506 | * the target contexts where each bank will be restored and returning | |
507 | * warnings/errors as needed. | |
508 | * | |
509 | * Some contextlevels (system, coursecat), will delegate process to | |
510 | * course level if any problem is found (lack of permissions, non-matching | |
511 | * target context...). Other contextlevels (course, module) will | |
512 | * cause return error if some problem is found. | |
513 | * | |
514 | * At the end, if no errors were found, all the categories in backup_temp_ids | |
515 | * will be pointing (parentitemid) to the target context where they must be | |
516 | * created later in the restore process. | |
517 | * | |
518 | * Note: at the time these prechecks are executed, activities haven't been | |
519 | * created yet so, for CONTEXT_MODULE banks, we keep the old contextid | |
520 | * in the parentitemid field. Once the activity (and its context) has been | |
521 | * created, we'll update that context in the required qcats | |
522 | * | |
523 | * Caller {@link precheck_categories_and_questions} will, simply, execute | |
524 | * this function for all the contextlevels, acting as a simple controller | |
525 | * of warnings and errors. | |
526 | * | |
527 | * The function returns 2 arrays, one containing errors and another containing | |
528 | * warnings. Both empty if no errors/warnings are found. | |
529 | */ | |
530 | public static function prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, $contextlevel) { | |
531 | global $CFG, $DB; | |
532 | ||
533 | // To return any errors and warnings found | |
534 | $errors = array(); | |
535 | $warnings = array(); | |
536 | ||
537 | // Specify which fallbacks must be performed | |
538 | $fallbacks = array( | |
539 | CONTEXT_SYSTEM => CONTEXT_COURSE, | |
540 | CONTEXT_COURSECAT => CONTEXT_COURSE); | |
541 | ||
542 | // For any contextlevel, follow this process logic: | |
543 | // | |
544 | // 0) Iterate over each context (qbank) | |
545 | // 1) Iterate over each qcat in the context, matching by stamp for the found target context | |
546 | // 2a) No match, check if user can create qcat and q | |
547 | // 3a) User can, mark the qcat and all dependent qs to be created in that target context | |
548 | // 3b) User cannot, check if we are in some contextlevel with fallback | |
549 | // 4a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop | |
550 | // 4b) No fallback, error. End qcat loop. | |
551 | // 2b) Match, mark qcat to be mapped and iterate over each q, matching by stamp and version | |
552 | // 5a) No match, check if user can add q | |
553 | // 6a) User can, mark the q to be created | |
554 | // 6b) User cannot, check if we are in some contextlevel with fallback | |
555 | // 7a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop | |
556 | // 7b) No fallback, error. End qcat loop | |
557 | // 5b) Match, mark q to be mapped | |
558 | ||
559 | // Get all the contexts (question banks) in restore for the given contextlevel | |
560 | $contexts = self::restore_get_question_banks($restoreid, $contextlevel); | |
561 | ||
562 | // 0) Iterate over each context (qbank) | |
563 | foreach ($contexts as $contextid => $contextlevel) { | |
564 | // Init some perms | |
565 | $canmanagecategory = false; | |
566 | $canadd = false; | |
567 | // get categories in context (bank) | |
568 | $categories = self::restore_get_question_categories($restoreid, $contextid); | |
569 | // cache permissions if $targetcontext is found | |
570 | if ($targetcontext = self::restore_find_best_target_context($categories, $courseid, $contextlevel)) { | |
571 | $canmanagecategory = has_capability('moodle/question:managecategory', $targetcontext, $userid); | |
572 | $canadd = has_capability('moodle/question:add', $targetcontext, $userid); | |
573 | } | |
574 | // 1) Iterate over each qcat in the context, matching by stamp for the found target context | |
575 | foreach ($categories as $category) { | |
576 | $matchcat = false; | |
577 | if ($targetcontext) { | |
578 | $matchcat = $DB->get_record('question_categories', array( | |
579 | 'contextid' => $targetcontext->id, | |
580 | 'stamp' => $category->stamp)); | |
581 | } | |
582 | // 2a) No match, check if user can create qcat and q | |
583 | if (!$matchcat) { | |
584 | // 3a) User can, mark the qcat and all dependent qs to be created in that target context | |
585 | if ($canmanagecategory && $canadd) { | |
586 | // Set parentitemid to targetcontext, BUT for CONTEXT_MODULE categories, where | |
587 | // we keep the source contextid unmodified (for easier matching later when the | |
588 | // activities are created) | |
589 | $parentitemid = $targetcontext->id; | |
590 | if ($contextlevel == CONTEXT_MODULE) { | |
591 | $parentitemid = null; // null means "not modify" a.k.a. leave original contextid | |
592 | } | |
593 | self::set_backup_ids_record($restoreid, 'question_category', $category->id, 0, $parentitemid); | |
594 | // Nothing else to mark, newitemid = 0 means create | |
595 | ||
596 | // 3b) User cannot, check if we are in some contextlevel with fallback | |
597 | } else { | |
598 | // 4a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop | |
599 | if (array_key_exists($contextlevel, $fallbacks)) { | |
600 | foreach ($categories as $movedcat) { | |
601 | $movedcat->contextlevel = $fallbacks[$contextlevel]; | |
602 | self::set_backup_ids_record($restoreid, 'question_category', $movedcat->id, 0, $contextid, $movedcat); | |
603 | // Warn about the performed fallback | |
604 | $warnings[] = get_string('qcategory2coursefallback', 'backup', $movedcat); | |
605 | } | |
606 | ||
607 | // 4b) No fallback, error. End qcat loop. | |
608 | } else { | |
609 | $errors[] = get_string('qcategorycannotberestored', 'backup', $category); | |
610 | } | |
611 | break; // out from qcat loop (both 4a and 4b), we have decided about ALL categories in context (bank) | |
612 | } | |
613 | ||
614 | // 2b) Match, mark qcat to be mapped and iterate over each q, matching by stamp and version | |
615 | } else { | |
616 | self::set_backup_ids_record($restoreid, 'question_category', $category->id, $matchcat->id, $targetcontext->id); | |
617 | $questions = self::restore_get_questions($restoreid, $category->id); | |
618 | foreach ($questions as $question) { | |
619 | $matchq = $DB->get_record('question', array( | |
620 | 'category' => $matchcat->id, | |
621 | 'stamp' => $question->stamp, | |
622 | 'version' => $question->version)); | |
623 | // 5a) No match, check if user can add q | |
624 | if (!$matchq) { | |
625 | // 6a) User can, mark the q to be created | |
626 | if ($canadd) { | |
627 | // Nothing to mark, newitemid means create | |
628 | ||
629 | // 6b) User cannot, check if we are in some contextlevel with fallback | |
630 | } else { | |
631 | // 7a) There is fallback, move ALL the qcats to fallback, warn. End qcat loo | |
632 | if (array_key_exists($contextlevel, $fallbacks)) { | |
633 | foreach ($categories as $movedcat) { | |
634 | $movedcat->contextlevel = $fallbacks[$contextlevel]; | |
635 | self::set_backup_ids_record($restoreid, 'question_category', $movedcat->id, 0, $contextid, $movedcat); | |
636 | // Warn about the performed fallback | |
637 | $warnings[] = get_string('question2coursefallback', 'backup', $movedcat); | |
638 | } | |
639 | ||
640 | // 7b) No fallback, error. End qcat loop | |
641 | } else { | |
642 | $errors[] = get_string('questioncannotberestored', 'backup', $question); | |
643 | } | |
644 | break 2; // out from qcat loop (both 7a and 7b), we have decided about ALL categories in context (bank) | |
645 | } | |
646 | ||
647 | // 5b) Match, mark q to be mapped | |
648 | } else { | |
649 | self::set_backup_ids_record($restoreid, 'question', $question->id, $matchq->id); | |
650 | } | |
651 | } | |
652 | } | |
653 | } | |
654 | } | |
655 | ||
656 | return array($errors, $warnings); | |
657 | } | |
658 | ||
659 | /** | |
660 | * Return one array of contextid => contextlevel pairs | |
661 | * of question banks to be checked for one given restore operation | |
662 | * ordered from CONTEXT_SYSTEM downto CONTEXT_MODULE | |
663 | * If contextlevel is specified, then only banks corresponding to | |
664 | * that level are returned | |
665 | */ | |
666 | public static function restore_get_question_banks($restoreid, $contextlevel = null) { | |
667 | global $DB; | |
668 | ||
669 | $results = array(); | |
670 | $qcats = $DB->get_records_sql("SELECT itemid, parentitemid AS contextid | |
671 | FROM {backup_ids_temp} | |
672 | WHERE backupid = ? | |
673 | AND itemname = 'question_category'", array($restoreid)); | |
674 | foreach ($qcats as $qcat) { | |
675 | // If this qcat context haven't been acummulated yet, do that | |
676 | if (!isset($results[$qcat->contextid])) { | |
677 | $temprec = self::get_backup_ids_record($restoreid, 'question_category', $qcat->itemid); | |
678 | // Filter by contextlevel if necessary | |
679 | if (is_null($contextlevel) || $contextlevel == $temprec->info->contextlevel) { | |
680 | $results[$qcat->contextid] = $temprec->info->contextlevel; | |
681 | } | |
682 | } | |
683 | } | |
684 | // Sort by value (contextlevel from CONTEXT_SYSTEM downto CONTEXT_MODULE) | |
685 | asort($results); | |
686 | return $results; | |
687 | } | |
688 | ||
689 | /** | |
690 | * Return one array of question_category records for | |
691 | * a given restore operation and one restore context (question bank) | |
692 | */ | |
693 | public static function restore_get_question_categories($restoreid, $contextid) { | |
694 | global $DB; | |
695 | ||
696 | $results = array(); | |
697 | $qcats = $DB->get_records_sql("SELECT itemid | |
698 | FROM {backup_ids_temp} | |
699 | WHERE backupid = ? | |
700 | AND itemname = 'question_category' | |
701 | AND parentitemid = ?", array($restoreid, $contextid)); | |
702 | foreach ($qcats as $qcat) { | |
703 | $temprec = self::get_backup_ids_record($restoreid, 'question_category', $qcat->itemid); | |
704 | $results[$qcat->itemid] = $temprec->info; | |
705 | } | |
706 | return $results; | |
707 | } | |
708 | ||
709 | /** | |
710 | * Calculates the best context found to restore one collection of qcats, | |
711 | * al them belonging to the same context (question bank), returning the | |
712 | * target context found (object) or false | |
713 | */ | |
714 | public static function restore_find_best_target_context($categories, $courseid, $contextlevel) { | |
715 | global $DB; | |
716 | ||
717 | $targetcontext = false; | |
718 | ||
719 | // Depending of $contextlevel, we perform different actions | |
720 | switch ($contextlevel) { | |
721 | // For system is easy, the best context is the system context | |
722 | case CONTEXT_SYSTEM: | |
723 | $targetcontext = get_context_instance(CONTEXT_SYSTEM); | |
724 | break; | |
725 | ||
726 | // For coursecat, we are going to look for stamps in all the | |
727 | // course categories between CONTEXT_SYSTEM and CONTEXT_COURSE | |
728 | // (i.e. in all the course categories in the path) | |
729 | // | |
730 | // And only will return one "best" target context if all the | |
731 | // matches belong to ONE and ONLY ONE context. If multiple | |
732 | // matches are found, that means that there is some annoying | |
733 | // qbank "fragmentation" in the categories, so we'll fallback | |
734 | // to create the qbank at course level | |
735 | case CONTEXT_COURSECAT: | |
736 | // Build the array of stamps we are going to match | |
737 | $stamps = array(); | |
738 | foreach ($categories as $category) { | |
739 | $stamps[] = $category->stamp; | |
740 | } | |
741 | $contexts = array(); | |
742 | // Build the array of contexts we are going to look | |
743 | $systemctx = get_context_instance(CONTEXT_SYSTEM); | |
744 | $coursectx = get_context_instance(CONTEXT_COURSE, $courseid); | |
745 | $parentctxs= get_parent_contexts($coursectx); | |
746 | foreach ($parentctxs as $parentctx) { | |
747 | // Exclude system context | |
748 | if ($parentctx == $systemctx->id) { | |
749 | continue; | |
750 | } | |
751 | $contexts[] = $parentctx; | |
752 | } | |
753 | if (!empty($stamps) && !empty($contexts)) { | |
754 | // Prepare the query | |
755 | list($stamp_sql, $stamp_params) = $DB->get_in_or_equal($stamps); | |
756 | list($context_sql, $context_params) = $DB->get_in_or_equal($contexts); | |
757 | $sql = "SELECT contextid | |
758 | FROM {question_categories} | |
759 | WHERE stamp $stamp_sql | |
760 | AND contextid $context_sql"; | |
761 | $params = array_merge($stamp_params, $context_params); | |
762 | $matchingcontexts = $DB->get_records_sql($sql, $params); | |
763 | // Only if ONE and ONLY ONE context is found, use it as valid target | |
764 | if (count($matchingcontexts) == 1) { | |
765 | $targetcontext = get_context_instance_by_id(reset($matchingcontexts)->contextid); | |
766 | } | |
767 | } | |
768 | break; | |
769 | ||
770 | // For course is easy, the best context is the course context | |
771 | case CONTEXT_COURSE: | |
772 | $targetcontext = get_context_instance(CONTEXT_COURSE, $courseid); | |
773 | break; | |
774 | ||
775 | // For module is easy, there is not best context, as far as the | |
776 | // activity hasn't been created yet. So we return context course | |
777 | // for them, so permission checks and friends will work. Note this | |
778 | // case is handled by {@link prechek_precheck_qbanks_by_level} | |
779 | // in an special way | |
780 | case CONTEXT_MODULE: | |
781 | $targetcontext = get_context_instance(CONTEXT_COURSE, $courseid); | |
782 | break; | |
783 | } | |
784 | return $targetcontext; | |
785 | } | |
786 | ||
787 | /** | |
788 | * Return one array of question records for | |
789 | * a given restore operation and one question category | |
790 | */ | |
791 | public static function restore_get_questions($restoreid, $qcatid) { | |
792 | global $DB; | |
793 | ||
794 | $results = array(); | |
795 | $qs = $DB->get_records_sql("SELECT itemid | |
796 | FROM {backup_ids_temp} | |
797 | WHERE backupid = ? | |
798 | AND itemname = 'question' | |
799 | AND parentitemid = ?", array($restoreid, $qcatid)); | |
800 | foreach ($qs as $q) { | |
801 | $temprec = self::get_backup_ids_record($restoreid, 'question', $q->itemid); | |
802 | $results[$q->itemid] = $temprec->info; | |
803 | } | |
804 | return $results; | |
805 | } | |
806 | ||
2df0f295 EL |
807 | /** |
808 | * Given one component/filearea/context and | |
809 | * optionally one source itemname to match itemids | |
810 | * put the corresponding files in the pool | |
811 | */ | |
41941110 | 812 | public static function send_files_to_pool($basepath, $restoreid, $component, $filearea, $oldcontextid, $dfltuserid, $itemname = null, $olditemid = null, $forcenewcontextid = null, $skipparentitemidctxmatch = false) { |
2df0f295 EL |
813 | global $DB; |
814 | ||
41941110 EL |
815 | if ($forcenewcontextid) { |
816 | // Some components can have "forced" new contexts (example: questions can end belonging to non-standard context mappings, | |
817 | // with questions originally at system/coursecat context in source being restored to course context in target). So we need | |
818 | // to be able to force the new contextid | |
819 | $newcontextid = $forcenewcontextid; | |
820 | } else { | |
821 | // Get new context, must exist or this will fail | |
822 | if (!$newcontextid = self::get_backup_ids_record($restoreid, 'context', $oldcontextid)->newitemid) { | |
823 | throw new restore_dbops_exception('unknown_context_mapping', $oldcontextid); | |
824 | } | |
825 | } | |
826 | ||
827 | // Sometimes it's possible to have not the oldcontextids stored into backup_ids_temp->parentitemid | |
828 | // columns (because we have used them to store other information). This happens usually with | |
829 | // all the question related backup_ids_temp records. In that case, it's safe to ignore that | |
830 | // matching as far as we are always restoring for well known oldcontexts and olditemids | |
831 | $parentitemctxmatchsql = ' AND i.parentitemid = f.contextid '; | |
832 | if ($skipparentitemidctxmatch) { | |
833 | $parentitemctxmatchsql = ''; | |
2df0f295 EL |
834 | } |
835 | ||
b212f87e | 836 | // Important: remember how files have been loaded to backup_files_temp |
2df0f295 EL |
837 | // - info: contains the whole original object (times, names...) |
838 | // (all them being original ids as loaded from xml) | |
839 | ||
840 | // itemname = null, we are going to match only by context, no need to use itemid (all them are 0) | |
841 | if ($itemname == null) { | |
70c1ad58 | 842 | $sql = 'SELECT contextid, component, filearea, itemid, itemid AS newitemid, info |
b8bb45b0 | 843 | FROM {backup_files_temp} |
2df0f295 | 844 | WHERE backupid = ? |
b8bb45b0 EL |
845 | AND contextid = ? |
846 | AND component = ? | |
847 | AND filearea = ?'; | |
848 | $params = array($restoreid, $oldcontextid, $component, $filearea); | |
2df0f295 | 849 | |
b8bb45b0 | 850 | // itemname not null, going to join with backup_ids to perform the old-new mapping of itemids |
2df0f295 | 851 | } else { |
41941110 | 852 | $sql = "SELECT f.contextid, f.component, f.filearea, f.itemid, i.newitemid, f.info |
b8bb45b0 | 853 | FROM {backup_files_temp} f |
2df0f295 | 854 | JOIN {backup_ids_temp} i ON i.backupid = f.backupid |
41941110 | 855 | $parentitemctxmatchsql |
b8bb45b0 | 856 | AND i.itemid = f.itemid |
2df0f295 | 857 | WHERE f.backupid = ? |
b8bb45b0 EL |
858 | AND f.contextid = ? |
859 | AND f.component = ? | |
860 | AND f.filearea = ? | |
41941110 | 861 | AND i.itemname = ?"; |
b8bb45b0 | 862 | $params = array($restoreid, $oldcontextid, $component, $filearea, $itemname); |
f2745cbe EL |
863 | if ($olditemid !== null) { // Just process ONE olditemid intead of the whole itemname |
864 | $sql .= ' AND i.itemid = ?'; | |
865 | $params[] = $olditemid; | |
866 | } | |
2df0f295 EL |
867 | } |
868 | ||
2df0f295 EL |
869 | $fs = get_file_storage(); // Get moodle file storage |
870 | $basepath = $basepath . '/files/';// Get backup file pool base | |
71a50b13 | 871 | $rs = $DB->get_recordset_sql($sql, $params); |
2df0f295 | 872 | foreach ($rs as $rec) { |
b8bb45b0 | 873 | $file = (object)unserialize(base64_decode($rec->info)); |
67233725 DC |
874 | |
875 | $isreference = !empty($file->repositoryid); | |
876 | ||
2df0f295 EL |
877 | // ignore root dirs (they are created automatically) |
878 | if ($file->filepath == '/' && $file->filename == '.') { | |
879 | continue; | |
880 | } | |
84cdf7de EL |
881 | // set the best possible user |
882 | $mappeduser = self::get_backup_ids_record($restoreid, 'user', $file->userid); | |
883 | $file->userid = !empty($mappeduser) ? $mappeduser->newitemid : $dfltuserid; | |
2df0f295 EL |
884 | // dir found (and not root one), let's create if |
885 | if ($file->filename == '.') { | |
84cdf7de | 886 | $fs->create_directory($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->userid); |
2df0f295 EL |
887 | continue; |
888 | } | |
67233725 | 889 | |
2df0f295 EL |
890 | // arrived here, file found |
891 | // Find file in backup pool | |
2b199e7c | 892 | $backuppath = $basepath . backup_file_manager::get_backup_content_file_location($file->contenthash); |
67233725 DC |
893 | |
894 | if (!file_exists($backuppath) && !$isreference) { | |
2df0f295 EL |
895 | throw new restore_dbops_exception('file_not_found_in_pool', $file); |
896 | } | |
897 | if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) { | |
898 | $file_record = array( | |
899 | 'contextid' => $newcontextid, | |
900 | 'component' => $component, | |
901 | 'filearea' => $filearea, | |
902 | 'itemid' => $rec->newitemid, | |
903 | 'filepath' => $file->filepath, | |
904 | 'filename' => $file->filename, | |
905 | 'timecreated' => $file->timecreated, | |
906 | 'timemodified'=> $file->timemodified, | |
84cdf7de | 907 | 'userid' => $file->userid, |
2df0f295 | 908 | 'author' => $file->author, |
84cdf7de EL |
909 | 'license' => $file->license, |
910 | 'sortorder' => $file->sortorder); | |
67233725 DC |
911 | if ($isreference) { |
912 | $fs->create_file_from_reference($file_record, $file->repositoryid, $file->reference); | |
913 | } else { | |
914 | $fs->create_file_from_pathname($file_record, $backuppath); | |
915 | } | |
2df0f295 EL |
916 | } |
917 | } | |
918 | $rs->close(); | |
919 | } | |
920 | ||
482aac65 EL |
921 | /** |
922 | * Given one restoreid, create in DB all the users present | |
923 | * in backup_ids having newitemid = 0, as far as | |
924 | * precheck_included_users() have left them there | |
925 | * ready to be created. Also, annotate their newids | |
926 | * once created for later reference | |
927 | */ | |
ac6dc09c | 928 | public static function create_included_users($basepath, $restoreid, $userid) { |
482aac65 EL |
929 | global $CFG, $DB; |
930 | ||
931 | $authcache = array(); // Cache to get some bits from authentication plugins | |
932 | $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search later | |
933 | $themes = get_list_of_themes(); // Get themes for quick search later | |
934 | ||
935 | // Iterate over all the included users with newitemid = 0, have to create them | |
936 | $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid'); | |
937 | foreach ($rs as $recuser) { | |
938 | $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info; | |
939 | ||
940 | // if user lang doesn't exist here, use site default | |
941 | if (!array_key_exists($user->lang, $languages)) { | |
942 | $user->lang = $CFG->lang; | |
943 | } | |
944 | ||
945 | // if user theme isn't available on target site or they are disabled, reset theme | |
946 | if (!empty($user->theme)) { | |
947 | if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) { | |
948 | $user->theme = ''; | |
949 | } | |
950 | } | |
951 | ||
952 | // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id | |
953 | // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual | |
954 | if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) { | |
955 | // Respect registerauth | |
956 | if ($CFG->registerauth == 'email') { | |
957 | $user->auth = 'email'; | |
958 | } else { | |
959 | $user->auth = 'manual'; | |
960 | } | |
961 | } | |
962 | unset($user->mnethosturl); // Not needed anymore | |
963 | ||
964 | // Disable pictures based on global setting | |
965 | if (!empty($CFG->disableuserimages)) { | |
966 | $user->picture = 0; | |
967 | } | |
968 | ||
969 | // We need to analyse the AUTH field to recode it: | |
970 | // - if the auth isn't enabled in target site, $CFG->registerauth will decide | |
971 | // - finally, if the auth resulting isn't enabled, default to 'manual' | |
972 | if (!is_enabled_auth($user->auth)) { | |
973 | if ($CFG->registerauth == 'email') { | |
974 | $user->auth = 'email'; | |
975 | } else { | |
976 | $user->auth = 'manual'; | |
977 | } | |
978 | } | |
979 | if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled | |
980 | $user->auth = 'manual'; | |
981 | } | |
982 | ||
983 | // Now that we know the auth method, for users to be created without pass | |
984 | // if password handling is internal and reset password is available | |
985 | // we set the password to "restored" (plain text), so the login process | |
986 | // will know how to handle that situation in order to allow the user to | |
987 | // recover the password. MDL-20846 | |
988 | if (empty($user->password)) { // Only if restore comes without password | |
989 | if (!array_key_exists($user->auth, $authcache)) { // Not in cache | |
990 | $userauth = new stdClass(); | |
991 | $authplugin = get_auth_plugin($user->auth); | |
992 | $userauth->preventpassindb = $authplugin->prevent_local_passwords(); | |
993 | $userauth->isinternal = $authplugin->is_internal(); | |
994 | $userauth->canresetpwd = $authplugin->can_reset_password(); | |
995 | $authcache[$user->auth] = $userauth; | |
996 | } else { | |
997 | $userauth = $authcache[$user->auth]; // Get from cache | |
998 | } | |
999 | ||
1000 | // Most external plugins do not store passwords locally | |
1001 | if (!empty($userauth->preventpassindb)) { | |
1002 | $user->password = 'not cached'; | |
1003 | ||
1004 | // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark | |
1005 | } else if ($userauth->isinternal and $userauth->canresetpwd) { | |
1006 | $user->password = 'restored'; | |
1007 | } | |
1008 | } | |
1009 | ||
1010 | // Creating new user, we must reset the policyagreed always | |
1011 | $user->policyagreed = 0; | |
1012 | ||
1013 | // Set time created if empty | |
1014 | if (empty($user->timecreated)) { | |
1015 | $user->timecreated = time(); | |
1016 | } | |
1017 | ||
1018 | // Done, let's create the user and annotate its id | |
1019 | $newuserid = $DB->insert_record('user', $user); | |
1020 | self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid); | |
1021 | // Let's create the user context and annotate it (we need it for sure at least for files) | |
1acad8ee EL |
1022 | // but for deleted users that don't have a context anymore (MDL-30192). We are done for them |
1023 | // and nothing else (custom fields, prefs, tags, files...) will be created. | |
1024 | if (empty($user->deleted)) { | |
1025 | $newuserctxid = $user->deleted ? 0 : get_context_instance(CONTEXT_USER, $newuserid)->id; | |
1026 | self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid); | |
1027 | ||
1028 | // Process custom fields | |
1029 | if (isset($user->custom_fields)) { // if present in backup | |
1030 | foreach($user->custom_fields['custom_field'] as $udata) { | |
1031 | $udata = (object)$udata; | |
1032 | // If the profile field has data and the profile shortname-datatype is defined in server | |
1033 | if ($udata->field_data) { | |
1034 | if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) { | |
1035 | /// Insert the user_custom_profile_field | |
1036 | $rec = new stdClass(); | |
1037 | $rec->userid = $newuserid; | |
1038 | $rec->fieldid = $field->id; | |
1039 | $rec->data = $udata->field_data; | |
1040 | $DB->insert_record('user_info_data', $rec); | |
1041 | } | |
482aac65 EL |
1042 | } |
1043 | } | |
1044 | } | |
482aac65 | 1045 | |
1acad8ee EL |
1046 | // Process tags |
1047 | if (!empty($CFG->usetags) && isset($user->tags)) { // if enabled in server and present in backup | |
1048 | $tags = array(); | |
1049 | foreach($user->tags['tag'] as $usertag) { | |
1050 | $usertag = (object)$usertag; | |
1051 | $tags[] = $usertag->rawname; | |
1052 | } | |
1053 | tag_set('user', $newuserid, $tags); | |
482aac65 | 1054 | } |
482aac65 | 1055 | |
1acad8ee EL |
1056 | // Process preferences |
1057 | if (isset($user->preferences)) { // if present in backup | |
1058 | foreach($user->preferences['preference'] as $preference) { | |
1059 | $preference = (object)$preference; | |
1060 | // Prepare the record and insert it | |
1061 | $preference->userid = $newuserid; | |
1062 | $status = $DB->insert_record('user_preferences', $preference); | |
1063 | } | |
482aac65 | 1064 | } |
482aac65 | 1065 | |
1acad8ee EL |
1066 | // Create user files in pool (profile, icon, private) by context |
1067 | restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon', $recuser->parentitemid, $userid); | |
1068 | restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile', $recuser->parentitemid, $userid); | |
1acad8ee | 1069 | } |
482aac65 EL |
1070 | } |
1071 | $rs->close(); | |
1072 | } | |
1073 | ||
1074 | /** | |
1075 | * Given one user object (from backup file), perform all the neccesary | |
1076 | * checks is order to decide how that user will be handled on restore. | |
1077 | * | |
1078 | * Note the function requires $user->mnethostid to be already calculated | |
1079 | * so it's caller responsibility to set it | |
1080 | * | |
1081 | * This function is used both by @restore_precheck_users() and | |
1082 | * @restore_create_users() to get consistent results in both places | |
1083 | * | |
1084 | * It returns: | |
1085 | * - one user object (from DB), if match has been found and user will be remapped | |
1086 | * - boolean true if the user needs to be created | |
1087 | * - boolean false if some conflict happened and the user cannot be handled | |
1088 | * | |
1089 | * Each test is responsible for returning its results and interrupt | |
1090 | * execution. At the end, boolean true (user needs to be created) will be | |
1091 | * returned if no test has interrupted that. | |
1092 | * | |
1093 | * Here it's the logic applied, keep it updated: | |
1094 | * | |
1095 | * If restoring users from same site backup: | |
1096 | * 1A - Normal check: If match by id and username and mnethost => ok, return target user | |
1097 | * 1B - Handle users deleted in DB and "alive" in backup file: | |
1098 | * If match by id and mnethost and user is deleted in DB and | |
1099 | * (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user | |
1100 | * 1C - Handle users deleted in backup file and "alive" in DB: | |
1101 | * If match by id and mnethost and user is deleted in backup file | |
1102 | * and match by email = email_without_time(backup_email) => ok, return target user | |
1103 | * 1D - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false | |
1104 | * 1E - None of the above, return true => User needs to be created | |
1105 | * | |
1106 | * if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination): | |
1107 | * 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user | |
1108 | * 2B - Handle users deleted in DB and "alive" in backup file: | |
1109 | * 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and | |
1110 | * (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user | |
1111 | * 2B2 - If match by mnethost and user is deleted in DB and | |
1112 | * username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user | |
1113 | * (to cover situations were md5(username) wasn't implemented on delete we requiere both) | |
1114 | * 2C - Handle users deleted in backup file and "alive" in DB: | |
1115 | * If match mnethost and user is deleted in backup file | |
1116 | * and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user | |
1117 | * 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false | |
1118 | * 2E - None of the above, return true => User needs to be created | |
1119 | * | |
1120 | * Note: for DB deleted users email is stored in username field, hence we | |
1121 | * are looking there for emails. See delete_user() | |
1122 | * Note: for DB deleted users md5(username) is stored *sometimes* in the email field, | |
1123 | * hence we are looking there for usernames if not empty. See delete_user() | |
1124 | */ | |
1125 | protected static function precheck_user($user, $samesite) { | |
1126 | global $CFG, $DB; | |
1127 | ||
1128 | // Handle checks from same site backups | |
1129 | if ($samesite && empty($CFG->forcedifferentsitecheckingusersonrestore)) { | |
1130 | ||
1131 | // 1A - If match by id and username and mnethost => ok, return target user | |
1132 | if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) { | |
1133 | return $rec; // Matching user found, return it | |
1134 | } | |
1135 | ||
1136 | // 1B - Handle users deleted in DB and "alive" in backup file | |
1137 | // Note: for DB deleted users email is stored in username field, hence we | |
1138 | // are looking there for emails. See delete_user() | |
1139 | // Note: for DB deleted users md5(username) is stored *sometimes* in the email field, | |
1140 | // hence we are looking there for usernames if not empty. See delete_user() | |
1141 | // If match by id and mnethost and user is deleted in DB and | |
1142 | // match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user | |
1143 | if ($rec = $DB->get_record_sql("SELECT * | |
1144 | FROM {user} u | |
1145 | WHERE id = ? | |
1146 | AND mnethostid = ? | |
1147 | AND deleted = 1 | |
1148 | AND ( | |
ef6b3ba1 | 1149 | UPPER(username) LIKE UPPER(?) |
482aac65 EL |
1150 | OR ( |
1151 | ".$DB->sql_isnotempty('user', 'email', false, false)." | |
1152 | AND email = ? | |
1153 | ) | |
1154 | )", | |
1155 | array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) { | |
1156 | return $rec; // Matching user, deleted in DB found, return it | |
1157 | } | |
1158 | ||
1159 | // 1C - Handle users deleted in backup file and "alive" in DB | |
1160 | // If match by id and mnethost and user is deleted in backup file | |
1161 | // and match by email = email_without_time(backup_email) => ok, return target user | |
1162 | if ($user->deleted) { | |
1163 | // Note: for DB deleted users email is stored in username field, hence we | |
1164 | // are looking there for emails. See delete_user() | |
1165 | // Trim time() from email | |
1166 | $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username); | |
1167 | if ($rec = $DB->get_record_sql("SELECT * | |
1168 | FROM {user} u | |
1169 | WHERE id = ? | |
1170 | AND mnethostid = ? | |
ef6b3ba1 | 1171 | AND UPPER(email) = UPPER(?)", |
482aac65 EL |
1172 | array($user->id, $user->mnethostid, $trimemail))) { |
1173 | return $rec; // Matching user, deleted in backup file found, return it | |
1174 | } | |
1175 | } | |
1176 | ||
1177 | // 1D - If match by username and mnethost and doesn't match by id => conflict, return false | |
1178 | if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) { | |
1179 | if ($user->id != $rec->id) { | |
1180 | return false; // Conflict, username already exists and belongs to another id | |
1181 | } | |
1182 | } | |
1183 | ||
1184 | // Handle checks from different site backups | |
1185 | } else { | |
1186 | ||
1187 | // 2A - If match by username and mnethost and | |
1188 | // (email or non-zero firstaccess) => ok, return target user | |
1189 | if ($rec = $DB->get_record_sql("SELECT * | |
1190 | FROM {user} u | |
1191 | WHERE username = ? | |
1192 | AND mnethostid = ? | |
1193 | AND ( | |
ef6b3ba1 | 1194 | UPPER(email) = UPPER(?) |
482aac65 EL |
1195 | OR ( |
1196 | firstaccess != 0 | |
1197 | AND firstaccess = ? | |
1198 | ) | |
1199 | )", | |
1200 | array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) { | |
1201 | return $rec; // Matching user found, return it | |
1202 | } | |
1203 | ||
1204 | // 2B - Handle users deleted in DB and "alive" in backup file | |
1205 | // Note: for DB deleted users email is stored in username field, hence we | |
1206 | // are looking there for emails. See delete_user() | |
1207 | // Note: for DB deleted users md5(username) is stored *sometimes* in the email field, | |
1208 | // hence we are looking there for usernames if not empty. See delete_user() | |
1209 | // 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and | |
1210 | // (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user | |
1211 | if ($rec = $DB->get_record_sql("SELECT * | |
1212 | FROM {user} u | |
1213 | WHERE mnethostid = ? | |
1214 | AND deleted = 1 | |
1215 | AND ".$DB->sql_isnotempty('user', 'email', false, false)." | |
1216 | AND email = ? | |
1217 | AND ( | |
ef6b3ba1 | 1218 | UPPER(username) LIKE UPPER(?) |
482aac65 EL |
1219 | OR ( |
1220 | firstaccess != 0 | |
1221 | AND firstaccess = ? | |
1222 | ) | |
1223 | )", | |
1224 | array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) { | |
1225 | return $rec; // Matching user found, return it | |
1226 | } | |
1227 | ||
1228 | // 2B2 - If match by mnethost and user is deleted in DB and | |
1229 | // username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user | |
1230 | // (this covers situations where md5(username) wasn't being stored so we require both | |
1231 | // the email & non-zero firstaccess to match) | |
1232 | if ($rec = $DB->get_record_sql("SELECT * | |
1233 | FROM {user} u | |
1234 | WHERE mnethostid = ? | |
1235 | AND deleted = 1 | |
ef6b3ba1 | 1236 | AND UPPER(username) LIKE UPPER(?) |
482aac65 EL |
1237 | AND firstaccess != 0 |
1238 | AND firstaccess = ?", | |
1239 | array($user->mnethostid, $user->email.'.%', $user->firstaccess))) { | |
1240 | return $rec; // Matching user found, return it | |
1241 | } | |
1242 | ||
1243 | // 2C - Handle users deleted in backup file and "alive" in DB | |
1244 | // If match mnethost and user is deleted in backup file | |
1245 | // and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user | |
1246 | if ($user->deleted) { | |
1247 | // Note: for DB deleted users email is stored in username field, hence we | |
1248 | // are looking there for emails. See delete_user() | |
1249 | // Trim time() from email | |
1250 | $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username); | |
1251 | if ($rec = $DB->get_record_sql("SELECT * | |
1252 | FROM {user} u | |
1253 | WHERE mnethostid = ? | |
ef6b3ba1 | 1254 | AND UPPER(email) = UPPER(?) |
482aac65 EL |
1255 | AND firstaccess != 0 |
1256 | AND firstaccess = ?", | |
1257 | array($user->mnethostid, $trimemail, $user->firstaccess))) { | |
1258 | return $rec; // Matching user, deleted in backup file found, return it | |
1259 | } | |
1260 | } | |
1261 | ||
1262 | // 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false | |
1263 | if ($rec = $DB->get_record_sql("SELECT * | |
1264 | FROM {user} u | |
1265 | WHERE username = ? | |
1266 | AND mnethostid = ? | |
1267 | AND NOT ( | |
ef6b3ba1 | 1268 | UPPER(email) = UPPER(?) |
482aac65 EL |
1269 | OR ( |
1270 | firstaccess != 0 | |
1271 | AND firstaccess = ? | |
1272 | ) | |
1273 | )", | |
1274 | array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) { | |
1275 | return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess) | |
1276 | } | |
1277 | } | |
1278 | ||
1279 | // Arrived here, return true as the user will need to be created and no | |
1280 | // conflicts have been found in the logic above. This covers: | |
1281 | // 1E - else => user needs to be created, return true | |
1282 | // 2E - else => user needs to be created, return true | |
1283 | return true; | |
1284 | } | |
1285 | ||
1286 | /** | |
1287 | * Check all the included users, deciding the action to perform | |
1288 | * for each one (mapping / creation) and returning one array | |
1289 | * of problems in case something is wrong (lack of permissions, | |
1290 | * conficts) | |
1291 | */ | |
1292 | public static function precheck_included_users($restoreid, $courseid, $userid, $samesite) { | |
1293 | global $CFG, $DB; | |
1294 | ||
1295 | // To return any problem found | |
1296 | $problems = array(); | |
1297 | ||
1298 | // We are going to map mnethostid, so load all the available ones | |
1299 | $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id'); | |
1300 | ||
1301 | // Calculate the context we are going to use for capability checking | |
1302 | $context = get_context_instance(CONTEXT_COURSE, $courseid); | |
1303 | ||
1304 | // Calculate if we have perms to create users, by checking: | |
1305 | // to 'moodle/restore:createuser' and 'moodle/restore:userinfo' | |
1306 | // and also observe $CFG->disableusercreationonrestore | |
1307 | $cancreateuser = false; | |
1308 | if (has_capability('moodle/restore:createuser', $context, $userid) and | |
1309 | has_capability('moodle/restore:userinfo', $context, $userid) and | |
1310 | empty($CFG->disableusercreationonrestore)) { // Can create users | |
1311 | ||
1312 | $cancreateuser = true; | |
1313 | } | |
1314 | ||
1315 | // Iterate over all the included users | |
1316 | $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user'), '', 'itemid'); | |
1317 | foreach ($rs as $recuser) { | |
1318 | $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info; | |
1319 | ||
1320 | // Find the correct mnethostid for user before performing any further check | |
1321 | if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) { | |
1322 | $user->mnethostid = $CFG->mnet_localhost_id; | |
1323 | } else { | |
1324 | // fast url-to-id lookups | |
1325 | if (isset($mnethosts[$user->mnethosturl])) { | |
1326 | $user->mnethostid = $mnethosts[$user->mnethosturl]->id; | |
1327 | } else { | |
1328 | $user->mnethostid = $CFG->mnet_localhost_id; | |
1329 | } | |
1330 | } | |
1331 | ||
1332 | // Now, precheck that user and, based on returned results, annotate action/problem | |
1333 | $usercheck = self::precheck_user($user, $samesite); | |
1334 | ||
1335 | if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to | |
1336 | // Annotate it, for later process. Set newitemid to mapping user->id | |
1337 | self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $usercheck->id); | |
1338 | ||
1339 | } else if ($usercheck === false) { // Found conflict, report it as problem | |
1340 | $problems[] = get_string('restoreuserconflict', '', $user->username); | |
1341 | ||
1342 | } else if ($usercheck === true) { // User needs to be created, check if we are able | |
1343 | if ($cancreateuser) { // Can create user, set newitemid to 0 so will be created later | |
1344 | self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, 0, null, (array)$user); | |
1345 | ||
1346 | } else { // Cannot create user, report it as problem | |
1347 | $problems[] = get_string('restorecannotcreateuser', '', $user->username); | |
1348 | } | |
1349 | ||
1350 | } else { // Shouldn't arrive here ever, something is for sure wrong. Exception | |
1351 | throw new restore_dbops_exception('restore_error_processing_user', $user->username); | |
1352 | } | |
1353 | } | |
1354 | $rs->close(); | |
1355 | return $problems; | |
1356 | } | |
1357 | ||
1358 | /** | |
41941110 EL |
1359 | * Process the needed users in order to decide |
1360 | * which action to perform with them (create/map) | |
482aac65 EL |
1361 | * |
1362 | * Just wrap over precheck_included_users(), returning | |
41941110 | 1363 | * exception if any problem is found |
482aac65 EL |
1364 | */ |
1365 | public static function process_included_users($restoreid, $courseid, $userid, $samesite) { | |
1366 | global $DB; | |
1367 | ||
1368 | // Just let precheck_included_users() to do all the hard work | |
1369 | $problems = self::precheck_included_users($restoreid, $courseid, $userid, $samesite); | |
1370 | ||
1371 | // With problems, throw exception, shouldn't happen if prechecks were originally | |
1372 | // executed, so be radical here. | |
1373 | if (!empty($problems)) { | |
1374 | throw new restore_dbops_exception('restore_problems_processing_users', null, implode(', ', $problems)); | |
1375 | } | |
482aac65 EL |
1376 | } |
1377 | ||
41941110 EL |
1378 | /** |
1379 | * Process the needed question categories and questions | |
1380 | * to check all them, deciding about the action to perform | |
1381 | * (create/map) and target. | |
1382 | * | |
1383 | * Just wrap over precheck_categories_and_questions(), returning | |
1384 | * exception if any problem is found | |
1385 | */ | |
1386 | public static function process_categories_and_questions($restoreid, $courseid, $userid, $samesite) { | |
1387 | global $DB; | |
1388 | ||
1389 | // Just let precheck_included_users() to do all the hard work | |
1390 | $problems = self::precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite); | |
1391 | ||
1392 | // With problems of type error, throw exception, shouldn't happen if prechecks were originally | |
1393 | // executed, so be radical here. | |
1394 | if (array_key_exists('errors', $problems)) { | |
ede7105f | 1395 | throw new restore_dbops_exception('restore_problems_processing_questions', null, implode(', ', $problems['errors'])); |
41941110 EL |
1396 | } |
1397 | } | |
1398 | ||
b8bb45b0 EL |
1399 | public static function set_backup_files_record($restoreid, $filerec) { |
1400 | global $DB; | |
1401 | ||
67233725 | 1402 | // Store external files info in `info` field |
b8bb45b0 EL |
1403 | $filerec->info = base64_encode(serialize($filerec)); // Serialize the whole rec in info |
1404 | $filerec->backupid = $restoreid; | |
1405 | $DB->insert_record('backup_files_temp', $filerec); | |
1406 | } | |
1407 | ||
482aac65 | 1408 | public static function set_backup_ids_record($restoreid, $itemname, $itemid, $newitemid = 0, $parentitemid = null, $info = null) { |
482aac65 EL |
1409 | // Build conditionally the extra record info |
1410 | $extrarecord = array(); | |
1411 | if ($newitemid != 0) { | |
1412 | $extrarecord['newitemid'] = $newitemid; | |
1413 | } | |
1414 | if ($parentitemid != null) { | |
1415 | $extrarecord['parentitemid'] = $parentitemid; | |
1416 | } | |
1417 | if ($info != null) { | |
1418 | $extrarecord['info'] = base64_encode(serialize($info)); | |
1419 | } | |
1420 | ||
7f98b12f | 1421 | self::set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord); |
482aac65 EL |
1422 | } |
1423 | ||
1424 | public static function get_backup_ids_record($restoreid, $itemname, $itemid) { | |
7f98b12f | 1425 | $dbrec = self::get_backup_ids_cached($restoreid, $itemname, $itemid); |
482aac65 | 1426 | |
7f98b12f TL |
1427 | if ($dbrec && isset($dbrec->info) && is_string($dbrec->info)) { |
1428 | $dbrec->info = unserialize(base64_decode($dbrec->info)); | |
482aac65 | 1429 | } |
7f98b12f | 1430 | |
482aac65 EL |
1431 | return $dbrec; |
1432 | } | |
4bca307a EL |
1433 | |
1434 | /** | |
1435 | * Given on courseid, fullname and shortname, calculate the correct fullname/shortname to avoid dupes | |
1436 | */ | |
1437 | public static function calculate_course_names($courseid, $fullname, $shortname) { | |
1438 | global $CFG, $DB; | |
1439 | ||
1440 | $currentfullname = ''; | |
1441 | $currentshortname = ''; | |
1442 | $counter = 0; | |
1443 | // Iteratere while the name exists | |
1444 | do { | |
1445 | if ($counter) { | |
1446 | $suffixfull = ' ' . get_string('copyasnoun') . ' ' . $counter; | |
1447 | $suffixshort = '_' . $counter; | |
1448 | } else { | |
1449 | $suffixfull = ''; | |
1450 | $suffixshort = ''; | |
1451 | } | |
1452 | $currentfullname = $fullname.$suffixfull; | |
1453 | $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; // < 100cc | |
1454 | $coursefull = $DB->get_record_select('course', 'fullname = ? AND id != ?', array($currentfullname, $courseid)); | |
1455 | $courseshort = $DB->get_record_select('course', 'shortname = ? AND id != ?', array($currentshortname, $courseid)); | |
1456 | $counter++; | |
1457 | } while ($coursefull || $courseshort); | |
1458 | ||
1459 | // Return results | |
1460 | return array($currentfullname, $currentshortname); | |
1461 | } | |
1462 | ||
1463 | /** | |
1464 | * For the target course context, put as many custom role names as possible | |
1465 | */ | |
1466 | public static function set_course_role_names($restoreid, $courseid) { | |
1467 | global $DB; | |
1468 | ||
1469 | // Get the course context | |
1470 | $coursectx = get_context_instance(CONTEXT_COURSE, $courseid); | |
1471 | // Get all the mapped roles we have | |
1472 | $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid'); | |
1473 | foreach ($rs as $recrole) { | |
1474 | // Get the complete temp_ids record | |
1475 | $role = (object)self::get_backup_ids_record($restoreid, 'role', $recrole->itemid); | |
024c288d EL |
1476 | // If it's one mapped role and we have one name for it |
1477 | if (!empty($role->newitemid) && !empty($role->info['nameincourse'])) { | |
4bca307a EL |
1478 | // If role name doesn't exist, add it |
1479 | $rolename = new stdclass(); | |
1480 | $rolename->roleid = $role->newitemid; | |
1481 | $rolename->contextid = $coursectx->id; | |
1482 | if (!$DB->record_exists('role_names', (array)$rolename)) { | |
1483 | $rolename->name = $role->info['nameincourse']; | |
1484 | $DB->insert_record('role_names', $rolename); | |
1485 | } | |
1486 | } | |
1487 | } | |
1488 | $rs->close(); | |
1489 | } | |
785d6603 | 1490 | |
3acc9b81 SH |
1491 | /** |
1492 | * Creates a skeleton record within the database using the passed parameters | |
1493 | * and returns the new course id. | |
1494 | * | |
1495 | * @global moodle_database $DB | |
1496 | * @param string $fullname | |
1497 | * @param string $shortname | |
1498 | * @param int $categoryid | |
1499 | * @return int The new course id | |
1500 | */ | |
785d6603 SH |
1501 | public static function create_new_course($fullname, $shortname, $categoryid) { |
1502 | global $DB; | |
1503 | $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST); | |
1504 | ||
1505 | $course = new stdClass; | |
1506 | $course->fullname = $fullname; | |
1507 | $course->shortname = $shortname; | |
1508 | $course->category = $category->id; | |
1509 | $course->sortorder = 0; | |
1510 | $course->timecreated = time(); | |
1511 | $course->timemodified = $course->timecreated; | |
ed6a14eb AB |
1512 | // forcing skeleton courses to be hidden instead of going by $category->visible , until MDL-27790 is resolved. |
1513 | $course->visible = 0; | |
785d6603 | 1514 | |
593fc4a9 SH |
1515 | $courseid = $DB->insert_record('course', $course); |
1516 | ||
1517 | $category->coursecount++; | |
1518 | $DB->update_record('course_categories', $category); | |
1519 | ||
1520 | return $courseid; | |
785d6603 SH |
1521 | } |
1522 | ||
3acc9b81 SH |
1523 | /** |
1524 | * Deletes all of the content associated with the given course (courseid) | |
1525 | * @param int $courseid | |
d53e3298 | 1526 | * @param array $options |
3acc9b81 SH |
1527 | * @return bool True for success |
1528 | */ | |
d53e3298 PS |
1529 | public static function delete_course_content($courseid, array $options = null) { |
1530 | return remove_course_contents($courseid, false, $options); | |
785d6603 | 1531 | } |
482aac65 | 1532 | } |
fbc2778d EL |
1533 | |
1534 | /* | |
1535 | * Exception class used by all the @dbops stuff | |
1536 | */ | |
1537 | class restore_dbops_exception extends backup_exception { | |
1538 | ||
1539 | public function __construct($errorcode, $a=NULL, $debuginfo=null) { | |
1540 | parent::__construct($errorcode, 'error', '', $a, null, $debuginfo); | |
1541 | } | |
1542 | } |