3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
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
26 * Base abstract class for all the helper classes providing DB operations
28 * TODO: Finish phpdocs
30 abstract class restore_dbops {
32 * Keep cache of backup records.
34 * @todo MDL-25290 static should be replaced with MUC code.
36 private static $backupidscache = array();
38 * Keep track of backup ids which are cached.
40 * @todo MDL-25290 static should be replaced with MUC code.
42 private static $backupidsexist = array();
44 * Count is expensive, so manually keeping track of
45 * backupidscache, to avoid memory issues.
47 * @todo MDL-25290 static should be replaced with MUC code.
49 private static $backupidscachesize = 2048;
51 * Count is expensive, so manually keeping track of
52 * backupidsexist, to avoid memory issues.
54 * @todo MDL-25290 static should be replaced with MUC code.
56 private static $backupidsexistsize = 10240;
58 * Slice backupids cache to add more data.
60 * @todo MDL-25290 static should be replaced with MUC code.
62 private static $backupidsslice = 512;
65 * Return one array containing all the tasks that have been included
66 * in the restore process. Note that these tasks aren't built (they
67 * haven't steps nor ids data available)
69 public static function get_included_tasks($restoreid) {
70 $rc = restore_controller_dbops::load_controller($restoreid);
71 $tasks = $rc->get_plan()->get_tasks();
72 $includedtasks = array();
73 foreach ($tasks as $key => $task) {
74 // Calculate if the task is being included
76 // blocks, based in blocks setting and parent activity/course
77 if ($task instanceof restore_block_task) {
78 if (!$task->get_setting_value('blocks')) { // Blocks not included, continue
81 $parent = basename(dirname(dirname($task->get_taskbasepath())));
82 if ($parent == 'course') { // Parent is course, always included if present
85 } else { // Look for activity_included setting
86 $included = $task->get_setting_value($parent . '_included');
89 // ativities, based on included setting
90 } else if ($task instanceof restore_activity_task) {
91 $included = $task->get_setting_value('included');
93 // sections, based on included setting
94 } else if ($task instanceof restore_section_task) {
95 $included = $task->get_setting_value('included');
97 // course always included if present
98 } else if ($task instanceof restore_course_task) {
102 // If included, add it
104 $includedtasks[] = $task;
107 return $includedtasks;
111 * Load one inforef.xml file to backup_ids table for future reference
113 * @param string $restoreid Restore id
114 * @param string $inforeffile File path
115 * @param core_backup_progress $progress Progress tracker
117 public static function load_inforef_to_tempids($restoreid, $inforeffile,
118 core_backup_progress $progress = null) {
120 if (!file_exists($inforeffile)) { // Shouldn't happen ever, but...
121 throw new backup_helper_exception('missing_inforef_xml_file', $inforeffile);
124 // Set up progress tracking (indeterminate).
126 $progress = new core_backup_null_progress();
128 $progress->start_progress('Loading inforef.xml file');
130 // Let's parse, custom processor will do its work, sending info to DB
131 $xmlparser = new progressive_parser();
132 $xmlparser->set_file($inforeffile);
133 $xmlprocessor = new restore_inforef_parser_processor($restoreid);
134 $xmlparser->set_processor($xmlprocessor);
135 $xmlparser->set_progress($progress);
136 $xmlparser->process();
139 $progress->end_progress();
143 * Load the needed role.xml file to backup_ids table for future reference
145 public static function load_roles_to_tempids($restoreid, $rolesfile) {
147 if (!file_exists($rolesfile)) { // Shouldn't happen ever, but...
148 throw new backup_helper_exception('missing_roles_xml_file', $rolesfile);
150 // Let's parse, custom processor will do its work, sending info to DB
151 $xmlparser = new progressive_parser();
152 $xmlparser->set_file($rolesfile);
153 $xmlprocessor = new restore_roles_parser_processor($restoreid);
154 $xmlparser->set_processor($xmlprocessor);
155 $xmlparser->process();
159 * Precheck the loaded roles, return empty array if everything is ok, and
160 * array with 'errors', 'warnings' elements (suitable to be used by restore_prechecks)
161 * with any problem found. At the same time, store all the mapping into backup_ids_temp
162 * and also put the information into $rolemappings (controller->info), so it can be reworked later by
163 * post-precheck stages while at the same time accept modified info in the same object coming from UI
165 public static function precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings) {
168 $problems = array(); // To store warnings/errors
170 // Get loaded roles from backup_ids
171 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid, info');
172 foreach ($rs as $recrole) {
173 // If the rolemappings->modified flag is set, that means that we are coming from
174 // manually modified mappings (by UI), so accept those mappings an put them to backup_ids
175 if ($rolemappings->modified) {
176 $target = $rolemappings->mappings[$recrole->itemid]->targetroleid;
177 self::set_backup_ids_record($restoreid, 'role', $recrole->itemid, $target);
179 // Else, we haven't any info coming from UI, let's calculate the mappings, matching
180 // in multiple ways and checking permissions. Note mapping to 0 means "skip"
182 $role = (object)backup_controller_dbops::decode_backup_temp_info($recrole->info);
183 $match = self::get_best_assignable_role($role, $courseid, $userid, $samesite);
184 // Send match to backup_ids
185 self::set_backup_ids_record($restoreid, 'role', $recrole->itemid, $match);
186 // Build the rolemappings element for controller
188 unset($role->nameincourse);
189 $role->targetroleid = $match;
190 $rolemappings->mappings[$recrole->itemid] = $role;
191 // Prepare warning if no match found
193 $problems['warnings'][] = get_string('cannotfindassignablerole', 'backup', $role->name);
202 * Return cached backup id's
204 * @param int $restoreid id of backup
205 * @param string $itemname name of the item
206 * @param int $itemid id of item
207 * @return array backup id's
208 * @todo MDL-25290 replace static backupids* with MUC code
210 protected static function get_backup_ids_cached($restoreid, $itemname, $itemid) {
213 $key = "$itemid $itemname $restoreid";
215 // If record exists in cache then return.
216 if (isset(self::$backupidsexist[$key]) && isset(self::$backupidscache[$key])) {
217 // Return a copy of cached data, to avoid any alterations in cached data.
218 return clone self::$backupidscache[$key];
221 // Clean cache, if it's full.
222 if (self::$backupidscachesize <= 0) {
223 // Remove some records, to keep memory in limit.
224 self::$backupidscache = array_slice(self::$backupidscache, self::$backupidsslice, null, true);
225 self::$backupidscachesize = self::$backupidscachesize + self::$backupidsslice;
227 if (self::$backupidsexistsize <= 0) {
228 self::$backupidsexist = array_slice(self::$backupidsexist, self::$backupidsslice, null, true);
229 self::$backupidsexistsize = self::$backupidsexistsize + self::$backupidsslice;
232 // Retrive record from database.
234 'backupid' => $restoreid,
235 'itemname' => $itemname,
238 if ($dbrec = $DB->get_record('backup_ids_temp', $record)) {
239 self::$backupidsexist[$key] = $dbrec->id;
240 self::$backupidscache[$key] = $dbrec;
241 self::$backupidscachesize--;
242 self::$backupidsexistsize--;
252 * @param int $restoreid id of backup
253 * @param string $itemname name of the item
254 * @param int $itemid id of item
255 * @param array $extrarecord extra record which needs to be updated
257 * @todo MDL-25290 replace static BACKUP_IDS_* with MUC code
259 protected static function set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord) {
262 $key = "$itemid $itemname $restoreid";
265 'backupid' => $restoreid,
266 'itemname' => $itemname,
270 // If record is not cached then add one.
271 if (!isset(self::$backupidsexist[$key])) {
272 // If we have this record in db, then just update this.
273 if ($existingrecord = $DB->get_record('backup_ids_temp', $record)) {
274 self::$backupidsexist[$key] = $existingrecord->id;
275 self::$backupidsexistsize--;
276 self::update_backup_cached_record($record, $extrarecord, $key, $existingrecord);
278 // Add new record to cache and db.
279 $recorddefault = array (
281 'parentitemid' => null,
283 $record = array_merge($record, $recorddefault, $extrarecord);
284 $record['id'] = $DB->insert_record('backup_ids_temp', $record);
285 self::$backupidsexist[$key] = $record['id'];
286 self::$backupidsexistsize--;
287 if (self::$backupidscachesize > 0) {
288 // Cache new records if we haven't got many yet.
289 self::$backupidscache[$key] = (object) $record;
290 self::$backupidscachesize--;
294 self::update_backup_cached_record($record, $extrarecord, $key);
299 * Updates existing backup record
301 * @param array $record record which needs to be updated
302 * @param array $extrarecord extra record which needs to be updated
303 * @param string $key unique key which is used to identify cached record
304 * @param stdClass $existingrecord (optional) existing record
306 protected static function update_backup_cached_record($record, $extrarecord, $key, $existingrecord = null) {
308 // Update only if extrarecord is not empty.
309 if (!empty($extrarecord)) {
310 $extrarecord['id'] = self::$backupidsexist[$key];
311 $DB->update_record('backup_ids_temp', $extrarecord);
312 // Update existing cache or add new record to cache.
313 if (isset(self::$backupidscache[$key])) {
314 $record = array_merge((array)self::$backupidscache[$key], $extrarecord);
315 self::$backupidscache[$key] = (object) $record;
316 } else if (self::$backupidscachesize > 0) {
317 if ($existingrecord) {
318 self::$backupidscache[$key] = $existingrecord;
320 // Retrive record from database and cache updated records.
321 self::$backupidscache[$key] = $DB->get_record('backup_ids_temp', $record);
323 $record = array_merge((array)self::$backupidscache[$key], $extrarecord);
324 self::$backupidscache[$key] = (object) $record;
325 self::$backupidscachesize--;
331 * Reset the ids caches completely
333 * Any destructive operation (partial delete, truncate, drop or recreate) performed
334 * with the backup_ids table must cause the backup_ids caches to be
335 * invalidated by calling this method. See MDL-33630.
337 * Note that right now, the only operation of that type is the recreation
338 * (drop & restore) of the table that may happen once the prechecks have ended. All
339 * the rest of operations are always routed via {@link set_backup_ids_record()}, 1 by 1,
340 * keeping the caches on sync.
342 * @todo MDL-25290 static should be replaced with MUC code.
344 public static function reset_backup_ids_cached() {
345 // Reset the ids cache.
346 $cachetoadd = count(self::$backupidscache);
347 self::$backupidscache = array();
348 self::$backupidscachesize = self::$backupidscachesize + $cachetoadd;
349 // Reset the exists cache.
350 $existstoadd = count(self::$backupidsexist);
351 self::$backupidsexist = array();
352 self::$backupidsexistsize = self::$backupidsexistsize + $existstoadd;
356 * Given one role, as loaded from XML, perform the best possible matching against the assignable
357 * roles, using different fallback alternatives (shortname, archetype, editingteacher => teacher, defaultcourseroleid)
358 * returning the id of the best matching role or 0 if no match is found
360 protected static function get_best_assignable_role($role, $courseid, $userid, $samesite) {
363 // Gather various information about roles
364 $coursectx = context_course::instance($courseid);
365 $assignablerolesshortname = get_assignable_roles($coursectx, ROLENAME_SHORT, false, $userid);
367 // Note: under 1.9 we had one function restore_samerole() that performed one complete
368 // matching of roles (all caps) and if match was found the mapping was availabe bypassing
369 // any assignable_roles() security. IMO that was wrong and we must not allow such
370 // mappings anymore. So we have left that matching strategy out in 2.0
372 // Empty assignable roles, mean no match possible
373 if (empty($assignablerolesshortname)) {
377 // Match by shortname
378 if ($match = array_search($role->shortname, $assignablerolesshortname)) {
382 // Match by archetype
383 list($in_sql, $in_params) = $DB->get_in_or_equal(array_keys($assignablerolesshortname));
384 $params = array_merge(array($role->archetype), $in_params);
385 if ($rec = $DB->get_record_select('role', "archetype = ? AND id $in_sql", $params, 'id', IGNORE_MULTIPLE)) {
389 // Match editingteacher to teacher (happens a lot, from 1.9)
390 if ($role->shortname == 'editingteacher' && in_array('teacher', $assignablerolesshortname)) {
391 return array_search('teacher', $assignablerolesshortname);
394 // No match, return 0
400 * Process the loaded roles, looking for their best mapping or skipping
401 * Any error will cause exception. Note this is one wrapper over
402 * precheck_included_roles, that contains all the logic, but returns
403 * errors/warnings instead and is executed as part of the restore prechecks
405 public static function process_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings) {
408 // Just let precheck_included_roles() to do all the hard work
409 $problems = self::precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings);
411 // With problems of type error, throw exception, shouldn't happen if prechecks executed
412 if (array_key_exists('errors', $problems)) {
413 throw new restore_dbops_exception('restore_problems_processing_roles', null, implode(', ', $problems['errors']));
418 * Load the needed users.xml file to backup_ids table for future reference
420 * @param string $restoreid Restore id
421 * @param string $usersfile File path
422 * @param core_backup_progress $progress Progress tracker
424 public static function load_users_to_tempids($restoreid, $usersfile,
425 core_backup_progress $progress = null) {
427 if (!file_exists($usersfile)) { // Shouldn't happen ever, but...
428 throw new backup_helper_exception('missing_users_xml_file', $usersfile);
431 // Set up progress tracking (indeterminate).
433 $progress = new core_backup_null_progress();
435 $progress->start_progress('Loading users into temporary table');
437 // Let's parse, custom processor will do its work, sending info to DB
438 $xmlparser = new progressive_parser();
439 $xmlparser->set_file($usersfile);
440 $xmlprocessor = new restore_users_parser_processor($restoreid);
441 $xmlparser->set_processor($xmlprocessor);
442 $xmlparser->set_progress($progress);
443 $xmlparser->process();
446 $progress->end_progress();
450 * Load the needed questions.xml file to backup_ids table for future reference
452 public static function load_categories_and_questions_to_tempids($restoreid, $questionsfile) {
454 if (!file_exists($questionsfile)) { // Shouldn't happen ever, but...
455 throw new backup_helper_exception('missing_questions_xml_file', $questionsfile);
457 // Let's parse, custom processor will do its work, sending info to DB
458 $xmlparser = new progressive_parser();
459 $xmlparser->set_file($questionsfile);
460 $xmlprocessor = new restore_questions_parser_processor($restoreid);
461 $xmlparser->set_processor($xmlprocessor);
462 $xmlparser->process();
466 * Check all the included categories and questions, deciding the action to perform
467 * for each one (mapping / creation) and returning one array of problems in case
468 * something is wrong.
470 * There are some basic rules that the method below will always try to enforce:
472 * Rule1: Targets will be, always, calculated for *whole* question banks (a.k.a. contexid source),
473 * so, given 2 question categories belonging to the same bank, their target bank will be
474 * always the same. If not, we can be incurring into "fragmentation", leading to random/cloze
475 * problems (qtypes having "child" questions).
477 * Rule2: The 'moodle/question:managecategory' and 'moodle/question:add' capabilities will be
478 * checked before creating any category/question respectively and, if the cap is not allowed
479 * into upper contexts (system, coursecat)) but in lower ones (course), the *whole* question bank
480 * will be created there.
482 * Rule3: Coursecat question banks not existing in the target site will be created as course
483 * (lower ctx) question banks, never as "guessed" coursecat question banks base on depth or so.
485 * Rule4: System question banks will be created at system context if user has perms to do so. Else they
486 * will created as course (lower ctx) question banks (similary to rule3). In other words, course ctx
487 * if always a fallback for system and coursecat question banks.
489 * Also, there are some notes to clarify the scope of this method:
491 * Note1: This method won't create any question category nor question at all. It simply will calculate
492 * which actions (create/map) must be performed for each element and where, validating that all those
493 * actions are doable by the user executing the restore operation. Any problem found will be
494 * returned in the problems array, causing the restore process to stop with error.
496 * Note2: To decide if one question bank (all its question categories and questions) is going to be remapped,
497 * then all the categories and questions must exist in the same target bank. If able to do so, missing
498 * qcats and qs will be created (rule2). But if, at the end, something is missing, the whole question bank
499 * will be recreated at course ctx (rule1), no matter if that duplicates some categories/questions.
501 * Note3: We'll be using the newitemid column in the temp_ids table to store the action to be performed
502 * with each question category and question. newitemid = 0 means the qcat/q needs to be created and
503 * any other value means the qcat/q is mapped. Also, for qcats, parentitemid will contain the target
504 * context where the categories have to be created (but for module contexts where we'll keep the old
505 * one until the activity is created)
507 * Note4: All these "actions" will be "executed" later by {@link restore_create_categories_and_questions}
509 public static function precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite) {
513 // TODO: Check all qs, looking their qtypes are restorable
515 // Precheck all qcats and qs looking for target contexts / warnings / errors
516 list($syserr, $syswarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_SYSTEM);
517 list($caterr, $catwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_COURSECAT);
518 list($couerr, $couwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_COURSE);
519 list($moderr, $modwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_MODULE);
521 // Acummulate and handle errors and warnings
522 $errors = array_merge($syserr, $caterr, $couerr, $moderr);
523 $warnings = array_merge($syswarn, $catwarn, $couwarn, $modwarn);
524 if (!empty($errors)) {
525 $problems['errors'] = $errors;
527 if (!empty($warnings)) {
528 $problems['warnings'] = $warnings;
534 * This function will process all the question banks present in restore
535 * at some contextlevel (from CONTEXT_SYSTEM to CONTEXT_MODULE), finding
536 * the target contexts where each bank will be restored and returning
537 * warnings/errors as needed.
539 * Some contextlevels (system, coursecat), will delegate process to
540 * course level if any problem is found (lack of permissions, non-matching
541 * target context...). Other contextlevels (course, module) will
542 * cause return error if some problem is found.
544 * At the end, if no errors were found, all the categories in backup_temp_ids
545 * will be pointing (parentitemid) to the target context where they must be
546 * created later in the restore process.
548 * Note: at the time these prechecks are executed, activities haven't been
549 * created yet so, for CONTEXT_MODULE banks, we keep the old contextid
550 * in the parentitemid field. Once the activity (and its context) has been
551 * created, we'll update that context in the required qcats
553 * Caller {@link precheck_categories_and_questions} will, simply, execute
554 * this function for all the contextlevels, acting as a simple controller
555 * of warnings and errors.
557 * The function returns 2 arrays, one containing errors and another containing
558 * warnings. Both empty if no errors/warnings are found.
560 public static function prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, $contextlevel) {
563 // To return any errors and warnings found
567 // Specify which fallbacks must be performed
569 CONTEXT_SYSTEM => CONTEXT_COURSE,
570 CONTEXT_COURSECAT => CONTEXT_COURSE);
572 // For any contextlevel, follow this process logic:
574 // 0) Iterate over each context (qbank)
575 // 1) Iterate over each qcat in the context, matching by stamp for the found target context
576 // 2a) No match, check if user can create qcat and q
577 // 3a) User can, mark the qcat and all dependent qs to be created in that target context
578 // 3b) User cannot, check if we are in some contextlevel with fallback
579 // 4a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
580 // 4b) No fallback, error. End qcat loop.
581 // 2b) Match, mark qcat to be mapped and iterate over each q, matching by stamp and version
582 // 5a) No match, check if user can add q
583 // 6a) User can, mark the q to be created
584 // 6b) User cannot, check if we are in some contextlevel with fallback
585 // 7a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
586 // 7b) No fallback, error. End qcat loop
587 // 5b) Match, mark q to be mapped
589 // Get all the contexts (question banks) in restore for the given contextlevel
590 $contexts = self::restore_get_question_banks($restoreid, $contextlevel);
592 // 0) Iterate over each context (qbank)
593 foreach ($contexts as $contextid => $contextlevel) {
595 $canmanagecategory = false;
597 // get categories in context (bank)
598 $categories = self::restore_get_question_categories($restoreid, $contextid);
599 // cache permissions if $targetcontext is found
600 if ($targetcontext = self::restore_find_best_target_context($categories, $courseid, $contextlevel)) {
601 $canmanagecategory = has_capability('moodle/question:managecategory', $targetcontext, $userid);
602 $canadd = has_capability('moodle/question:add', $targetcontext, $userid);
604 // 1) Iterate over each qcat in the context, matching by stamp for the found target context
605 foreach ($categories as $category) {
607 if ($targetcontext) {
608 $matchcat = $DB->get_record('question_categories', array(
609 'contextid' => $targetcontext->id,
610 'stamp' => $category->stamp));
612 // 2a) No match, check if user can create qcat and q
614 // 3a) User can, mark the qcat and all dependent qs to be created in that target context
615 if ($canmanagecategory && $canadd) {
616 // Set parentitemid to targetcontext, BUT for CONTEXT_MODULE categories, where
617 // we keep the source contextid unmodified (for easier matching later when the
618 // activities are created)
619 $parentitemid = $targetcontext->id;
620 if ($contextlevel == CONTEXT_MODULE) {
621 $parentitemid = null; // null means "not modify" a.k.a. leave original contextid
623 self::set_backup_ids_record($restoreid, 'question_category', $category->id, 0, $parentitemid);
624 // Nothing else to mark, newitemid = 0 means create
626 // 3b) User cannot, check if we are in some contextlevel with fallback
628 // 4a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
629 if (array_key_exists($contextlevel, $fallbacks)) {
630 foreach ($categories as $movedcat) {
631 $movedcat->contextlevel = $fallbacks[$contextlevel];
632 self::set_backup_ids_record($restoreid, 'question_category', $movedcat->id, 0, $contextid, $movedcat);
633 // Warn about the performed fallback
634 $warnings[] = get_string('qcategory2coursefallback', 'backup', $movedcat);
637 // 4b) No fallback, error. End qcat loop.
639 $errors[] = get_string('qcategorycannotberestored', 'backup', $category);
641 break; // out from qcat loop (both 4a and 4b), we have decided about ALL categories in context (bank)
644 // 2b) Match, mark qcat to be mapped and iterate over each q, matching by stamp and version
646 self::set_backup_ids_record($restoreid, 'question_category', $category->id, $matchcat->id, $targetcontext->id);
647 $questions = self::restore_get_questions($restoreid, $category->id);
649 // Collect all the questions for this category into memory so we only talk to the DB once.
650 $questioncache = $DB->get_records_sql_menu("SELECT ".$DB->sql_concat('stamp', "' '", 'version').", id
652 WHERE category = ?", array($matchcat->id));
654 foreach ($questions as $question) {
655 if (isset($questioncache[$question->stamp." ".$question->version])) {
656 $matchqid = $questioncache[$question->stamp." ".$question->version];
660 // 5a) No match, check if user can add q
662 // 6a) User can, mark the q to be created
664 // Nothing to mark, newitemid means create
666 // 6b) User cannot, check if we are in some contextlevel with fallback
668 // 7a) There is fallback, move ALL the qcats to fallback, warn. End qcat loo
669 if (array_key_exists($contextlevel, $fallbacks)) {
670 foreach ($categories as $movedcat) {
671 $movedcat->contextlevel = $fallbacks[$contextlevel];
672 self::set_backup_ids_record($restoreid, 'question_category', $movedcat->id, 0, $contextid, $movedcat);
673 // Warn about the performed fallback
674 $warnings[] = get_string('question2coursefallback', 'backup', $movedcat);
677 // 7b) No fallback, error. End qcat loop
679 $errors[] = get_string('questioncannotberestored', 'backup', $question);
681 break 2; // out from qcat loop (both 7a and 7b), we have decided about ALL categories in context (bank)
684 // 5b) Match, mark q to be mapped
686 self::set_backup_ids_record($restoreid, 'question', $question->id, $matchqid);
693 return array($errors, $warnings);
697 * Return one array of contextid => contextlevel pairs
698 * of question banks to be checked for one given restore operation
699 * ordered from CONTEXT_SYSTEM downto CONTEXT_MODULE
700 * If contextlevel is specified, then only banks corresponding to
701 * that level are returned
703 public static function restore_get_question_banks($restoreid, $contextlevel = null) {
707 $qcats = $DB->get_recordset_sql("SELECT itemid, parentitemid AS contextid, info
708 FROM {backup_ids_temp}
710 AND itemname = 'question_category'", array($restoreid));
711 foreach ($qcats as $qcat) {
712 // If this qcat context haven't been acummulated yet, do that
713 if (!isset($results[$qcat->contextid])) {
714 $info = backup_controller_dbops::decode_backup_temp_info($qcat->info);
715 // Filter by contextlevel if necessary
716 if (is_null($contextlevel) || $contextlevel == $info->contextlevel) {
717 $results[$qcat->contextid] = $info->contextlevel;
722 // Sort by value (contextlevel from CONTEXT_SYSTEM downto CONTEXT_MODULE)
728 * Return one array of question_category records for
729 * a given restore operation and one restore context (question bank)
731 public static function restore_get_question_categories($restoreid, $contextid) {
735 $qcats = $DB->get_recordset_sql("SELECT itemid, info
736 FROM {backup_ids_temp}
738 AND itemname = 'question_category'
739 AND parentitemid = ?", array($restoreid, $contextid));
740 foreach ($qcats as $qcat) {
741 $results[$qcat->itemid] = backup_controller_dbops::decode_backup_temp_info($qcat->info);
749 * Calculates the best context found to restore one collection of qcats,
750 * al them belonging to the same context (question bank), returning the
751 * target context found (object) or false
753 public static function restore_find_best_target_context($categories, $courseid, $contextlevel) {
756 $targetcontext = false;
758 // Depending of $contextlevel, we perform different actions
759 switch ($contextlevel) {
760 // For system is easy, the best context is the system context
762 $targetcontext = context_system::instance();
765 // For coursecat, we are going to look for stamps in all the
766 // course categories between CONTEXT_SYSTEM and CONTEXT_COURSE
767 // (i.e. in all the course categories in the path)
769 // And only will return one "best" target context if all the
770 // matches belong to ONE and ONLY ONE context. If multiple
771 // matches are found, that means that there is some annoying
772 // qbank "fragmentation" in the categories, so we'll fallback
773 // to create the qbank at course level
774 case CONTEXT_COURSECAT:
775 // Build the array of stamps we are going to match
777 foreach ($categories as $category) {
778 $stamps[] = $category->stamp;
781 // Build the array of contexts we are going to look
782 $systemctx = context_system::instance();
783 $coursectx = context_course::instance($courseid);
784 $parentctxs = $coursectx->get_parent_context_ids();
785 foreach ($parentctxs as $parentctx) {
786 // Exclude system context
787 if ($parentctx == $systemctx->id) {
790 $contexts[] = $parentctx;
792 if (!empty($stamps) && !empty($contexts)) {
794 list($stamp_sql, $stamp_params) = $DB->get_in_or_equal($stamps);
795 list($context_sql, $context_params) = $DB->get_in_or_equal($contexts);
796 $sql = "SELECT contextid
797 FROM {question_categories}
798 WHERE stamp $stamp_sql
799 AND contextid $context_sql";
800 $params = array_merge($stamp_params, $context_params);
801 $matchingcontexts = $DB->get_records_sql($sql, $params);
802 // Only if ONE and ONLY ONE context is found, use it as valid target
803 if (count($matchingcontexts) == 1) {
804 $targetcontext = context::instance_by_id(reset($matchingcontexts)->contextid);
809 // For course is easy, the best context is the course context
811 $targetcontext = context_course::instance($courseid);
814 // For module is easy, there is not best context, as far as the
815 // activity hasn't been created yet. So we return context course
816 // for them, so permission checks and friends will work. Note this
817 // case is handled by {@link prechek_precheck_qbanks_by_level}
820 $targetcontext = context_course::instance($courseid);
823 return $targetcontext;
827 * Return one array of question records for
828 * a given restore operation and one question category
830 public static function restore_get_questions($restoreid, $qcatid) {
834 $qs = $DB->get_recordset_sql("SELECT itemid, info
835 FROM {backup_ids_temp}
837 AND itemname = 'question'
838 AND parentitemid = ?", array($restoreid, $qcatid));
839 foreach ($qs as $q) {
840 $results[$q->itemid] = backup_controller_dbops::decode_backup_temp_info($q->info);
847 * Given one component/filearea/context and
848 * optionally one source itemname to match itemids
849 * put the corresponding files in the pool
851 * If you specify a progress reporter, it will get called once per file with
852 * indeterminate progress.
854 * @param string $basepath the full path to the root of unzipped backup file
855 * @param string $restoreid the restore job's identification
856 * @param string $component
857 * @param string $filearea
858 * @param int $oldcontextid
859 * @param int $dfltuserid default $file->user if the old one can't be mapped
860 * @param string|null $itemname
861 * @param int|null $olditemid
862 * @param int|null $forcenewcontextid explicit value for the new contextid (skip mapping)
863 * @param bool $skipparentitemidctxmatch
864 * @param core_backup_progress $progress Optional progress reporter
865 * @return array of result object
867 public static function send_files_to_pool($basepath, $restoreid, $component, $filearea,
868 $oldcontextid, $dfltuserid, $itemname = null, $olditemid = null,
869 $forcenewcontextid = null, $skipparentitemidctxmatch = false,
870 core_backup_progress $progress = null) {
873 $backupinfo = backup_general_helper::get_backup_information(basename($basepath));
874 $includesfiles = $backupinfo->include_files;
878 if ($forcenewcontextid) {
879 // Some components can have "forced" new contexts (example: questions can end belonging to non-standard context mappings,
880 // with questions originally at system/coursecat context in source being restored to course context in target). So we need
881 // to be able to force the new contextid
882 $newcontextid = $forcenewcontextid;
884 // Get new context, must exist or this will fail
885 $newcontextrecord = self::get_backup_ids_record($restoreid, 'context', $oldcontextid);
886 if (!$newcontextrecord || !$newcontextrecord->newitemid) {
887 throw new restore_dbops_exception('unknown_context_mapping', $oldcontextid);
889 $newcontextid = $newcontextrecord->newitemid;
892 // Sometimes it's possible to have not the oldcontextids stored into backup_ids_temp->parentitemid
893 // columns (because we have used them to store other information). This happens usually with
894 // all the question related backup_ids_temp records. In that case, it's safe to ignore that
895 // matching as far as we are always restoring for well known oldcontexts and olditemids
896 $parentitemctxmatchsql = ' AND i.parentitemid = f.contextid ';
897 if ($skipparentitemidctxmatch) {
898 $parentitemctxmatchsql = '';
901 // Important: remember how files have been loaded to backup_files_temp
902 // - info: contains the whole original object (times, names...)
903 // (all them being original ids as loaded from xml)
905 // itemname = null, we are going to match only by context, no need to use itemid (all them are 0)
906 if ($itemname == null) {
907 $sql = "SELECT id AS bftid, contextid, component, filearea, itemid, itemid AS newitemid, info
908 FROM {backup_files_temp}
913 $params = array($restoreid, $oldcontextid, $component, $filearea);
915 // itemname not null, going to join with backup_ids to perform the old-new mapping of itemids
917 $sql = "SELECT f.id AS bftid, f.contextid, f.component, f.filearea, f.itemid, i.newitemid, f.info
918 FROM {backup_files_temp} f
919 JOIN {backup_ids_temp} i ON i.backupid = f.backupid
920 $parentitemctxmatchsql
921 AND i.itemid = f.itemid
927 $params = array($restoreid, $oldcontextid, $component, $filearea, $itemname);
928 if ($olditemid !== null) { // Just process ONE olditemid intead of the whole itemname
929 $sql .= ' AND i.itemid = ?';
930 $params[] = $olditemid;
934 $fs = get_file_storage(); // Get moodle file storage
935 $basepath = $basepath . '/files/';// Get backup file pool base
936 // Report progress before query.
938 $progress->progress();
940 $rs = $DB->get_recordset_sql($sql, $params);
941 foreach ($rs as $rec) {
942 // Report progress each time around loop.
944 $progress->progress();
947 $file = (object)backup_controller_dbops::decode_backup_temp_info($rec->info);
949 // ignore root dirs (they are created automatically)
950 if ($file->filepath == '/' && $file->filename == '.') {
954 // set the best possible user
955 $mappeduser = self::get_backup_ids_record($restoreid, 'user', $file->userid);
956 $mappeduserid = !empty($mappeduser) ? $mappeduser->newitemid : $dfltuserid;
958 // dir found (and not root one), let's create it
959 if ($file->filename == '.') {
960 $fs->create_directory($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $mappeduserid);
964 // The file record to restore.
965 $file_record = array(
966 'contextid' => $newcontextid,
967 'component' => $component,
968 'filearea' => $filearea,
969 'itemid' => $rec->newitemid,
970 'filepath' => $file->filepath,
971 'filename' => $file->filename,
972 'timecreated' => $file->timecreated,
973 'timemodified'=> $file->timemodified,
974 'userid' => $mappeduserid,
975 'author' => $file->author,
976 'license' => $file->license,
977 'sortorder' => $file->sortorder
980 if (empty($file->repositoryid)) {
981 // If contenthash is empty then gracefully skip adding file.
982 if (empty($file->contenthash)) {
983 $result = new stdClass();
984 $result->code = 'file_missing_in_backup';
985 $result->message = sprintf('missing file (%s) contenthash in backup for component %s', $file->filename, $component);
986 $result->level = backup::LOG_WARNING;
987 $results[] = $result;
990 // this is a regular file, it must be present in the backup pool
991 $backuppath = $basepath . backup_file_manager::get_backup_content_file_location($file->contenthash);
993 // Some file types do not include the files as they should already be
994 // present. We still need to create entries into the files table.
995 if ($includesfiles) {
996 // The file is not found in the backup.
997 if (!file_exists($backuppath)) {
998 $results[] = self::get_missing_file_result($file);
1002 // create the file in the filepool if it does not exist yet
1003 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
1005 // If no license found, use default.
1006 if ($file->license == null){
1007 $file->license = $CFG->sitedefaultlicense;
1010 $fs->create_file_from_pathname($file_record, $backuppath);
1013 // This backup does not include the files - they should be available in moodle filestorage already.
1015 // Create the file in the filepool if it does not exist yet.
1016 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
1018 // Even if a file has been deleted since the backup was made, the file metadata will remain in the
1019 // files table, and the file will not be moved to the trashdir.
1020 // Files are not cleared from the files table by cron until several days after deletion.
1021 if ($foundfiles = $DB->get_records('files', array('contenthash' => $file->contenthash))) {
1022 // Only grab one of the foundfiles - the file content should be the same for all entries.
1023 $foundfile = reset($foundfiles);
1024 $fs->create_file_from_storedfile($file_record, $foundfile->id);
1026 // A matching existing file record was not found in the database.
1027 $results[] = self::get_missing_file_result($file);
1033 // store the the new contextid and the new itemid in case we need to remap
1034 // references to this file later
1035 $DB->update_record('backup_files_temp', array(
1036 'id' => $rec->bftid,
1037 'newcontextid' => $newcontextid,
1038 'newitemid' => $rec->newitemid), true);
1041 // this is an alias - we can't create it yet so we stash it in a temp
1042 // table and will let the final task to deal with it
1043 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
1044 $info = new stdClass();
1045 // oldfile holds the raw information stored in MBZ (including reference-related info)
1046 $info->oldfile = $file;
1047 // newfile holds the info for the new file_record with the context, user and itemid mapped
1048 $info->newfile = (object) $file_record;
1050 restore_dbops::set_backup_ids_record($restoreid, 'file_aliases_queue', $file->id, 0, null, $info);
1059 * Returns suitable entry to include in log when there is a missing file.
1061 * @param stdClass $file File definition
1062 * @return stdClass Log entry
1064 protected static function get_missing_file_result($file) {
1065 $result = new stdClass();
1066 $result->code = 'file_missing_in_backup';
1067 $result->message = 'Missing file in backup: ' . $file->filepath . $file->filename .
1068 ' (old context ' . $file->contextid . ', component ' . $file->component .
1069 ', filearea ' . $file->filearea . ', old itemid ' . $file->itemid . ')';
1070 $result->level = backup::LOG_WARNING;
1075 * Given one restoreid, create in DB all the users present
1076 * in backup_ids having newitemid = 0, as far as
1077 * precheck_included_users() have left them there
1078 * ready to be created. Also, annotate their newids
1079 * once created for later reference.
1081 * This function will start and end a new progress section in the progress
1084 * @param string $basepath Base path of unzipped backup
1085 * @param string $restoreid Restore ID
1086 * @param int $userid Default userid for files
1087 * @param core_backup_progress $progress Object used for progress tracking
1089 public static function create_included_users($basepath, $restoreid, $userid,
1090 core_backup_progress $progress) {
1092 $progress->start_progress('Creating included users');
1094 $authcache = array(); // Cache to get some bits from authentication plugins
1095 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search later
1096 $themes = get_list_of_themes(); // Get themes for quick search later
1098 // Iterate over all the included users with newitemid = 0, have to create them
1099 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid, info');
1100 foreach ($rs as $recuser) {
1101 $progress->progress();
1102 $user = (object)backup_controller_dbops::decode_backup_temp_info($recuser->info);
1104 // if user lang doesn't exist here, use site default
1105 if (!array_key_exists($user->lang, $languages)) {
1106 $user->lang = $CFG->lang;
1109 // if user theme isn't available on target site or they are disabled, reset theme
1110 if (!empty($user->theme)) {
1111 if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) {
1116 // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id
1117 // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual
1118 if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
1119 // Respect registerauth
1120 if ($CFG->registerauth == 'email') {
1121 $user->auth = 'email';
1123 $user->auth = 'manual';
1126 unset($user->mnethosturl); // Not needed anymore
1128 // Disable pictures based on global setting
1129 if (!empty($CFG->disableuserimages)) {
1133 // We need to analyse the AUTH field to recode it:
1134 // - if the auth isn't enabled in target site, $CFG->registerauth will decide
1135 // - finally, if the auth resulting isn't enabled, default to 'manual'
1136 if (!is_enabled_auth($user->auth)) {
1137 if ($CFG->registerauth == 'email') {
1138 $user->auth = 'email';
1140 $user->auth = 'manual';
1143 if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled
1144 $user->auth = 'manual';
1147 // Now that we know the auth method, for users to be created without pass
1148 // if password handling is internal and reset password is available
1149 // we set the password to "restored" (plain text), so the login process
1150 // will know how to handle that situation in order to allow the user to
1151 // recover the password. MDL-20846
1152 if (empty($user->password)) { // Only if restore comes without password
1153 if (!array_key_exists($user->auth, $authcache)) { // Not in cache
1154 $userauth = new stdClass();
1155 $authplugin = get_auth_plugin($user->auth);
1156 $userauth->preventpassindb = $authplugin->prevent_local_passwords();
1157 $userauth->isinternal = $authplugin->is_internal();
1158 $userauth->canresetpwd = $authplugin->can_reset_password();
1159 $authcache[$user->auth] = $userauth;
1161 $userauth = $authcache[$user->auth]; // Get from cache
1164 // Most external plugins do not store passwords locally
1165 if (!empty($userauth->preventpassindb)) {
1166 $user->password = AUTH_PASSWORD_NOT_CACHED;
1168 // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
1169 } else if ($userauth->isinternal and $userauth->canresetpwd) {
1170 $user->password = 'restored';
1174 // Creating new user, we must reset the policyagreed always
1175 $user->policyagreed = 0;
1177 // Set time created if empty
1178 if (empty($user->timecreated)) {
1179 $user->timecreated = time();
1182 // Done, let's create the user and annotate its id
1183 $newuserid = $DB->insert_record('user', $user);
1184 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid);
1185 // Let's create the user context and annotate it (we need it for sure at least for files)
1186 // but for deleted users that don't have a context anymore (MDL-30192). We are done for them
1187 // and nothing else (custom fields, prefs, tags, files...) will be created.
1188 if (empty($user->deleted)) {
1189 $newuserctxid = $user->deleted ? 0 : context_user::instance($newuserid)->id;
1190 self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid);
1192 // Process custom fields
1193 if (isset($user->custom_fields)) { // if present in backup
1194 foreach($user->custom_fields['custom_field'] as $udata) {
1195 $udata = (object)$udata;
1196 // If the profile field has data and the profile shortname-datatype is defined in server
1197 if ($udata->field_data) {
1198 if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) {
1199 /// Insert the user_custom_profile_field
1200 $rec = new stdClass();
1201 $rec->userid = $newuserid;
1202 $rec->fieldid = $field->id;
1203 $rec->data = $udata->field_data;
1204 $DB->insert_record('user_info_data', $rec);
1211 if (!empty($CFG->usetags) && isset($user->tags)) { // if enabled in server and present in backup
1213 foreach($user->tags['tag'] as $usertag) {
1214 $usertag = (object)$usertag;
1215 $tags[] = $usertag->rawname;
1217 tag_set('user', $newuserid, $tags);
1220 // Process preferences
1221 if (isset($user->preferences)) { // if present in backup
1222 foreach($user->preferences['preference'] as $preference) {
1223 $preference = (object)$preference;
1224 // Prepare the record and insert it
1225 $preference->userid = $newuserid;
1226 $status = $DB->insert_record('user_preferences', $preference);
1229 // Special handling for htmleditor which was converted to a preference.
1230 if (isset($user->htmleditor)) {
1231 if ($user->htmleditor == 0) {
1232 $preference = new stdClass();
1233 $preference->userid = $newuserid;
1234 $preference->name = 'htmleditor';
1235 $preference->value = 'textarea';
1236 $status = $DB->insert_record('user_preferences', $preference);
1240 // Create user files in pool (profile, icon, private) by context
1241 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon',
1242 $recuser->parentitemid, $userid, null, null, null, false, $progress);
1243 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile',
1244 $recuser->parentitemid, $userid, null, null, null, false, $progress);
1248 $progress->end_progress();
1252 * Given one user object (from backup file), perform all the neccesary
1253 * checks is order to decide how that user will be handled on restore.
1255 * Note the function requires $user->mnethostid to be already calculated
1256 * so it's caller responsibility to set it
1258 * This function is used both by @restore_precheck_users() and
1259 * @restore_create_users() to get consistent results in both places
1262 * - one user object (from DB), if match has been found and user will be remapped
1263 * - boolean true if the user needs to be created
1264 * - boolean false if some conflict happened and the user cannot be handled
1266 * Each test is responsible for returning its results and interrupt
1267 * execution. At the end, boolean true (user needs to be created) will be
1268 * returned if no test has interrupted that.
1270 * Here it's the logic applied, keep it updated:
1272 * If restoring users from same site backup:
1273 * 1A - Normal check: If match by id and username and mnethost => ok, return target user
1274 * 1B - If restoring an 'anonymous' user (created via the 'Anonymize user information' option) try to find a
1275 * match by username only => ok, return target user MDL-31484
1276 * 1C - Handle users deleted in DB and "alive" in backup file:
1277 * If match by id and mnethost and user is deleted in DB and
1278 * (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user
1279 * 1D - Handle users deleted in backup file and "alive" in DB:
1280 * If match by id and mnethost and user is deleted in backup file
1281 * and match by email = email_without_time(backup_email) => ok, return target user
1282 * 1E - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false
1283 * 1F - None of the above, return true => User needs to be created
1285 * if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination):
1286 * 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user
1287 * 2B - Handle users deleted in DB and "alive" in backup file:
1288 * 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
1289 * (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
1290 * 2B2 - If match by mnethost and user is deleted in DB and
1291 * username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
1292 * (to cover situations were md5(username) wasn't implemented on delete we requiere both)
1293 * 2C - Handle users deleted in backup file and "alive" in DB:
1294 * If match mnethost and user is deleted in backup file
1295 * and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
1296 * 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
1297 * 2E - None of the above, return true => User needs to be created
1299 * Note: for DB deleted users email is stored in username field, hence we
1300 * are looking there for emails. See delete_user()
1301 * Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1302 * hence we are looking there for usernames if not empty. See delete_user()
1304 protected static function precheck_user($user, $samesite) {
1307 // Handle checks from same site backups
1308 if ($samesite && empty($CFG->forcedifferentsitecheckingusersonrestore)) {
1310 // 1A - If match by id and username and mnethost => ok, return target user
1311 if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
1312 return $rec; // Matching user found, return it
1315 // 1B - If restoring an 'anonymous' user (created via the 'Anonymize user information' option) try to find a
1316 // match by username only => ok, return target user MDL-31484
1317 // This avoids username / id mis-match problems when restoring subsequent anonymized backups.
1318 if (backup_anonymizer_helper::is_anonymous_user($user)) {
1319 if ($rec = $DB->get_record('user', array('username' => $user->username))) {
1320 return $rec; // Matching anonymous user found - return it
1324 // 1C - Handle users deleted in DB and "alive" in backup file
1325 // Note: for DB deleted users email is stored in username field, hence we
1326 // are looking there for emails. See delete_user()
1327 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1328 // hence we are looking there for usernames if not empty. See delete_user()
1329 // If match by id and mnethost and user is deleted in DB and
1330 // match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user
1331 if ($rec = $DB->get_record_sql("SELECT *
1337 UPPER(username) LIKE UPPER(?)
1339 ".$DB->sql_isnotempty('user', 'email', false, false)."
1343 array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) {
1344 return $rec; // Matching user, deleted in DB found, return it
1347 // 1D - Handle users deleted in backup file and "alive" in DB
1348 // If match by id and mnethost and user is deleted in backup file
1349 // and match by email = email_without_time(backup_email) => ok, return target user
1350 if ($user->deleted) {
1351 // Note: for DB deleted users email is stored in username field, hence we
1352 // are looking there for emails. See delete_user()
1353 // Trim time() from email
1354 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
1355 if ($rec = $DB->get_record_sql("SELECT *
1359 AND UPPER(email) = UPPER(?)",
1360 array($user->id, $user->mnethostid, $trimemail))) {
1361 return $rec; // Matching user, deleted in backup file found, return it
1365 // 1E - If match by username and mnethost and doesn't match by id => conflict, return false
1366 if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
1367 if ($user->id != $rec->id) {
1368 return false; // Conflict, username already exists and belongs to another id
1372 // Handle checks from different site backups
1375 // 2A - If match by username and mnethost and
1376 // (email or non-zero firstaccess) => ok, return target user
1377 if ($rec = $DB->get_record_sql("SELECT *
1382 UPPER(email) = UPPER(?)
1388 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
1389 return $rec; // Matching user found, return it
1392 // 2B - Handle users deleted in DB and "alive" in backup file
1393 // Note: for DB deleted users email is stored in username field, hence we
1394 // are looking there for emails. See delete_user()
1395 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1396 // hence we are looking there for usernames if not empty. See delete_user()
1397 // 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
1398 // (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
1399 if ($rec = $DB->get_record_sql("SELECT *
1401 WHERE mnethostid = ?
1403 AND ".$DB->sql_isnotempty('user', 'email', false, false)."
1406 UPPER(username) LIKE UPPER(?)
1412 array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) {
1413 return $rec; // Matching user found, return it
1416 // 2B2 - If match by mnethost and user is deleted in DB and
1417 // username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
1418 // (this covers situations where md5(username) wasn't being stored so we require both
1419 // the email & non-zero firstaccess to match)
1420 if ($rec = $DB->get_record_sql("SELECT *
1422 WHERE mnethostid = ?
1424 AND UPPER(username) LIKE UPPER(?)
1425 AND firstaccess != 0
1426 AND firstaccess = ?",
1427 array($user->mnethostid, $user->email.'.%', $user->firstaccess))) {
1428 return $rec; // Matching user found, return it
1431 // 2C - Handle users deleted in backup file and "alive" in DB
1432 // If match mnethost and user is deleted in backup file
1433 // and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
1434 if ($user->deleted) {
1435 // Note: for DB deleted users email is stored in username field, hence we
1436 // are looking there for emails. See delete_user()
1437 // Trim time() from email
1438 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
1439 if ($rec = $DB->get_record_sql("SELECT *
1441 WHERE mnethostid = ?
1442 AND UPPER(email) = UPPER(?)
1443 AND firstaccess != 0
1444 AND firstaccess = ?",
1445 array($user->mnethostid, $trimemail, $user->firstaccess))) {
1446 return $rec; // Matching user, deleted in backup file found, return it
1450 // 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
1451 if ($rec = $DB->get_record_sql("SELECT *
1456 UPPER(email) = UPPER(?)
1462 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
1463 return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess)
1467 // Arrived here, return true as the user will need to be created and no
1468 // conflicts have been found in the logic above. This covers:
1469 // 1E - else => user needs to be created, return true
1470 // 2E - else => user needs to be created, return true
1475 * Check all the included users, deciding the action to perform
1476 * for each one (mapping / creation) and returning one array
1477 * of problems in case something is wrong (lack of permissions,
1480 * @param string $restoreid Restore id
1481 * @param int $courseid Course id
1482 * @param int $userid User id
1483 * @param bool $samesite True if restore is to same site
1484 * @param core_backup_progress $progress Progress reporter
1486 public static function precheck_included_users($restoreid, $courseid, $userid, $samesite,
1487 core_backup_progress $progress) {
1490 // To return any problem found
1491 $problems = array();
1493 // We are going to map mnethostid, so load all the available ones
1494 $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id');
1496 // Calculate the context we are going to use for capability checking
1497 $context = context_course::instance($courseid);
1499 // Calculate if we have perms to create users, by checking:
1500 // to 'moodle/restore:createuser' and 'moodle/restore:userinfo'
1501 // and also observe $CFG->disableusercreationonrestore
1502 $cancreateuser = false;
1503 if (has_capability('moodle/restore:createuser', $context, $userid) and
1504 has_capability('moodle/restore:userinfo', $context, $userid) and
1505 empty($CFG->disableusercreationonrestore)) { // Can create users
1507 $cancreateuser = true;
1510 // Prepare for reporting progress.
1511 $conditions = array('backupid' => $restoreid, 'itemname' => 'user');
1512 $max = $DB->count_records('backup_ids_temp', $conditions);
1514 $progress->start_progress('Checking users', $max);
1516 // Iterate over all the included users
1517 $rs = $DB->get_recordset('backup_ids_temp', $conditions, '', 'itemid, info');
1518 foreach ($rs as $recuser) {
1519 $user = (object)backup_controller_dbops::decode_backup_temp_info($recuser->info);
1521 // Find the correct mnethostid for user before performing any further check
1522 if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
1523 $user->mnethostid = $CFG->mnet_localhost_id;
1525 // fast url-to-id lookups
1526 if (isset($mnethosts[$user->mnethosturl])) {
1527 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
1529 $user->mnethostid = $CFG->mnet_localhost_id;
1533 // Now, precheck that user and, based on returned results, annotate action/problem
1534 $usercheck = self::precheck_user($user, $samesite);
1536 if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to
1537 // Annotate it, for later process. Set newitemid to mapping user->id
1538 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $usercheck->id);
1540 } else if ($usercheck === false) { // Found conflict, report it as problem
1541 $problems[] = get_string('restoreuserconflict', '', $user->username);
1543 } else if ($usercheck === true) { // User needs to be created, check if we are able
1544 if ($cancreateuser) { // Can create user, set newitemid to 0 so will be created later
1545 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, 0, null, (array)$user);
1547 } else { // Cannot create user, report it as problem
1548 $problems[] = get_string('restorecannotcreateuser', '', $user->username);
1551 } else { // Shouldn't arrive here ever, something is for sure wrong. Exception
1552 throw new restore_dbops_exception('restore_error_processing_user', $user->username);
1555 $progress->progress($done);
1558 $progress->end_progress();
1563 * Process the needed users in order to decide
1564 * which action to perform with them (create/map)
1566 * Just wrap over precheck_included_users(), returning
1567 * exception if any problem is found
1569 * @param string $restoreid Restore id
1570 * @param int $courseid Course id
1571 * @param int $userid User id
1572 * @param bool $samesite True if restore is to same site
1573 * @param core_backup_progress $progress Optional progress tracker
1575 public static function process_included_users($restoreid, $courseid, $userid, $samesite,
1576 core_backup_progress $progress = null) {
1579 // Just let precheck_included_users() to do all the hard work
1580 $problems = self::precheck_included_users($restoreid, $courseid, $userid, $samesite, $progress);
1582 // With problems, throw exception, shouldn't happen if prechecks were originally
1583 // executed, so be radical here.
1584 if (!empty($problems)) {
1585 throw new restore_dbops_exception('restore_problems_processing_users', null, implode(', ', $problems));
1590 * Process the needed question categories and questions
1591 * to check all them, deciding about the action to perform
1592 * (create/map) and target.
1594 * Just wrap over precheck_categories_and_questions(), returning
1595 * exception if any problem is found
1597 public static function process_categories_and_questions($restoreid, $courseid, $userid, $samesite) {
1600 // Just let precheck_included_users() to do all the hard work
1601 $problems = self::precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite);
1603 // With problems of type error, throw exception, shouldn't happen if prechecks were originally
1604 // executed, so be radical here.
1605 if (array_key_exists('errors', $problems)) {
1606 throw new restore_dbops_exception('restore_problems_processing_questions', null, implode(', ', $problems['errors']));
1610 public static function set_backup_files_record($restoreid, $filerec) {
1613 // Store external files info in `info` field
1614 $filerec->info = backup_controller_dbops::encode_backup_temp_info($filerec); // Encode the whole record into info.
1615 $filerec->backupid = $restoreid;
1616 $DB->insert_record('backup_files_temp', $filerec);
1619 public static function set_backup_ids_record($restoreid, $itemname, $itemid, $newitemid = 0, $parentitemid = null, $info = null) {
1620 // Build conditionally the extra record info
1621 $extrarecord = array();
1622 if ($newitemid != 0) {
1623 $extrarecord['newitemid'] = $newitemid;
1625 if ($parentitemid != null) {
1626 $extrarecord['parentitemid'] = $parentitemid;
1628 if ($info != null) {
1629 $extrarecord['info'] = backup_controller_dbops::encode_backup_temp_info($info);
1632 self::set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord);
1635 public static function get_backup_ids_record($restoreid, $itemname, $itemid) {
1636 $dbrec = self::get_backup_ids_cached($restoreid, $itemname, $itemid);
1638 // We must test if info is a string, as the cache stores info in object form.
1639 if ($dbrec && isset($dbrec->info) && is_string($dbrec->info)) {
1640 $dbrec->info = backup_controller_dbops::decode_backup_temp_info($dbrec->info);
1647 * Given on courseid, fullname and shortname, calculate the correct fullname/shortname to avoid dupes
1649 public static function calculate_course_names($courseid, $fullname, $shortname) {
1652 $currentfullname = '';
1653 $currentshortname = '';
1655 // Iteratere while the name exists
1658 $suffixfull = ' ' . get_string('copyasnoun') . ' ' . $counter;
1659 $suffixshort = '_' . $counter;
1664 $currentfullname = $fullname.$suffixfull;
1665 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; // < 100cc
1666 $coursefull = $DB->get_record_select('course', 'fullname = ? AND id != ?',
1667 array($currentfullname, $courseid), '*', IGNORE_MULTIPLE);
1668 $courseshort = $DB->get_record_select('course', 'shortname = ? AND id != ?', array($currentshortname, $courseid));
1670 } while ($coursefull || $courseshort);
1673 return array($currentfullname, $currentshortname);
1677 * For the target course context, put as many custom role names as possible
1679 public static function set_course_role_names($restoreid, $courseid) {
1682 // Get the course context
1683 $coursectx = context_course::instance($courseid);
1684 // Get all the mapped roles we have
1685 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid, info, newitemid');
1686 foreach ($rs as $recrole) {
1687 $info = backup_controller_dbops::decode_backup_temp_info($recrole->info);
1688 // If it's one mapped role and we have one name for it
1689 if (!empty($recrole->newitemid) && !empty($info['nameincourse'])) {
1690 // If role name doesn't exist, add it
1691 $rolename = new stdclass();
1692 $rolename->roleid = $recrole->newitemid;
1693 $rolename->contextid = $coursectx->id;
1694 if (!$DB->record_exists('role_names', (array)$rolename)) {
1695 $rolename->name = $info['nameincourse'];
1696 $DB->insert_record('role_names', $rolename);
1704 * Creates a skeleton record within the database using the passed parameters
1705 * and returns the new course id.
1707 * @global moodle_database $DB
1708 * @param string $fullname
1709 * @param string $shortname
1710 * @param int $categoryid
1711 * @return int The new course id
1713 public static function create_new_course($fullname, $shortname, $categoryid) {
1715 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1717 $course = new stdClass;
1718 $course->fullname = $fullname;
1719 $course->shortname = $shortname;
1720 $course->category = $category->id;
1721 $course->sortorder = 0;
1722 $course->timecreated = time();
1723 $course->timemodified = $course->timecreated;
1724 // forcing skeleton courses to be hidden instead of going by $category->visible , until MDL-27790 is resolved.
1725 $course->visible = 0;
1727 $courseid = $DB->insert_record('course', $course);
1729 $category->coursecount++;
1730 $DB->update_record('course_categories', $category);
1736 * Deletes all of the content associated with the given course (courseid)
1737 * @param int $courseid
1738 * @param array $options
1739 * @return bool True for success
1741 public static function delete_course_content($courseid, array $options = null) {
1742 return remove_course_contents($courseid, false, $options);
1747 * Exception class used by all the @dbops stuff
1749 class restore_dbops_exception extends backup_exception {
1751 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
1752 parent::__construct($errorcode, 'error', '', $a, null, $debuginfo);