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