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