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