MDL-21432 backup - allow restore of only one itemid (instead of the whole itemname)
[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) {
4a15bb76 46 if (!$task->get_setting_value('blocks')) { // Blocks not included, continue
482aac65
EL
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 */
f2745cbe 241 public static function send_files_to_pool($basepath, $restoreid, $component, $filearea, $oldcontextid, $dfltuserid, $itemname = null, $olditemid = null) {
2df0f295
EL
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) {
70c1ad58 255 $sql = 'SELECT contextid, component, filearea, itemid, itemid AS newitemid, info
b8bb45b0 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);
f2745cbe
EL
276 if ($olditemid !== null) { // Just process ONE olditemid intead of the whole itemname
277 $sql .= ' AND i.itemid = ?';
278 $params[] = $olditemid;
279 }
2df0f295
EL
280 }
281
2df0f295
EL
282 $fs = get_file_storage(); // Get moodle file storage
283 $basepath = $basepath . '/files/';// Get backup file pool base
71a50b13 284 $rs = $DB->get_recordset_sql($sql, $params);
2df0f295 285 foreach ($rs as $rec) {
b8bb45b0 286 $file = (object)unserialize(base64_decode($rec->info));
2df0f295
EL
287 // ignore root dirs (they are created automatically)
288 if ($file->filepath == '/' && $file->filename == '.') {
289 continue;
290 }
84cdf7de
EL
291 // set the best possible user
292 $mappeduser = self::get_backup_ids_record($restoreid, 'user', $file->userid);
293 $file->userid = !empty($mappeduser) ? $mappeduser->newitemid : $dfltuserid;
2df0f295
EL
294 // dir found (and not root one), let's create if
295 if ($file->filename == '.') {
84cdf7de 296 $fs->create_directory($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->userid);
2df0f295
EL
297 continue;
298 }
299 // arrived here, file found
300 // Find file in backup pool
301 $backuppath = $basepath . backup_file_manager::get_content_file_location($file->contenthash);
302 if (!file_exists($backuppath)) {
303 throw new restore_dbops_exception('file_not_found_in_pool', $file);
304 }
305 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
306 $file_record = array(
307 'contextid' => $newcontextid,
308 'component' => $component,
309 'filearea' => $filearea,
310 'itemid' => $rec->newitemid,
311 'filepath' => $file->filepath,
312 'filename' => $file->filename,
313 'timecreated' => $file->timecreated,
314 'timemodified'=> $file->timemodified,
84cdf7de 315 'userid' => $file->userid,
2df0f295 316 'author' => $file->author,
84cdf7de
EL
317 'license' => $file->license,
318 'sortorder' => $file->sortorder);
2df0f295
EL
319 $fs->create_file_from_pathname($file_record, $backuppath);
320 }
321 }
322 $rs->close();
323 }
324
482aac65
EL
325 /**
326 * Given one restoreid, create in DB all the users present
327 * in backup_ids having newitemid = 0, as far as
328 * precheck_included_users() have left them there
329 * ready to be created. Also, annotate their newids
330 * once created for later reference
331 */
2df0f295 332 public static function create_included_users($basepath, $restoreid, $userfiles) {
482aac65
EL
333 global $CFG, $DB;
334
335 $authcache = array(); // Cache to get some bits from authentication plugins
336 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search later
337 $themes = get_list_of_themes(); // Get themes for quick search later
338
339 // Iterate over all the included users with newitemid = 0, have to create them
340 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid');
341 foreach ($rs as $recuser) {
342 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
343
344 // if user lang doesn't exist here, use site default
345 if (!array_key_exists($user->lang, $languages)) {
346 $user->lang = $CFG->lang;
347 }
348
349 // if user theme isn't available on target site or they are disabled, reset theme
350 if (!empty($user->theme)) {
351 if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) {
352 $user->theme = '';
353 }
354 }
355
356 // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id
357 // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual
358 if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
359 // Respect registerauth
360 if ($CFG->registerauth == 'email') {
361 $user->auth = 'email';
362 } else {
363 $user->auth = 'manual';
364 }
365 }
366 unset($user->mnethosturl); // Not needed anymore
367
368 // Disable pictures based on global setting
369 if (!empty($CFG->disableuserimages)) {
370 $user->picture = 0;
371 }
372
373 // We need to analyse the AUTH field to recode it:
374 // - if the auth isn't enabled in target site, $CFG->registerauth will decide
375 // - finally, if the auth resulting isn't enabled, default to 'manual'
376 if (!is_enabled_auth($user->auth)) {
377 if ($CFG->registerauth == 'email') {
378 $user->auth = 'email';
379 } else {
380 $user->auth = 'manual';
381 }
382 }
383 if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled
384 $user->auth = 'manual';
385 }
386
387 // Now that we know the auth method, for users to be created without pass
388 // if password handling is internal and reset password is available
389 // we set the password to "restored" (plain text), so the login process
390 // will know how to handle that situation in order to allow the user to
391 // recover the password. MDL-20846
392 if (empty($user->password)) { // Only if restore comes without password
393 if (!array_key_exists($user->auth, $authcache)) { // Not in cache
394 $userauth = new stdClass();
395 $authplugin = get_auth_plugin($user->auth);
396 $userauth->preventpassindb = $authplugin->prevent_local_passwords();
397 $userauth->isinternal = $authplugin->is_internal();
398 $userauth->canresetpwd = $authplugin->can_reset_password();
399 $authcache[$user->auth] = $userauth;
400 } else {
401 $userauth = $authcache[$user->auth]; // Get from cache
402 }
403
404 // Most external plugins do not store passwords locally
405 if (!empty($userauth->preventpassindb)) {
406 $user->password = 'not cached';
407
408 // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
409 } else if ($userauth->isinternal and $userauth->canresetpwd) {
410 $user->password = 'restored';
411 }
412 }
413
414 // Creating new user, we must reset the policyagreed always
415 $user->policyagreed = 0;
416
417 // Set time created if empty
418 if (empty($user->timecreated)) {
419 $user->timecreated = time();
420 }
421
422 // Done, let's create the user and annotate its id
423 $newuserid = $DB->insert_record('user', $user);
424 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid);
425 // Let's create the user context and annotate it (we need it for sure at least for files)
426 $newuserctxid = get_context_instance(CONTEXT_USER, $newuserid)->id;
427 self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid);
428
429 // Process custom fields
430 if (isset($user->custom_fields)) { // if present in backup
431 foreach($user->custom_fields['custom_field'] as $udata) {
432 $udata = (object)$udata;
433 // If the profile field has data and the profile shortname-datatype is defined in server
434 if ($udata->field_data) {
435 if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) {
436 /// Insert the user_custom_profile_field
437 $rec = new object();
438 $rec->userid = $newuserid;
439 $rec->fieldid = $field->id;
440 $rec->data = $udata->field_data;
441 $DB->insert_record('user_info_data', $rec);
442 }
443 }
444 }
445 }
446
447 // Process tags
448 if (!empty($CFG->usetags) && isset($user->tags)) { // if enabled in server and present in backup
449 $tags = array();
450 foreach($user->tags['tag'] as $usertag) {
451 $usertag = (object)$usertag;
452 $tags[] = $usertag->rawname;
453 }
454 tag_set('user', $newuserid, $tags);
455 }
456
457 // Process preferences
458 if (isset($user->preferences)) { // if present in backup
2df0f295 459 foreach($user->preferences['preference'] as $preference) {
482aac65
EL
460 $preference = (object)$preference;
461 // Prepare the record and insert it
462 $preference->userid = $newuserid;
463 $status = $DB->insert_record('user_preferences', $preference);
464 }
465 }
466
2df0f295
EL
467 // Create user files in pool (profile, icon, private) by context
468 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon', $recuser->parentitemid);
469 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile', $recuser->parentitemid);
470 if ($userfiles) { // private files only if enabled in settings
471 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'private', $recuser->parentitemid);
472 }
473
482aac65
EL
474 }
475 $rs->close();
476 }
477
478 /**
479 * Given one user object (from backup file), perform all the neccesary
480 * checks is order to decide how that user will be handled on restore.
481 *
482 * Note the function requires $user->mnethostid to be already calculated
483 * so it's caller responsibility to set it
484 *
485 * This function is used both by @restore_precheck_users() and
486 * @restore_create_users() to get consistent results in both places
487 *
488 * It returns:
489 * - one user object (from DB), if match has been found and user will be remapped
490 * - boolean true if the user needs to be created
491 * - boolean false if some conflict happened and the user cannot be handled
492 *
493 * Each test is responsible for returning its results and interrupt
494 * execution. At the end, boolean true (user needs to be created) will be
495 * returned if no test has interrupted that.
496 *
497 * Here it's the logic applied, keep it updated:
498 *
499 * If restoring users from same site backup:
500 * 1A - Normal check: If match by id and username and mnethost => ok, return target user
501 * 1B - Handle users deleted in DB and "alive" in backup file:
502 * If match by id and mnethost and user is deleted in DB and
503 * (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user
504 * 1C - Handle users deleted in backup file and "alive" in DB:
505 * If match by id and mnethost and user is deleted in backup file
506 * and match by email = email_without_time(backup_email) => ok, return target user
507 * 1D - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false
508 * 1E - None of the above, return true => User needs to be created
509 *
510 * if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination):
511 * 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user
512 * 2B - Handle users deleted in DB and "alive" in backup file:
513 * 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
514 * (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
515 * 2B2 - If match by mnethost and user is deleted in DB and
516 * username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
517 * (to cover situations were md5(username) wasn't implemented on delete we requiere both)
518 * 2C - Handle users deleted in backup file and "alive" in DB:
519 * If match mnethost and user is deleted in backup file
520 * and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
521 * 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
522 * 2E - None of the above, return true => User needs to be created
523 *
524 * Note: for DB deleted users email is stored in username field, hence we
525 * are looking there for emails. See delete_user()
526 * Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
527 * hence we are looking there for usernames if not empty. See delete_user()
528 */
529 protected static function precheck_user($user, $samesite) {
530 global $CFG, $DB;
531
532 // Handle checks from same site backups
533 if ($samesite && empty($CFG->forcedifferentsitecheckingusersonrestore)) {
534
535 // 1A - If match by id and username and mnethost => ok, return target user
536 if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
537 return $rec; // Matching user found, return it
538 }
539
540 // 1B - Handle users deleted in DB and "alive" in backup file
541 // Note: for DB deleted users email is stored in username field, hence we
542 // are looking there for emails. See delete_user()
543 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
544 // hence we are looking there for usernames if not empty. See delete_user()
545 // If match by id and mnethost and user is deleted in DB and
546 // match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user
547 if ($rec = $DB->get_record_sql("SELECT *
548 FROM {user} u
549 WHERE id = ?
550 AND mnethostid = ?
551 AND deleted = 1
552 AND (
553 username LIKE ?
554 OR (
555 ".$DB->sql_isnotempty('user', 'email', false, false)."
556 AND email = ?
557 )
558 )",
559 array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) {
560 return $rec; // Matching user, deleted in DB found, return it
561 }
562
563 // 1C - Handle users deleted in backup file and "alive" in DB
564 // If match by id and mnethost and user is deleted in backup file
565 // and match by email = email_without_time(backup_email) => ok, return target user
566 if ($user->deleted) {
567 // Note: for DB deleted users email is stored in username field, hence we
568 // are looking there for emails. See delete_user()
569 // Trim time() from email
570 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
571 if ($rec = $DB->get_record_sql("SELECT *
572 FROM {user} u
573 WHERE id = ?
574 AND mnethostid = ?
575 AND email = ?",
576 array($user->id, $user->mnethostid, $trimemail))) {
577 return $rec; // Matching user, deleted in backup file found, return it
578 }
579 }
580
581 // 1D - If match by username and mnethost and doesn't match by id => conflict, return false
582 if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
583 if ($user->id != $rec->id) {
584 return false; // Conflict, username already exists and belongs to another id
585 }
586 }
587
588 // Handle checks from different site backups
589 } else {
590
591 // 2A - If match by username and mnethost and
592 // (email or non-zero firstaccess) => ok, return target user
593 if ($rec = $DB->get_record_sql("SELECT *
594 FROM {user} u
595 WHERE username = ?
596 AND mnethostid = ?
597 AND (
598 email = ?
599 OR (
600 firstaccess != 0
601 AND firstaccess = ?
602 )
603 )",
604 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
605 return $rec; // Matching user found, return it
606 }
607
608 // 2B - Handle users deleted in DB and "alive" in backup file
609 // Note: for DB deleted users email is stored in username field, hence we
610 // are looking there for emails. See delete_user()
611 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
612 // hence we are looking there for usernames if not empty. See delete_user()
613 // 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
614 // (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
615 if ($rec = $DB->get_record_sql("SELECT *
616 FROM {user} u
617 WHERE mnethostid = ?
618 AND deleted = 1
619 AND ".$DB->sql_isnotempty('user', 'email', false, false)."
620 AND email = ?
621 AND (
622 username LIKE ?
623 OR (
624 firstaccess != 0
625 AND firstaccess = ?
626 )
627 )",
628 array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) {
629 return $rec; // Matching user found, return it
630 }
631
632 // 2B2 - If match by mnethost and user is deleted in DB and
633 // username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
634 // (this covers situations where md5(username) wasn't being stored so we require both
635 // the email & non-zero firstaccess to match)
636 if ($rec = $DB->get_record_sql("SELECT *
637 FROM {user} u
638 WHERE mnethostid = ?
639 AND deleted = 1
640 AND username LIKE ?
641 AND firstaccess != 0
642 AND firstaccess = ?",
643 array($user->mnethostid, $user->email.'.%', $user->firstaccess))) {
644 return $rec; // Matching user found, return it
645 }
646
647 // 2C - Handle users deleted in backup file and "alive" in DB
648 // If match mnethost and user is deleted in backup file
649 // and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
650 if ($user->deleted) {
651 // Note: for DB deleted users email is stored in username field, hence we
652 // are looking there for emails. See delete_user()
653 // Trim time() from email
654 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
655 if ($rec = $DB->get_record_sql("SELECT *
656 FROM {user} u
657 WHERE mnethostid = ?
658 AND email = ?
659 AND firstaccess != 0
660 AND firstaccess = ?",
661 array($user->mnethostid, $trimemail, $user->firstaccess))) {
662 return $rec; // Matching user, deleted in backup file found, return it
663 }
664 }
665
666 // 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
667 if ($rec = $DB->get_record_sql("SELECT *
668 FROM {user} u
669 WHERE username = ?
670 AND mnethostid = ?
671 AND NOT (
672 email = ?
673 OR (
674 firstaccess != 0
675 AND firstaccess = ?
676 )
677 )",
678 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
679 return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess)
680 }
681 }
682
683 // Arrived here, return true as the user will need to be created and no
684 // conflicts have been found in the logic above. This covers:
685 // 1E - else => user needs to be created, return true
686 // 2E - else => user needs to be created, return true
687 return true;
688 }
689
690 /**
691 * Check all the included users, deciding the action to perform
692 * for each one (mapping / creation) and returning one array
693 * of problems in case something is wrong (lack of permissions,
694 * conficts)
695 */
696 public static function precheck_included_users($restoreid, $courseid, $userid, $samesite) {
697 global $CFG, $DB;
698
699 // To return any problem found
700 $problems = array();
701
702 // We are going to map mnethostid, so load all the available ones
703 $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id');
704
705 // Calculate the context we are going to use for capability checking
706 $context = get_context_instance(CONTEXT_COURSE, $courseid);
707
708 // Calculate if we have perms to create users, by checking:
709 // to 'moodle/restore:createuser' and 'moodle/restore:userinfo'
710 // and also observe $CFG->disableusercreationonrestore
711 $cancreateuser = false;
712 if (has_capability('moodle/restore:createuser', $context, $userid) and
713 has_capability('moodle/restore:userinfo', $context, $userid) and
714 empty($CFG->disableusercreationonrestore)) { // Can create users
715
716 $cancreateuser = true;
717 }
718
719 // Iterate over all the included users
720 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user'), '', 'itemid');
721 foreach ($rs as $recuser) {
722 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
723
724 // Find the correct mnethostid for user before performing any further check
725 if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
726 $user->mnethostid = $CFG->mnet_localhost_id;
727 } else {
728 // fast url-to-id lookups
729 if (isset($mnethosts[$user->mnethosturl])) {
730 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
731 } else {
732 $user->mnethostid = $CFG->mnet_localhost_id;
733 }
734 }
735
736 // Now, precheck that user and, based on returned results, annotate action/problem
737 $usercheck = self::precheck_user($user, $samesite);
738
739 if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to
740 // Annotate it, for later process. Set newitemid to mapping user->id
741 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $usercheck->id);
742
743 } else if ($usercheck === false) { // Found conflict, report it as problem
744 $problems[] = get_string('restoreuserconflict', '', $user->username);
745
746 } else if ($usercheck === true) { // User needs to be created, check if we are able
747 if ($cancreateuser) { // Can create user, set newitemid to 0 so will be created later
748 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, 0, null, (array)$user);
749
750 } else { // Cannot create user, report it as problem
751 $problems[] = get_string('restorecannotcreateuser', '', $user->username);
752 }
753
754 } else { // Shouldn't arrive here ever, something is for sure wrong. Exception
755 throw new restore_dbops_exception('restore_error_processing_user', $user->username);
756 }
757 }
758 $rs->close();
759 return $problems;
760 }
761
762 /**
763 * Process the needed users in order to create / map them
764 *
765 * Just wrap over precheck_included_users(), returning
766 * exception if any problem is found or performing the
767 * required user creations if needed
768 */
769 public static function process_included_users($restoreid, $courseid, $userid, $samesite) {
770 global $DB;
771
772 // Just let precheck_included_users() to do all the hard work
773 $problems = self::precheck_included_users($restoreid, $courseid, $userid, $samesite);
774
775 // With problems, throw exception, shouldn't happen if prechecks were originally
776 // executed, so be radical here.
777 if (!empty($problems)) {
778 throw new restore_dbops_exception('restore_problems_processing_users', null, implode(', ', $problems));
779 }
482aac65
EL
780 }
781
b8bb45b0
EL
782 public static function set_backup_files_record($restoreid, $filerec) {
783 global $DB;
784
785 $filerec->info = base64_encode(serialize($filerec)); // Serialize the whole rec in info
786 $filerec->backupid = $restoreid;
787 $DB->insert_record('backup_files_temp', $filerec);
788 }
789
482aac65
EL
790
791 public static function set_backup_ids_record($restoreid, $itemname, $itemid, $newitemid = 0, $parentitemid = null, $info = null) {
792 global $DB;
793
794 // Build the basic (mandatory) record info
795 $record = array(
796 'backupid' => $restoreid,
797 'itemname' => $itemname,
798 'itemid' => $itemid
799 );
800 // Build conditionally the extra record info
801 $extrarecord = array();
802 if ($newitemid != 0) {
803 $extrarecord['newitemid'] = $newitemid;
804 }
805 if ($parentitemid != null) {
806 $extrarecord['parentitemid'] = $parentitemid;
807 }
808 if ($info != null) {
809 $extrarecord['info'] = base64_encode(serialize($info));
810 }
811
812 // TODO: Analyze if some static (and limited) cache by the 3 params could save us a bunch of get_record() calls
813 // Note: Sure it will! And also will improve getter
814 if (!$dbrec = $DB->get_record('backup_ids_temp', $record)) { // Need to insert the complete record
815 $DB->insert_record('backup_ids_temp', array_merge($record, $extrarecord));
816
817 } else { // Need to update the extra record info if there is something to
818 if (!empty($extrarecord)) {
819 $extrarecord['id'] = $dbrec->id;
820 $DB->update_record('backup_ids_temp', $extrarecord);
821 }
822 }
823 }
824
825 public static function get_backup_ids_record($restoreid, $itemname, $itemid) {
826 global $DB;
827
828 // Build the basic (mandatory) record info to look for
829 $record = array(
830 'backupid' => $restoreid,
831 'itemname' => $itemname,
832 'itemid' => $itemid
833 );
834 // TODO: Analyze if some static (and limited) cache by the 3 params could save us a bunch of get_record() calls
835 if ($dbrec = $DB->get_record('backup_ids_temp', $record)) {
836 if ($dbrec->info != null) {
837 $dbrec->info = unserialize(base64_decode($dbrec->info));
838 }
839 }
840 return $dbrec;
841 }
4bca307a
EL
842
843 /**
844 * Given on courseid, fullname and shortname, calculate the correct fullname/shortname to avoid dupes
845 */
846 public static function calculate_course_names($courseid, $fullname, $shortname) {
847 global $CFG, $DB;
848
849 $currentfullname = '';
850 $currentshortname = '';
851 $counter = 0;
852 // Iteratere while the name exists
853 do {
854 if ($counter) {
855 $suffixfull = ' ' . get_string('copyasnoun') . ' ' . $counter;
856 $suffixshort = '_' . $counter;
857 } else {
858 $suffixfull = '';
859 $suffixshort = '';
860 }
861 $currentfullname = $fullname.$suffixfull;
862 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; // < 100cc
863 $coursefull = $DB->get_record_select('course', 'fullname = ? AND id != ?', array($currentfullname, $courseid));
864 $courseshort = $DB->get_record_select('course', 'shortname = ? AND id != ?', array($currentshortname, $courseid));
865 $counter++;
866 } while ($coursefull || $courseshort);
867
868 // Return results
869 return array($currentfullname, $currentshortname);
870 }
871
872 /**
873 * For the target course context, put as many custom role names as possible
874 */
875 public static function set_course_role_names($restoreid, $courseid) {
876 global $DB;
877
878 // Get the course context
879 $coursectx = get_context_instance(CONTEXT_COURSE, $courseid);
880 // Get all the mapped roles we have
881 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid');
882 foreach ($rs as $recrole) {
883 // Get the complete temp_ids record
884 $role = (object)self::get_backup_ids_record($restoreid, 'role', $recrole->itemid);
024c288d
EL
885 // If it's one mapped role and we have one name for it
886 if (!empty($role->newitemid) && !empty($role->info['nameincourse'])) {
4bca307a
EL
887 // If role name doesn't exist, add it
888 $rolename = new stdclass();
889 $rolename->roleid = $role->newitemid;
890 $rolename->contextid = $coursectx->id;
891 if (!$DB->record_exists('role_names', (array)$rolename)) {
892 $rolename->name = $role->info['nameincourse'];
893 $DB->insert_record('role_names', $rolename);
894 }
895 }
896 }
897 $rs->close();
898 }
785d6603 899
3acc9b81
SH
900 /**
901 * Creates a skeleton record within the database using the passed parameters
902 * and returns the new course id.
903 *
904 * @global moodle_database $DB
905 * @param string $fullname
906 * @param string $shortname
907 * @param int $categoryid
908 * @return int The new course id
909 */
785d6603
SH
910 public static function create_new_course($fullname, $shortname, $categoryid) {
911 global $DB;
912 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
913
914 $course = new stdClass;
915 $course->fullname = $fullname;
916 $course->shortname = $shortname;
917 $course->category = $category->id;
918 $course->sortorder = 0;
919 $course->timecreated = time();
920 $course->timemodified = $course->timecreated;
921 $course->visible = $category->visible;
922
923 return $DB->insert_record('course', $course);
924 }
925
3acc9b81
SH
926 /**
927 * Deletes all of the content associated with the given course (courseid)
928 * @param int $courseid
929 * @return bool True for success
930 */
785d6603 931 public static function delete_course_content($courseid) {
3acc9b81 932 return remove_course_contents($courseid, false);
785d6603 933 }
482aac65 934}
fbc2778d
EL
935
936/*
937 * Exception class used by all the @dbops stuff
938 */
939class restore_dbops_exception extends backup_exception {
940
941 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
942 parent::__construct($errorcode, 'error', '', $a, null, $debuginfo);
943 }
944}