MDL-21840 backup - table for files handling on restore. Big thanks to MySQL for being...
[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
EL
30abstract class restore_dbops {
31
32 /**
33 * Return all the inforef.xml files to be loaded into the temp_ids table
34 * We do that by loading the controller from DB, then iterating over all the
35 * included tasks and calculating all the inforef files for them
36 */
37 public static function get_needed_inforef_files($restoreid) {
38 $rc = restore_controller_dbops::load_controller($restoreid);
39 $tasks = $rc->get_plan()->get_tasks();
40 $files = array();
41 foreach ($tasks as $task) {
42 // Calculate if the task is being included
43 $included = false;
44 // blocks, based in blocks setting and parent activity/course
45 if ($task instanceof restore_block_task) {
46 if (!$task->get_setting('blocks')) { // Blocks not included, continue
47 continue;
48 }
49 $parent = basename(dirname(dirname($task->get_taskbasepath())));
50 if ($parent == 'course') { // Parent is course, always included if present
51 $included = true;
52
53 } else { // Look for activity_included setting
54 $included = $task->get_setting_value($parent . '_included');
55 }
56
57 // ativities, based on included setting
58 } else if ($task instanceof restore_activity_task) {
59 $included = $task->get_setting_value('included');
60
61 // sections, based on included setting
62 } else if ($task instanceof restore_section_task) {
63 $included = $task->get_setting_value('included');
64
65 // course always included if present
66 } else if ($task instanceof restore_course_task) {
67 $included = true;
68 }
69
70 // If included and file exists, add it to results
71 if ($included) {
72 $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
73 if (file_exists($inforefpath)) {
74 $files[] = $inforefpath;
75 }
76 }
77 }
78 return $files;
79 }
80
81 /**
82 * Load one inforef.xml file to backup_ids table for future reference
83 */
84 public static function load_inforef_to_tempids($restoreid, $inforeffile) {
85
86 if (!file_exists($inforeffile)) { // Shouldn't happen ever, but...
87 throw new backup_helper_exception('missing_inforef_xml_file', $inforeffile);
88 }
89 // Let's parse, custom processor will do its work, sending info to DB
90 $xmlparser = new progressive_parser();
91 $xmlparser->set_file($inforeffile);
92 $xmlprocessor = new restore_inforef_parser_processor($restoreid);
93 $xmlparser->set_processor($xmlprocessor);
94 $xmlparser->process();
95 }
96
97 /**
98 * Load the needed users.xml file to backup_ids table for future reference
99 */
100 public static function load_users_to_tempids($restoreid, $usersfile) {
101
102 if (!file_exists($usersfile)) { // Shouldn't happen ever, but...
2df0f295 103 throw new backup_helper_exception('missing_users_xml_file', $usersfile);
482aac65
EL
104 }
105 // Let's parse, custom processor will do its work, sending info to DB
106 $xmlparser = new progressive_parser();
107 $xmlparser->set_file($usersfile);
108 $xmlprocessor = new restore_users_parser_processor($restoreid);
109 $xmlparser->set_processor($xmlprocessor);
110 $xmlparser->process();
111 }
112
2df0f295
EL
113 /**
114 * Given one component/filearea/context and
115 * optionally one source itemname to match itemids
116 * put the corresponding files in the pool
117 */
118 public static function send_files_to_pool($basepath, $restoreid, $component, $filearea, $oldcontextid, $itemname = null) {
119 global $DB;
120
121 // Get new context, must exist or this will fail
122 if (!$newcontextid = self::get_backup_ids_record($restoreid, 'context', $oldcontextid)->newitemid) {
123 throw new restore_dbops_exception('unknown_context_mapping', $oldcontextid);
124 }
125
126 // Important: remember how files have been loaded to backup_ids_temp
127 // - itemname: contains "file*component*fileara"
128 // - itemid: contains the original id of the file
129 // - newitemid: contains the itemid of the file
130 // - parentitemid: contains the context of the file
131 // - info: contains the whole original object (times, names...)
132 // (all them being original ids as loaded from xml)
133
134 // itemname = null, we are going to match only by context, no need to use itemid (all them are 0)
135 if ($itemname == null) {
136 $sql = 'SELECT id, itemname, itemid, 0 AS newitemid
137 FROM {backup_ids_temp}
138 WHERE backupid = ?
139 AND itemname = ?
140 AND parentitemid = ?';
141 $params = array($restoreid, 'file*' . $component . '*' . $filearea, $oldcontextid);
142
143 // itemname not null, going to join by context and itemid, we'll need itemid (non zero)
144 } else {
145 $sql = 'SELECT f.id, f.itemname, f.itemid, i.newitemid
146 FROM {backup_ids_temp} f
147 JOIN {backup_ids_temp} i ON i.backupid = f.backupid
148 AND i.parentitemid = f.parentitemid
149 AND i.itemid = f.newitemid
150 WHERE f.backupid = ?
151 AND f.itemname = ?
152 AND f.parentitemid = ?
153 AND i.itemname = ?';
154 $params = array($restoreid, 'file*' . $component . '*' . $filearea, $oldcontextid, $itemname);
155 }
156
157 $rs = $DB->get_recordset_sql($sql, $params);
158 $fs = get_file_storage(); // Get moodle file storage
159 $basepath = $basepath . '/files/';// Get backup file pool base
160 foreach ($rs as $rec) {
161 $file = (object)self::get_backup_ids_record($restoreid, $rec->itemname, $rec->itemid)->info;
162 // ignore root dirs (they are created automatically)
163 if ($file->filepath == '/' && $file->filename == '.') {
164 continue;
165 }
166 // dir found (and not root one), let's create if
167 if ($file->filename == '.') {
168 $fs->create_directory($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath);
169 continue;
170 }
171 // arrived here, file found
172 // Find file in backup pool
173 $backuppath = $basepath . backup_file_manager::get_content_file_location($file->contenthash);
174 if (!file_exists($backuppath)) {
175 throw new restore_dbops_exception('file_not_found_in_pool', $file);
176 }
177 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
178 $file_record = array(
179 'contextid' => $newcontextid,
180 'component' => $component,
181 'filearea' => $filearea,
182 'itemid' => $rec->newitemid,
183 'filepath' => $file->filepath,
184 'filename' => $file->filename,
185 'timecreated' => $file->timecreated,
186 'timemodified'=> $file->timemodified,
187 'author' => $file->author,
188 'license' => $file->license);
189 $fs->create_file_from_pathname($file_record, $backuppath);
190 }
191 }
192 $rs->close();
193 }
194
482aac65
EL
195 /**
196 * Given one restoreid, create in DB all the users present
197 * in backup_ids having newitemid = 0, as far as
198 * precheck_included_users() have left them there
199 * ready to be created. Also, annotate their newids
200 * once created for later reference
201 */
2df0f295 202 public static function create_included_users($basepath, $restoreid, $userfiles) {
482aac65
EL
203 global $CFG, $DB;
204
205 $authcache = array(); // Cache to get some bits from authentication plugins
206 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search later
207 $themes = get_list_of_themes(); // Get themes for quick search later
208
209 // Iterate over all the included users with newitemid = 0, have to create them
210 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid');
211 foreach ($rs as $recuser) {
212 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
213
214 // if user lang doesn't exist here, use site default
215 if (!array_key_exists($user->lang, $languages)) {
216 $user->lang = $CFG->lang;
217 }
218
219 // if user theme isn't available on target site or they are disabled, reset theme
220 if (!empty($user->theme)) {
221 if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) {
222 $user->theme = '';
223 }
224 }
225
226 // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id
227 // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual
228 if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
229 // Respect registerauth
230 if ($CFG->registerauth == 'email') {
231 $user->auth = 'email';
232 } else {
233 $user->auth = 'manual';
234 }
235 }
236 unset($user->mnethosturl); // Not needed anymore
237
238 // Disable pictures based on global setting
239 if (!empty($CFG->disableuserimages)) {
240 $user->picture = 0;
241 }
242
243 // We need to analyse the AUTH field to recode it:
244 // - if the auth isn't enabled in target site, $CFG->registerauth will decide
245 // - finally, if the auth resulting isn't enabled, default to 'manual'
246 if (!is_enabled_auth($user->auth)) {
247 if ($CFG->registerauth == 'email') {
248 $user->auth = 'email';
249 } else {
250 $user->auth = 'manual';
251 }
252 }
253 if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled
254 $user->auth = 'manual';
255 }
256
257 // Now that we know the auth method, for users to be created without pass
258 // if password handling is internal and reset password is available
259 // we set the password to "restored" (plain text), so the login process
260 // will know how to handle that situation in order to allow the user to
261 // recover the password. MDL-20846
262 if (empty($user->password)) { // Only if restore comes without password
263 if (!array_key_exists($user->auth, $authcache)) { // Not in cache
264 $userauth = new stdClass();
265 $authplugin = get_auth_plugin($user->auth);
266 $userauth->preventpassindb = $authplugin->prevent_local_passwords();
267 $userauth->isinternal = $authplugin->is_internal();
268 $userauth->canresetpwd = $authplugin->can_reset_password();
269 $authcache[$user->auth] = $userauth;
270 } else {
271 $userauth = $authcache[$user->auth]; // Get from cache
272 }
273
274 // Most external plugins do not store passwords locally
275 if (!empty($userauth->preventpassindb)) {
276 $user->password = 'not cached';
277
278 // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
279 } else if ($userauth->isinternal and $userauth->canresetpwd) {
280 $user->password = 'restored';
281 }
282 }
283
284 // Creating new user, we must reset the policyagreed always
285 $user->policyagreed = 0;
286
287 // Set time created if empty
288 if (empty($user->timecreated)) {
289 $user->timecreated = time();
290 }
291
292 // Done, let's create the user and annotate its id
293 $newuserid = $DB->insert_record('user', $user);
294 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid);
295 // Let's create the user context and annotate it (we need it for sure at least for files)
296 $newuserctxid = get_context_instance(CONTEXT_USER, $newuserid)->id;
297 self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid);
298
299 // Process custom fields
300 if (isset($user->custom_fields)) { // if present in backup
301 foreach($user->custom_fields['custom_field'] as $udata) {
302 $udata = (object)$udata;
303 // If the profile field has data and the profile shortname-datatype is defined in server
304 if ($udata->field_data) {
305 if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) {
306 /// Insert the user_custom_profile_field
307 $rec = new object();
308 $rec->userid = $newuserid;
309 $rec->fieldid = $field->id;
310 $rec->data = $udata->field_data;
311 $DB->insert_record('user_info_data', $rec);
312 }
313 }
314 }
315 }
316
317 // Process tags
318 if (!empty($CFG->usetags) && isset($user->tags)) { // if enabled in server and present in backup
319 $tags = array();
320 foreach($user->tags['tag'] as $usertag) {
321 $usertag = (object)$usertag;
322 $tags[] = $usertag->rawname;
323 }
324 tag_set('user', $newuserid, $tags);
325 }
326
327 // Process preferences
328 if (isset($user->preferences)) { // if present in backup
2df0f295 329 foreach($user->preferences['preference'] as $preference) {
482aac65
EL
330 $preference = (object)$preference;
331 // Prepare the record and insert it
332 $preference->userid = $newuserid;
333 $status = $DB->insert_record('user_preferences', $preference);
334 }
335 }
336
2df0f295
EL
337 // Create user files in pool (profile, icon, private) by context
338 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon', $recuser->parentitemid);
339 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile', $recuser->parentitemid);
340 if ($userfiles) { // private files only if enabled in settings
341 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'private', $recuser->parentitemid);
342 }
343
482aac65
EL
344 }
345 $rs->close();
346 }
347
348 /**
349 * Given one user object (from backup file), perform all the neccesary
350 * checks is order to decide how that user will be handled on restore.
351 *
352 * Note the function requires $user->mnethostid to be already calculated
353 * so it's caller responsibility to set it
354 *
355 * This function is used both by @restore_precheck_users() and
356 * @restore_create_users() to get consistent results in both places
357 *
358 * It returns:
359 * - one user object (from DB), if match has been found and user will be remapped
360 * - boolean true if the user needs to be created
361 * - boolean false if some conflict happened and the user cannot be handled
362 *
363 * Each test is responsible for returning its results and interrupt
364 * execution. At the end, boolean true (user needs to be created) will be
365 * returned if no test has interrupted that.
366 *
367 * Here it's the logic applied, keep it updated:
368 *
369 * If restoring users from same site backup:
370 * 1A - Normal check: If match by id and username and mnethost => ok, return target user
371 * 1B - Handle users deleted in DB and "alive" in backup file:
372 * If match by id and mnethost and user is deleted in DB and
373 * (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user
374 * 1C - Handle users deleted in backup file and "alive" in DB:
375 * If match by id and mnethost and user is deleted in backup file
376 * and match by email = email_without_time(backup_email) => ok, return target user
377 * 1D - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false
378 * 1E - None of the above, return true => User needs to be created
379 *
380 * if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination):
381 * 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user
382 * 2B - Handle users deleted in DB and "alive" in backup file:
383 * 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
384 * (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
385 * 2B2 - If match by mnethost and user is deleted in DB and
386 * username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
387 * (to cover situations were md5(username) wasn't implemented on delete we requiere both)
388 * 2C - Handle users deleted in backup file and "alive" in DB:
389 * If match mnethost and user is deleted in backup file
390 * and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
391 * 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
392 * 2E - None of the above, return true => User needs to be created
393 *
394 * Note: for DB deleted users email is stored in username field, hence we
395 * are looking there for emails. See delete_user()
396 * Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
397 * hence we are looking there for usernames if not empty. See delete_user()
398 */
399 protected static function precheck_user($user, $samesite) {
400 global $CFG, $DB;
401
402 // Handle checks from same site backups
403 if ($samesite && empty($CFG->forcedifferentsitecheckingusersonrestore)) {
404
405 // 1A - If match by id and username and mnethost => ok, return target user
406 if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
407 return $rec; // Matching user found, return it
408 }
409
410 // 1B - Handle users deleted in DB and "alive" in backup file
411 // Note: for DB deleted users email is stored in username field, hence we
412 // are looking there for emails. See delete_user()
413 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
414 // hence we are looking there for usernames if not empty. See delete_user()
415 // If match by id and mnethost and user is deleted in DB and
416 // match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user
417 if ($rec = $DB->get_record_sql("SELECT *
418 FROM {user} u
419 WHERE id = ?
420 AND mnethostid = ?
421 AND deleted = 1
422 AND (
423 username LIKE ?
424 OR (
425 ".$DB->sql_isnotempty('user', 'email', false, false)."
426 AND email = ?
427 )
428 )",
429 array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) {
430 return $rec; // Matching user, deleted in DB found, return it
431 }
432
433 // 1C - Handle users deleted in backup file and "alive" in DB
434 // If match by id and mnethost and user is deleted in backup file
435 // and match by email = email_without_time(backup_email) => ok, return target user
436 if ($user->deleted) {
437 // Note: for DB deleted users email is stored in username field, hence we
438 // are looking there for emails. See delete_user()
439 // Trim time() from email
440 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
441 if ($rec = $DB->get_record_sql("SELECT *
442 FROM {user} u
443 WHERE id = ?
444 AND mnethostid = ?
445 AND email = ?",
446 array($user->id, $user->mnethostid, $trimemail))) {
447 return $rec; // Matching user, deleted in backup file found, return it
448 }
449 }
450
451 // 1D - If match by username and mnethost and doesn't match by id => conflict, return false
452 if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
453 if ($user->id != $rec->id) {
454 return false; // Conflict, username already exists and belongs to another id
455 }
456 }
457
458 // Handle checks from different site backups
459 } else {
460
461 // 2A - If match by username and mnethost and
462 // (email or non-zero firstaccess) => ok, return target user
463 if ($rec = $DB->get_record_sql("SELECT *
464 FROM {user} u
465 WHERE username = ?
466 AND mnethostid = ?
467 AND (
468 email = ?
469 OR (
470 firstaccess != 0
471 AND firstaccess = ?
472 )
473 )",
474 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
475 return $rec; // Matching user found, return it
476 }
477
478 // 2B - Handle users deleted in DB and "alive" in backup file
479 // Note: for DB deleted users email is stored in username field, hence we
480 // are looking there for emails. See delete_user()
481 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
482 // hence we are looking there for usernames if not empty. See delete_user()
483 // 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
484 // (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
485 if ($rec = $DB->get_record_sql("SELECT *
486 FROM {user} u
487 WHERE mnethostid = ?
488 AND deleted = 1
489 AND ".$DB->sql_isnotempty('user', 'email', false, false)."
490 AND email = ?
491 AND (
492 username LIKE ?
493 OR (
494 firstaccess != 0
495 AND firstaccess = ?
496 )
497 )",
498 array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) {
499 return $rec; // Matching user found, return it
500 }
501
502 // 2B2 - If match by mnethost and user is deleted in DB and
503 // username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
504 // (this covers situations where md5(username) wasn't being stored so we require both
505 // the email & non-zero firstaccess to match)
506 if ($rec = $DB->get_record_sql("SELECT *
507 FROM {user} u
508 WHERE mnethostid = ?
509 AND deleted = 1
510 AND username LIKE ?
511 AND firstaccess != 0
512 AND firstaccess = ?",
513 array($user->mnethostid, $user->email.'.%', $user->firstaccess))) {
514 return $rec; // Matching user found, return it
515 }
516
517 // 2C - Handle users deleted in backup file and "alive" in DB
518 // If match mnethost and user is deleted in backup file
519 // and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
520 if ($user->deleted) {
521 // Note: for DB deleted users email is stored in username field, hence we
522 // are looking there for emails. See delete_user()
523 // Trim time() from email
524 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
525 if ($rec = $DB->get_record_sql("SELECT *
526 FROM {user} u
527 WHERE mnethostid = ?
528 AND email = ?
529 AND firstaccess != 0
530 AND firstaccess = ?",
531 array($user->mnethostid, $trimemail, $user->firstaccess))) {
532 return $rec; // Matching user, deleted in backup file found, return it
533 }
534 }
535
536 // 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
537 if ($rec = $DB->get_record_sql("SELECT *
538 FROM {user} u
539 WHERE username = ?
540 AND mnethostid = ?
541 AND NOT (
542 email = ?
543 OR (
544 firstaccess != 0
545 AND firstaccess = ?
546 )
547 )",
548 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
549 return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess)
550 }
551 }
552
553 // Arrived here, return true as the user will need to be created and no
554 // conflicts have been found in the logic above. This covers:
555 // 1E - else => user needs to be created, return true
556 // 2E - else => user needs to be created, return true
557 return true;
558 }
559
560 /**
561 * Check all the included users, deciding the action to perform
562 * for each one (mapping / creation) and returning one array
563 * of problems in case something is wrong (lack of permissions,
564 * conficts)
565 */
566 public static function precheck_included_users($restoreid, $courseid, $userid, $samesite) {
567 global $CFG, $DB;
568
569 // To return any problem found
570 $problems = array();
571
572 // We are going to map mnethostid, so load all the available ones
573 $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id');
574
575 // Calculate the context we are going to use for capability checking
576 $context = get_context_instance(CONTEXT_COURSE, $courseid);
577
578 // Calculate if we have perms to create users, by checking:
579 // to 'moodle/restore:createuser' and 'moodle/restore:userinfo'
580 // and also observe $CFG->disableusercreationonrestore
581 $cancreateuser = false;
582 if (has_capability('moodle/restore:createuser', $context, $userid) and
583 has_capability('moodle/restore:userinfo', $context, $userid) and
584 empty($CFG->disableusercreationonrestore)) { // Can create users
585
586 $cancreateuser = true;
587 }
588
589 // Iterate over all the included users
590 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user'), '', 'itemid');
591 foreach ($rs as $recuser) {
592 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
593
594 // Find the correct mnethostid for user before performing any further check
595 if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
596 $user->mnethostid = $CFG->mnet_localhost_id;
597 } else {
598 // fast url-to-id lookups
599 if (isset($mnethosts[$user->mnethosturl])) {
600 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
601 } else {
602 $user->mnethostid = $CFG->mnet_localhost_id;
603 }
604 }
605
606 // Now, precheck that user and, based on returned results, annotate action/problem
607 $usercheck = self::precheck_user($user, $samesite);
608
609 if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to
610 // Annotate it, for later process. Set newitemid to mapping user->id
611 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $usercheck->id);
612
613 } else if ($usercheck === false) { // Found conflict, report it as problem
614 $problems[] = get_string('restoreuserconflict', '', $user->username);
615
616 } else if ($usercheck === true) { // User needs to be created, check if we are able
617 if ($cancreateuser) { // Can create user, set newitemid to 0 so will be created later
618 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, 0, null, (array)$user);
619
620 } else { // Cannot create user, report it as problem
621 $problems[] = get_string('restorecannotcreateuser', '', $user->username);
622 }
623
624 } else { // Shouldn't arrive here ever, something is for sure wrong. Exception
625 throw new restore_dbops_exception('restore_error_processing_user', $user->username);
626 }
627 }
628 $rs->close();
629 return $problems;
630 }
631
632 /**
633 * Process the needed users in order to create / map them
634 *
635 * Just wrap over precheck_included_users(), returning
636 * exception if any problem is found or performing the
637 * required user creations if needed
638 */
639 public static function process_included_users($restoreid, $courseid, $userid, $samesite) {
640 global $DB;
641
642 // Just let precheck_included_users() to do all the hard work
643 $problems = self::precheck_included_users($restoreid, $courseid, $userid, $samesite);
644
645 // With problems, throw exception, shouldn't happen if prechecks were originally
646 // executed, so be radical here.
647 if (!empty($problems)) {
648 throw new restore_dbops_exception('restore_problems_processing_users', null, implode(', ', $problems));
649 }
482aac65
EL
650 }
651
652
653 public static function set_backup_ids_record($restoreid, $itemname, $itemid, $newitemid = 0, $parentitemid = null, $info = null) {
654 global $DB;
655
656 // Build the basic (mandatory) record info
657 $record = array(
658 'backupid' => $restoreid,
659 'itemname' => $itemname,
660 'itemid' => $itemid
661 );
662 // Build conditionally the extra record info
663 $extrarecord = array();
664 if ($newitemid != 0) {
665 $extrarecord['newitemid'] = $newitemid;
666 }
667 if ($parentitemid != null) {
668 $extrarecord['parentitemid'] = $parentitemid;
669 }
670 if ($info != null) {
671 $extrarecord['info'] = base64_encode(serialize($info));
672 }
673
674 // TODO: Analyze if some static (and limited) cache by the 3 params could save us a bunch of get_record() calls
675 // Note: Sure it will! And also will improve getter
676 if (!$dbrec = $DB->get_record('backup_ids_temp', $record)) { // Need to insert the complete record
677 $DB->insert_record('backup_ids_temp', array_merge($record, $extrarecord));
678
679 } else { // Need to update the extra record info if there is something to
680 if (!empty($extrarecord)) {
681 $extrarecord['id'] = $dbrec->id;
682 $DB->update_record('backup_ids_temp', $extrarecord);
683 }
684 }
685 }
686
687 public static function get_backup_ids_record($restoreid, $itemname, $itemid) {
688 global $DB;
689
690 // Build the basic (mandatory) record info to look for
691 $record = array(
692 'backupid' => $restoreid,
693 'itemname' => $itemname,
694 'itemid' => $itemid
695 );
696 // TODO: Analyze if some static (and limited) cache by the 3 params could save us a bunch of get_record() calls
697 if ($dbrec = $DB->get_record('backup_ids_temp', $record)) {
698 if ($dbrec->info != null) {
699 $dbrec->info = unserialize(base64_decode($dbrec->info));
700 }
701 }
702 return $dbrec;
703 }
704}
fbc2778d
EL
705
706/*
707 * Exception class used by all the @dbops stuff
708 */
709class restore_dbops_exception extends backup_exception {
710
711 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
712 parent::__construct($errorcode, 'error', '', $a, null, $debuginfo);
713 }
714}