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