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