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 {
0c99b722
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
0c99b722
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));
2df0f295
EL
749 // ignore root dirs (they are created automatically)
750 if ($file->filepath == '/' && $file->filename == '.') {
751 continue;
752 }
84cdf7de
EL
753 // set the best possible user
754 $mappeduser = self::get_backup_ids_record($restoreid, 'user', $file->userid);
755 $file->userid = !empty($mappeduser) ? $mappeduser->newitemid : $dfltuserid;
2df0f295
EL
756 // dir found (and not root one), let's create if
757 if ($file->filename == '.') {
84cdf7de 758 $fs->create_directory($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->userid);
2df0f295
EL
759 continue;
760 }
761 // arrived here, file found
762 // Find file in backup pool
2b199e7c 763 $backuppath = $basepath . backup_file_manager::get_backup_content_file_location($file->contenthash);
2df0f295
EL
764 if (!file_exists($backuppath)) {
765 throw new restore_dbops_exception('file_not_found_in_pool', $file);
766 }
767 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
768 $file_record = array(
769 'contextid' => $newcontextid,
770 'component' => $component,
771 'filearea' => $filearea,
772 'itemid' => $rec->newitemid,
773 'filepath' => $file->filepath,
774 'filename' => $file->filename,
775 'timecreated' => $file->timecreated,
776 'timemodified'=> $file->timemodified,
84cdf7de 777 'userid' => $file->userid,
2df0f295 778 'author' => $file->author,
84cdf7de
EL
779 'license' => $file->license,
780 'sortorder' => $file->sortorder);
2df0f295
EL
781 $fs->create_file_from_pathname($file_record, $backuppath);
782 }
783 }
784 $rs->close();
785 }
786
482aac65
EL
787 /**
788 * Given one restoreid, create in DB all the users present
789 * in backup_ids having newitemid = 0, as far as
790 * precheck_included_users() have left them there
791 * ready to be created. Also, annotate their newids
792 * once created for later reference
793 */
ac6dc09c 794 public static function create_included_users($basepath, $restoreid, $userid) {
482aac65
EL
795 global $CFG, $DB;
796
797 $authcache = array(); // Cache to get some bits from authentication plugins
798 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search later
799 $themes = get_list_of_themes(); // Get themes for quick search later
800
801 // Iterate over all the included users with newitemid = 0, have to create them
802 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid');
803 foreach ($rs as $recuser) {
804 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
805
806 // if user lang doesn't exist here, use site default
807 if (!array_key_exists($user->lang, $languages)) {
808 $user->lang = $CFG->lang;
809 }
810
811 // if user theme isn't available on target site or they are disabled, reset theme
812 if (!empty($user->theme)) {
813 if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) {
814 $user->theme = '';
815 }
816 }
817
818 // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id
819 // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual
820 if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
821 // Respect registerauth
822 if ($CFG->registerauth == 'email') {
823 $user->auth = 'email';
824 } else {
825 $user->auth = 'manual';
826 }
827 }
828 unset($user->mnethosturl); // Not needed anymore
829
830 // Disable pictures based on global setting
831 if (!empty($CFG->disableuserimages)) {
832 $user->picture = 0;
833 }
834
835 // We need to analyse the AUTH field to recode it:
836 // - if the auth isn't enabled in target site, $CFG->registerauth will decide
837 // - finally, if the auth resulting isn't enabled, default to 'manual'
838 if (!is_enabled_auth($user->auth)) {
839 if ($CFG->registerauth == 'email') {
840 $user->auth = 'email';
841 } else {
842 $user->auth = 'manual';
843 }
844 }
845 if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled
846 $user->auth = 'manual';
847 }
848
849 // Now that we know the auth method, for users to be created without pass
850 // if password handling is internal and reset password is available
851 // we set the password to "restored" (plain text), so the login process
852 // will know how to handle that situation in order to allow the user to
853 // recover the password. MDL-20846
854 if (empty($user->password)) { // Only if restore comes without password
855 if (!array_key_exists($user->auth, $authcache)) { // Not in cache
856 $userauth = new stdClass();
857 $authplugin = get_auth_plugin($user->auth);
858 $userauth->preventpassindb = $authplugin->prevent_local_passwords();
859 $userauth->isinternal = $authplugin->is_internal();
860 $userauth->canresetpwd = $authplugin->can_reset_password();
861 $authcache[$user->auth] = $userauth;
862 } else {
863 $userauth = $authcache[$user->auth]; // Get from cache
864 }
865
866 // Most external plugins do not store passwords locally
867 if (!empty($userauth->preventpassindb)) {
868 $user->password = 'not cached';
869
870 // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
871 } else if ($userauth->isinternal and $userauth->canresetpwd) {
872 $user->password = 'restored';
873 }
874 }
875
876 // Creating new user, we must reset the policyagreed always
877 $user->policyagreed = 0;
878
879 // Set time created if empty
880 if (empty($user->timecreated)) {
881 $user->timecreated = time();
882 }
883
884 // Done, let's create the user and annotate its id
885 $newuserid = $DB->insert_record('user', $user);
886 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid);
887 // Let's create the user context and annotate it (we need it for sure at least for files)
1acad8ee
EL
888 // but for deleted users that don't have a context anymore (MDL-30192). We are done for them
889 // and nothing else (custom fields, prefs, tags, files...) will be created.
890 if (empty($user->deleted)) {
891 $newuserctxid = $user->deleted ? 0 : get_context_instance(CONTEXT_USER, $newuserid)->id;
892 self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid);
893
894 // Process custom fields
895 if (isset($user->custom_fields)) { // if present in backup
896 foreach($user->custom_fields['custom_field'] as $udata) {
897 $udata = (object)$udata;
898 // If the profile field has data and the profile shortname-datatype is defined in server
899 if ($udata->field_data) {
900 if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) {
901 /// Insert the user_custom_profile_field
902 $rec = new stdClass();
903 $rec->userid = $newuserid;
904 $rec->fieldid = $field->id;
905 $rec->data = $udata->field_data;
906 $DB->insert_record('user_info_data', $rec);
907 }
482aac65
EL
908 }
909 }
910 }
482aac65 911
1acad8ee
EL
912 // Process tags
913 if (!empty($CFG->usetags) && isset($user->tags)) { // if enabled in server and present in backup
914 $tags = array();
915 foreach($user->tags['tag'] as $usertag) {
916 $usertag = (object)$usertag;
917 $tags[] = $usertag->rawname;
918 }
919 tag_set('user', $newuserid, $tags);
482aac65 920 }
482aac65 921
1acad8ee
EL
922 // Process preferences
923 if (isset($user->preferences)) { // if present in backup
924 foreach($user->preferences['preference'] as $preference) {
925 $preference = (object)$preference;
926 // Prepare the record and insert it
927 $preference->userid = $newuserid;
928 $status = $DB->insert_record('user_preferences', $preference);
929 }
482aac65 930 }
482aac65 931
1acad8ee
EL
932 // Create user files in pool (profile, icon, private) by context
933 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon', $recuser->parentitemid, $userid);
934 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile', $recuser->parentitemid, $userid);
1acad8ee 935 }
482aac65
EL
936 }
937 $rs->close();
938 }
939
940 /**
941 * Given one user object (from backup file), perform all the neccesary
942 * checks is order to decide how that user will be handled on restore.
943 *
944 * Note the function requires $user->mnethostid to be already calculated
945 * so it's caller responsibility to set it
946 *
947 * This function is used both by @restore_precheck_users() and
948 * @restore_create_users() to get consistent results in both places
949 *
950 * It returns:
951 * - one user object (from DB), if match has been found and user will be remapped
952 * - boolean true if the user needs to be created
953 * - boolean false if some conflict happened and the user cannot be handled
954 *
955 * Each test is responsible for returning its results and interrupt
956 * execution. At the end, boolean true (user needs to be created) will be
957 * returned if no test has interrupted that.
958 *
959 * Here it's the logic applied, keep it updated:
960 *
961 * If restoring users from same site backup:
962 * 1A - Normal check: If match by id and username and mnethost => ok, return target user
963 * 1B - Handle users deleted in DB and "alive" in backup file:
964 * If match by id and mnethost and user is deleted in DB and
965 * (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user
966 * 1C - Handle users deleted in backup file and "alive" in DB:
967 * If match by id and mnethost and user is deleted in backup file
968 * and match by email = email_without_time(backup_email) => ok, return target user
969 * 1D - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false
970 * 1E - None of the above, return true => User needs to be created
971 *
972 * if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination):
973 * 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user
974 * 2B - Handle users deleted in DB and "alive" in backup file:
975 * 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
976 * (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
977 * 2B2 - If match by mnethost and user is deleted in DB and
978 * username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
979 * (to cover situations were md5(username) wasn't implemented on delete we requiere both)
980 * 2C - Handle users deleted in backup file and "alive" in DB:
981 * If match mnethost and user is deleted in backup file
982 * and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
983 * 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
984 * 2E - None of the above, return true => User needs to be created
985 *
986 * Note: for DB deleted users email is stored in username field, hence we
987 * are looking there for emails. See delete_user()
988 * Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
989 * hence we are looking there for usernames if not empty. See delete_user()
990 */
991 protected static function precheck_user($user, $samesite) {
992 global $CFG, $DB;
993
994 // Handle checks from same site backups
995 if ($samesite && empty($CFG->forcedifferentsitecheckingusersonrestore)) {
996
997 // 1A - If match by id and username and mnethost => ok, return target user
998 if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
999 return $rec; // Matching user found, return it
1000 }
1001
1002 // 1B - Handle users deleted in DB and "alive" in backup file
1003 // Note: for DB deleted users email is stored in username field, hence we
1004 // are looking there for emails. See delete_user()
1005 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1006 // hence we are looking there for usernames if not empty. See delete_user()
1007 // If match by id and mnethost and user is deleted in DB and
1008 // match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user
1009 if ($rec = $DB->get_record_sql("SELECT *
1010 FROM {user} u
1011 WHERE id = ?
1012 AND mnethostid = ?
1013 AND deleted = 1
1014 AND (
ef6b3ba1 1015 UPPER(username) LIKE UPPER(?)
482aac65
EL
1016 OR (
1017 ".$DB->sql_isnotempty('user', 'email', false, false)."
1018 AND email = ?
1019 )
1020 )",
1021 array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) {
1022 return $rec; // Matching user, deleted in DB found, return it
1023 }
1024
1025 // 1C - Handle users deleted in backup file and "alive" in DB
1026 // If match by id and mnethost and user is deleted in backup file
1027 // and match by email = email_without_time(backup_email) => ok, return target user
1028 if ($user->deleted) {
1029 // Note: for DB deleted users email is stored in username field, hence we
1030 // are looking there for emails. See delete_user()
1031 // Trim time() from email
1032 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
1033 if ($rec = $DB->get_record_sql("SELECT *
1034 FROM {user} u
1035 WHERE id = ?
1036 AND mnethostid = ?
ef6b3ba1 1037 AND UPPER(email) = UPPER(?)",
482aac65
EL
1038 array($user->id, $user->mnethostid, $trimemail))) {
1039 return $rec; // Matching user, deleted in backup file found, return it
1040 }
1041 }
1042
1043 // 1D - If match by username and mnethost and doesn't match by id => conflict, return false
1044 if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
1045 if ($user->id != $rec->id) {
1046 return false; // Conflict, username already exists and belongs to another id
1047 }
1048 }
1049
1050 // Handle checks from different site backups
1051 } else {
1052
1053 // 2A - If match by username and mnethost and
1054 // (email or non-zero firstaccess) => ok, return target user
1055 if ($rec = $DB->get_record_sql("SELECT *
1056 FROM {user} u
1057 WHERE username = ?
1058 AND mnethostid = ?
1059 AND (
ef6b3ba1 1060 UPPER(email) = UPPER(?)
482aac65
EL
1061 OR (
1062 firstaccess != 0
1063 AND firstaccess = ?
1064 )
1065 )",
1066 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
1067 return $rec; // Matching user found, return it
1068 }
1069
1070 // 2B - Handle users deleted in DB and "alive" in backup file
1071 // Note: for DB deleted users email is stored in username field, hence we
1072 // are looking there for emails. See delete_user()
1073 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1074 // hence we are looking there for usernames if not empty. See delete_user()
1075 // 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
1076 // (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
1077 if ($rec = $DB->get_record_sql("SELECT *
1078 FROM {user} u
1079 WHERE mnethostid = ?
1080 AND deleted = 1
1081 AND ".$DB->sql_isnotempty('user', 'email', false, false)."
1082 AND email = ?
1083 AND (
ef6b3ba1 1084 UPPER(username) LIKE UPPER(?)
482aac65
EL
1085 OR (
1086 firstaccess != 0
1087 AND firstaccess = ?
1088 )
1089 )",
1090 array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) {
1091 return $rec; // Matching user found, return it
1092 }
1093
1094 // 2B2 - If match by mnethost and user is deleted in DB and
1095 // username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
1096 // (this covers situations where md5(username) wasn't being stored so we require both
1097 // the email & non-zero firstaccess to match)
1098 if ($rec = $DB->get_record_sql("SELECT *
1099 FROM {user} u
1100 WHERE mnethostid = ?
1101 AND deleted = 1
ef6b3ba1 1102 AND UPPER(username) LIKE UPPER(?)
482aac65
EL
1103 AND firstaccess != 0
1104 AND firstaccess = ?",
1105 array($user->mnethostid, $user->email.'.%', $user->firstaccess))) {
1106 return $rec; // Matching user found, return it
1107 }
1108
1109 // 2C - Handle users deleted in backup file and "alive" in DB
1110 // If match mnethost and user is deleted in backup file
1111 // and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
1112 if ($user->deleted) {
1113 // Note: for DB deleted users email is stored in username field, hence we
1114 // are looking there for emails. See delete_user()
1115 // Trim time() from email
1116 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
1117 if ($rec = $DB->get_record_sql("SELECT *
1118 FROM {user} u
1119 WHERE mnethostid = ?
ef6b3ba1 1120 AND UPPER(email) = UPPER(?)
482aac65
EL
1121 AND firstaccess != 0
1122 AND firstaccess = ?",
1123 array($user->mnethostid, $trimemail, $user->firstaccess))) {
1124 return $rec; // Matching user, deleted in backup file found, return it
1125 }
1126 }
1127
1128 // 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
1129 if ($rec = $DB->get_record_sql("SELECT *
1130 FROM {user} u
1131 WHERE username = ?
1132 AND mnethostid = ?
1133 AND NOT (
ef6b3ba1 1134 UPPER(email) = UPPER(?)
482aac65
EL
1135 OR (
1136 firstaccess != 0
1137 AND firstaccess = ?
1138 )
1139 )",
1140 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
1141 return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess)
1142 }
1143 }
1144
1145 // Arrived here, return true as the user will need to be created and no
1146 // conflicts have been found in the logic above. This covers:
1147 // 1E - else => user needs to be created, return true
1148 // 2E - else => user needs to be created, return true
1149 return true;
1150 }
1151
1152 /**
1153 * Check all the included users, deciding the action to perform
1154 * for each one (mapping / creation) and returning one array
1155 * of problems in case something is wrong (lack of permissions,
1156 * conficts)
1157 */
1158 public static function precheck_included_users($restoreid, $courseid, $userid, $samesite) {
1159 global $CFG, $DB;
1160
1161 // To return any problem found
1162 $problems = array();
1163
1164 // We are going to map mnethostid, so load all the available ones
1165 $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id');
1166
1167 // Calculate the context we are going to use for capability checking
1168 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1169
1170 // Calculate if we have perms to create users, by checking:
1171 // to 'moodle/restore:createuser' and 'moodle/restore:userinfo'
1172 // and also observe $CFG->disableusercreationonrestore
1173 $cancreateuser = false;
1174 if (has_capability('moodle/restore:createuser', $context, $userid) and
1175 has_capability('moodle/restore:userinfo', $context, $userid) and
1176 empty($CFG->disableusercreationonrestore)) { // Can create users
1177
1178 $cancreateuser = true;
1179 }
1180
1181 // Iterate over all the included users
1182 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user'), '', 'itemid');
1183 foreach ($rs as $recuser) {
1184 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
1185
1186 // Find the correct mnethostid for user before performing any further check
1187 if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
1188 $user->mnethostid = $CFG->mnet_localhost_id;
1189 } else {
1190 // fast url-to-id lookups
1191 if (isset($mnethosts[$user->mnethosturl])) {
1192 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
1193 } else {
1194 $user->mnethostid = $CFG->mnet_localhost_id;
1195 }
1196 }
1197
1198 // Now, precheck that user and, based on returned results, annotate action/problem
1199 $usercheck = self::precheck_user($user, $samesite);
1200
1201 if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to
1202 // Annotate it, for later process. Set newitemid to mapping user->id
1203 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $usercheck->id);
1204
1205 } else if ($usercheck === false) { // Found conflict, report it as problem
1206 $problems[] = get_string('restoreuserconflict', '', $user->username);
1207
1208 } else if ($usercheck === true) { // User needs to be created, check if we are able
1209 if ($cancreateuser) { // Can create user, set newitemid to 0 so will be created later
1210 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, 0, null, (array)$user);
1211
1212 } else { // Cannot create user, report it as problem
1213 $problems[] = get_string('restorecannotcreateuser', '', $user->username);
1214 }
1215
1216 } else { // Shouldn't arrive here ever, something is for sure wrong. Exception
1217 throw new restore_dbops_exception('restore_error_processing_user', $user->username);
1218 }
1219 }
1220 $rs->close();
1221 return $problems;
1222 }
1223
1224 /**
41941110
EL
1225 * Process the needed users in order to decide
1226 * which action to perform with them (create/map)
482aac65
EL
1227 *
1228 * Just wrap over precheck_included_users(), returning
41941110 1229 * exception if any problem is found
482aac65
EL
1230 */
1231 public static function process_included_users($restoreid, $courseid, $userid, $samesite) {
1232 global $DB;
1233
1234 // Just let precheck_included_users() to do all the hard work
1235 $problems = self::precheck_included_users($restoreid, $courseid, $userid, $samesite);
1236
1237 // With problems, throw exception, shouldn't happen if prechecks were originally
1238 // executed, so be radical here.
1239 if (!empty($problems)) {
1240 throw new restore_dbops_exception('restore_problems_processing_users', null, implode(', ', $problems));
1241 }
482aac65
EL
1242 }
1243
41941110
EL
1244 /**
1245 * Process the needed question categories and questions
1246 * to check all them, deciding about the action to perform
1247 * (create/map) and target.
1248 *
1249 * Just wrap over precheck_categories_and_questions(), returning
1250 * exception if any problem is found
1251 */
1252 public static function process_categories_and_questions($restoreid, $courseid, $userid, $samesite) {
1253 global $DB;
1254
1255 // Just let precheck_included_users() to do all the hard work
1256 $problems = self::precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite);
1257
1258 // With problems of type error, throw exception, shouldn't happen if prechecks were originally
1259 // executed, so be radical here.
1260 if (array_key_exists('errors', $problems)) {
ede7105f 1261 throw new restore_dbops_exception('restore_problems_processing_questions', null, implode(', ', $problems['errors']));
41941110
EL
1262 }
1263 }
1264
b8bb45b0
EL
1265 public static function set_backup_files_record($restoreid, $filerec) {
1266 global $DB;
1267
1268 $filerec->info = base64_encode(serialize($filerec)); // Serialize the whole rec in info
1269 $filerec->backupid = $restoreid;
1270 $DB->insert_record('backup_files_temp', $filerec);
1271 }
1272
482aac65 1273 public static function set_backup_ids_record($restoreid, $itemname, $itemid, $newitemid = 0, $parentitemid = null, $info = null) {
482aac65
EL
1274 // Build conditionally the extra record info
1275 $extrarecord = array();
1276 if ($newitemid != 0) {
1277 $extrarecord['newitemid'] = $newitemid;
1278 }
1279 if ($parentitemid != null) {
1280 $extrarecord['parentitemid'] = $parentitemid;
1281 }
1282 if ($info != null) {
1283 $extrarecord['info'] = base64_encode(serialize($info));
1284 }
1285
0c99b722 1286 self::set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord);
482aac65
EL
1287 }
1288
1289 public static function get_backup_ids_record($restoreid, $itemname, $itemid) {
0c99b722 1290 $dbrec = self::get_backup_ids_cached($restoreid, $itemname, $itemid);
482aac65 1291
0c99b722
TL
1292 if ($dbrec && isset($dbrec->info) && is_string($dbrec->info)) {
1293 $dbrec->info = unserialize(base64_decode($dbrec->info));
482aac65 1294 }
0c99b722 1295
482aac65
EL
1296 return $dbrec;
1297 }
4bca307a
EL
1298
1299 /**
1300 * Given on courseid, fullname and shortname, calculate the correct fullname/shortname to avoid dupes
1301 */
1302 public static function calculate_course_names($courseid, $fullname, $shortname) {
1303 global $CFG, $DB;
1304
1305 $currentfullname = '';
1306 $currentshortname = '';
1307 $counter = 0;
1308 // Iteratere while the name exists
1309 do {
1310 if ($counter) {
1311 $suffixfull = ' ' . get_string('copyasnoun') . ' ' . $counter;
1312 $suffixshort = '_' . $counter;
1313 } else {
1314 $suffixfull = '';
1315 $suffixshort = '';
1316 }
1317 $currentfullname = $fullname.$suffixfull;
1318 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; // < 100cc
1319 $coursefull = $DB->get_record_select('course', 'fullname = ? AND id != ?', array($currentfullname, $courseid));
1320 $courseshort = $DB->get_record_select('course', 'shortname = ? AND id != ?', array($currentshortname, $courseid));
1321 $counter++;
1322 } while ($coursefull || $courseshort);
1323
1324 // Return results
1325 return array($currentfullname, $currentshortname);
1326 }
1327
1328 /**
1329 * For the target course context, put as many custom role names as possible
1330 */
1331 public static function set_course_role_names($restoreid, $courseid) {
1332 global $DB;
1333
1334 // Get the course context
1335 $coursectx = get_context_instance(CONTEXT_COURSE, $courseid);
1336 // Get all the mapped roles we have
1337 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid');
1338 foreach ($rs as $recrole) {
1339 // Get the complete temp_ids record
1340 $role = (object)self::get_backup_ids_record($restoreid, 'role', $recrole->itemid);
024c288d
EL
1341 // If it's one mapped role and we have one name for it
1342 if (!empty($role->newitemid) && !empty($role->info['nameincourse'])) {
4bca307a
EL
1343 // If role name doesn't exist, add it
1344 $rolename = new stdclass();
1345 $rolename->roleid = $role->newitemid;
1346 $rolename->contextid = $coursectx->id;
1347 if (!$DB->record_exists('role_names', (array)$rolename)) {
1348 $rolename->name = $role->info['nameincourse'];
1349 $DB->insert_record('role_names', $rolename);
1350 }
1351 }
1352 }
1353 $rs->close();
1354 }
785d6603 1355
3acc9b81
SH
1356 /**
1357 * Creates a skeleton record within the database using the passed parameters
1358 * and returns the new course id.
1359 *
1360 * @global moodle_database $DB
1361 * @param string $fullname
1362 * @param string $shortname
1363 * @param int $categoryid
1364 * @return int The new course id
1365 */
785d6603
SH
1366 public static function create_new_course($fullname, $shortname, $categoryid) {
1367 global $DB;
1368 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1369
1370 $course = new stdClass;
1371 $course->fullname = $fullname;
1372 $course->shortname = $shortname;
1373 $course->category = $category->id;
1374 $course->sortorder = 0;
1375 $course->timecreated = time();
1376 $course->timemodified = $course->timecreated;
ed6a14eb
AB
1377 // forcing skeleton courses to be hidden instead of going by $category->visible , until MDL-27790 is resolved.
1378 $course->visible = 0;
785d6603 1379
593fc4a9
SH
1380 $courseid = $DB->insert_record('course', $course);
1381
1382 $category->coursecount++;
1383 $DB->update_record('course_categories', $category);
1384
1385 return $courseid;
785d6603
SH
1386 }
1387
3acc9b81
SH
1388 /**
1389 * Deletes all of the content associated with the given course (courseid)
1390 * @param int $courseid
d53e3298 1391 * @param array $options
3acc9b81
SH
1392 * @return bool True for success
1393 */
d53e3298
PS
1394 public static function delete_course_content($courseid, array $options = null) {
1395 return remove_course_contents($courseid, false, $options);
785d6603 1396 }
482aac65 1397}
fbc2778d
EL
1398
1399/*
1400 * Exception class used by all the @dbops stuff
1401 */
1402class restore_dbops_exception extends backup_exception {
1403
1404 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
1405 parent::__construct($errorcode, 'error', '', $a, null, $debuginfo);
1406 }
1407}