MDL-31484 backup - repeated restores with anonymised users now works correctly
[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 30abstract class restore_dbops {
e7b24943
RT
31 /**
32 * Keep cache of backup records.
33 * @var array
34 * @todo MDL-25290 static should be replaced with MUC code.
35 */
36 private static $backupidscache = array();
37 /**
38 * Keep track of backup ids which are cached.
39 * @var array
40 * @todo MDL-25290 static should be replaced with MUC code.
41 */
42 private static $backupidsexist = array();
43 /**
44 * Count is expensive, so manually keeping track of
45 * backupidscache, to avoid memory issues.
46 * @var int
47 * @todo MDL-25290 static should be replaced with MUC code.
48 */
49 private static $backupidscachesize = 2048;
50 /**
51 * Count is expensive, so manually keeping track of
52 * backupidsexist, to avoid memory issues.
53 * @var int
54 * @todo MDL-25290 static should be replaced with MUC code.
55 */
56 private static $backupidsexistsize = 10240;
57 /**
58 * Slice backupids cache to add more data.
59 * @var int
60 * @todo MDL-25290 static should be replaced with MUC code.
61 */
62 private static $backupidsslice = 512;
482aac65
EL
63
64 /**
648a575e
EL
65 * Return one array containing all the tasks that have been included
66 * in the restore process. Note that these tasks aren't built (they
67 * haven't steps nor ids data available)
482aac65 68 */
648a575e 69 public static function get_included_tasks($restoreid) {
482aac65
EL
70 $rc = restore_controller_dbops::load_controller($restoreid);
71 $tasks = $rc->get_plan()->get_tasks();
648a575e
EL
72 $includedtasks = array();
73 foreach ($tasks as $key => $task) {
482aac65
EL
74 // Calculate if the task is being included
75 $included = false;
76 // blocks, based in blocks setting and parent activity/course
77 if ($task instanceof restore_block_task) {
4a15bb76 78 if (!$task->get_setting_value('blocks')) { // Blocks not included, continue
482aac65
EL
79 continue;
80 }
81 $parent = basename(dirname(dirname($task->get_taskbasepath())));
82 if ($parent == 'course') { // Parent is course, always included if present
83 $included = true;
84
85 } else { // Look for activity_included setting
86 $included = $task->get_setting_value($parent . '_included');
87 }
88
89 // ativities, based on included setting
90 } else if ($task instanceof restore_activity_task) {
91 $included = $task->get_setting_value('included');
92
93 // sections, based on included setting
94 } else if ($task instanceof restore_section_task) {
95 $included = $task->get_setting_value('included');
96
97 // course always included if present
98 } else if ($task instanceof restore_course_task) {
99 $included = true;
100 }
101
648a575e 102 // If included, add it
482aac65 103 if ($included) {
648a575e 104 $includedtasks[] = $task;
482aac65
EL
105 }
106 }
648a575e 107 return $includedtasks;
482aac65
EL
108 }
109
110 /**
111 * Load one inforef.xml file to backup_ids table for future reference
112 */
113 public static function load_inforef_to_tempids($restoreid, $inforeffile) {
114
115 if (!file_exists($inforeffile)) { // Shouldn't happen ever, but...
116 throw new backup_helper_exception('missing_inforef_xml_file', $inforeffile);
117 }
118 // Let's parse, custom processor will do its work, sending info to DB
119 $xmlparser = new progressive_parser();
120 $xmlparser->set_file($inforeffile);
121 $xmlprocessor = new restore_inforef_parser_processor($restoreid);
122 $xmlparser->set_processor($xmlprocessor);
123 $xmlparser->process();
124 }
125
71a50b13
EL
126 /**
127 * Load the needed role.xml file to backup_ids table for future reference
128 */
129 public static function load_roles_to_tempids($restoreid, $rolesfile) {
130
131 if (!file_exists($rolesfile)) { // Shouldn't happen ever, but...
132 throw new backup_helper_exception('missing_roles_xml_file', $rolesfile);
133 }
134 // Let's parse, custom processor will do its work, sending info to DB
135 $xmlparser = new progressive_parser();
136 $xmlparser->set_file($rolesfile);
137 $xmlprocessor = new restore_roles_parser_processor($restoreid);
138 $xmlparser->set_processor($xmlprocessor);
139 $xmlparser->process();
140 }
141
142 /**
143 * Precheck the loaded roles, return empty array if everything is ok, and
144 * array with 'errors', 'warnings' elements (suitable to be used by restore_prechecks)
8d4e41f4
EL
145 * with any problem found. At the same time, store all the mapping into backup_ids_temp
146 * and also put the information into $rolemappings (controller->info), so it can be reworked later by
147 * post-precheck stages while at the same time accept modified info in the same object coming from UI
71a50b13 148 */
8d4e41f4
EL
149 public static function precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings) {
150 global $DB;
151
152 $problems = array(); // To store warnings/errors
153
154 // Get loaded roles from backup_ids
155 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid');
156 foreach ($rs as $recrole) {
157 // If the rolemappings->modified flag is set, that means that we are coming from
158 // manually modified mappings (by UI), so accept those mappings an put them to backup_ids
159 if ($rolemappings->modified) {
160 $target = $rolemappings->mappings[$recrole->itemid]->targetroleid;
161 self::set_backup_ids_record($restoreid, 'role', $recrole->itemid, $target);
162
163 // Else, we haven't any info coming from UI, let's calculate the mappings, matching
164 // in multiple ways and checking permissions. Note mapping to 0 means "skip"
165 } else {
166 $role = (object)self::get_backup_ids_record($restoreid, 'role', $recrole->itemid)->info;
167 $match = self::get_best_assignable_role($role, $courseid, $userid, $samesite);
168 // Send match to backup_ids
169 self::set_backup_ids_record($restoreid, 'role', $recrole->itemid, $match);
170 // Build the rolemappings element for controller
171 unset($role->id);
172 unset($role->nameincourse);
173 unset($role->nameincourse);
174 $role->targetroleid = $match;
175 $rolemappings->mappings[$recrole->itemid] = $role;
176 // Prepare warning if no match found
177 if (!$match) {
178 $problems['warnings'][] = get_string('cannotfindassignablerole', 'backup', $role->name);
179 }
180 }
181 }
182 $rs->close();
183 return $problems;
184 }
185
e7b24943
RT
186 /**
187 * Return cached backup id's
188 *
189 * @param int $restoreid id of backup
190 * @param string $itemname name of the item
191 * @param int $itemid id of item
192 * @return array backup id's
193 * @todo MDL-25290 replace static backupids* with MUC code
194 */
7f98b12f
TL
195 protected static function get_backup_ids_cached($restoreid, $itemname, $itemid) {
196 global $DB;
197
198 $key = "$itemid $itemname $restoreid";
199
e7b24943
RT
200 // If record exists in cache then return.
201 if (isset(self::$backupidsexist[$key]) && isset(self::$backupidscache[$key])) {
202 // Return a copy of cached data, to avoid any alterations in cached data.
203 return clone self::$backupidscache[$key];
7f98b12f
TL
204 }
205
e7b24943
RT
206 // Clean cache, if it's full.
207 if (self::$backupidscachesize <= 0) {
208 // Remove some records, to keep memory in limit.
209 self::$backupidscache = array_slice(self::$backupidscache, self::$backupidsslice, null, true);
210 self::$backupidscachesize = self::$backupidscachesize + self::$backupidsslice;
211 }
212 if (self::$backupidsexistsize <= 0) {
213 self::$backupidsexist = array_slice(self::$backupidsexist, self::$backupidsslice, null, true);
214 self::$backupidsexistsize = self::$backupidsexistsize + self::$backupidsslice;
7f98b12f
TL
215 }
216
e7b24943 217 // Retrive record from database.
7f98b12f
TL
218 $record = array(
219 'backupid' => $restoreid,
220 'itemname' => $itemname,
221 'itemid' => $itemid
222 );
e7b24943
RT
223 if ($dbrec = $DB->get_record('backup_ids_temp', $record)) {
224 self::$backupidsexist[$key] = $dbrec->id;
225 self::$backupidscache[$key] = $dbrec;
226 self::$backupidscachesize--;
227 self::$backupidsexistsize--;
228 return $dbrec;
229 } else {
230 return false;
7f98b12f 231 }
7f98b12f
TL
232 }
233
e7b24943
RT
234 /**
235 * Cache backup ids'
236 *
237 * @param int $restoreid id of backup
238 * @param string $itemname name of the item
239 * @param int $itemid id of item
240 * @param array $extrarecord extra record which needs to be updated
241 * @return void
242 * @todo MDL-25290 replace static BACKUP_IDS_* with MUC code
243 */
7f98b12f
TL
244 protected static function set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord) {
245 global $DB;
246
247 $key = "$itemid $itemname $restoreid";
248
e7b24943
RT
249 $record = array(
250 'backupid' => $restoreid,
251 'itemname' => $itemname,
252 'itemid' => $itemid,
253 );
254
255 // If record is not cached then add one.
256 if (!isset(self::$backupidsexist[$key])) {
257 // If we have this record in db, then just update this.
258 if ($existingrecord = $DB->get_record('backup_ids_temp', $record)) {
259 self::$backupidsexist[$key] = $existingrecord->id;
260 self::$backupidsexistsize--;
261 self::update_backup_cached_record($record, $extrarecord, $key, $existingrecord);
262 } else {
263 // Add new record to cache and db.
264 $recorddefault = array (
265 'newitemid' => 0,
266 'parentitemid' => null,
267 'info' => null);
268 $record = array_merge($record, $recorddefault, $extrarecord);
269 $record['id'] = $DB->insert_record('backup_ids_temp', $record);
270 self::$backupidsexist[$key] = $record['id'];
271 self::$backupidsexistsize--;
272 if (self::$backupidscachesize > 0) {
273 // Cache new records if we haven't got many yet.
274 self::$backupidscache[$key] = (object) $record;
275 self::$backupidscachesize--;
276 }
7f98b12f
TL
277 }
278 } else {
e7b24943
RT
279 self::update_backup_cached_record($record, $extrarecord, $key);
280 }
281 }
282
283 /**
284 * Updates existing backup record
285 *
286 * @param array $record record which needs to be updated
287 * @param array $extrarecord extra record which needs to be updated
288 * @param string $key unique key which is used to identify cached record
289 * @param stdClass $existingrecord (optional) existing record
290 */
291 protected static function update_backup_cached_record($record, $extrarecord, $key, $existingrecord = null) {
292 global $DB;
293 // Update only if extrarecord is not empty.
294 if (!empty($extrarecord)) {
295 $extrarecord['id'] = self::$backupidsexist[$key];
296 $DB->update_record('backup_ids_temp', $extrarecord);
297 // Update existing cache or add new record to cache.
298 if (isset(self::$backupidscache[$key])) {
299 $record = array_merge((array)self::$backupidscache[$key], $extrarecord);
300 self::$backupidscache[$key] = (object) $record;
301 } else if (self::$backupidscachesize > 0) {
302 if ($existingrecord) {
303 self::$backupidscache[$key] = $existingrecord;
304 } else {
305 // Retrive record from database and cache updated records.
306 self::$backupidscache[$key] = $DB->get_record('backup_ids_temp', $record);
7f98b12f 307 }
e7b24943
RT
308 $record = array_merge((array)self::$backupidscache[$key], $extrarecord);
309 self::$backupidscache[$key] = (object) $record;
310 self::$backupidscachesize--;
7f98b12f
TL
311 }
312 }
313 }
314
f0852f47
EL
315 /**
316 * Reset the ids caches completely
317 *
318 * Any destructive operation (partial delete, truncate, drop or recreate) performed
319 * with the backup_ids table must cause the backup_ids caches to be
320 * invalidated by calling this method. See MDL-33630.
321 *
322 * Note that right now, the only operation of that type is the recreation
323 * (drop & restore) of the table that may happen once the prechecks have ended. All
324 * the rest of operations are always routed via {@link set_backup_ids_record()}, 1 by 1,
325 * keeping the caches on sync.
326 *
327 * @todo MDL-25290 static should be replaced with MUC code.
328 */
329 public static function reset_backup_ids_cached() {
330 // Reset the ids cache.
331 $cachetoadd = count(self::$backupidscache);
332 self::$backupidscache = array();
333 self::$backupidscachesize = self::$backupidscachesize + $cachetoadd;
334 // Reset the exists cache.
335 $existstoadd = count(self::$backupidsexist);
336 self::$backupidsexist = array();
337 self::$backupidsexistsize = self::$backupidsexistsize + $existstoadd;
338 }
339
8d4e41f4
EL
340 /**
341 * Given one role, as loaded from XML, perform the best possible matching against the assignable
342 * roles, using different fallback alternatives (shortname, archetype, editingteacher => teacher, defaultcourseroleid)
343 * returning the id of the best matching role or 0 if no match is found
344 */
345 protected static function get_best_assignable_role($role, $courseid, $userid, $samesite) {
346 global $CFG, $DB;
347
348 // Gather various information about roles
349 $coursectx = get_context_instance(CONTEXT_COURSE, $courseid);
350 $allroles = $DB->get_records('role');
351 $assignablerolesshortname = get_assignable_roles($coursectx, ROLENAME_SHORT, false, $userid);
352
353 // Note: under 1.9 we had one function restore_samerole() that performed one complete
354 // matching of roles (all caps) and if match was found the mapping was availabe bypassing
355 // any assignable_roles() security. IMO that was wrong and we must not allow such
356 // mappings anymore. So we have left that matching strategy out in 2.0
357
358 // Empty assignable roles, mean no match possible
359 if (empty($assignablerolesshortname)) {
360 return 0;
361 }
362
363 // Match by shortname
364 if ($match = array_search($role->shortname, $assignablerolesshortname)) {
365 return $match;
366 }
367
368 // Match by archetype
369 list($in_sql, $in_params) = $DB->get_in_or_equal(array_keys($assignablerolesshortname));
370 $params = array_merge(array($role->archetype), $in_params);
371 if ($rec = $DB->get_record_select('role', "archetype = ? AND id $in_sql", $params, 'id', IGNORE_MULTIPLE)) {
372 return $rec->id;
373 }
374
375 // Match editingteacher to teacher (happens a lot, from 1.9)
376 if ($role->shortname == 'editingteacher' && in_array('teacher', $assignablerolesshortname)) {
377 return array_search('teacher', $assignablerolesshortname);
378 }
379
380 // No match, return 0
381 return 0;
71a50b13
EL
382 }
383
8d4e41f4 384
71a50b13
EL
385 /**
386 * Process the loaded roles, looking for their best mapping or skipping
387 * Any error will cause exception. Note this is one wrapper over
388 * precheck_included_roles, that contains all the logic, but returns
389 * errors/warnings instead and is executed as part of the restore prechecks
390 */
8d4e41f4 391 public static function process_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings) {
71a50b13
EL
392 global $DB;
393
394 // Just let precheck_included_roles() to do all the hard work
8d4e41f4 395 $problems = self::precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings);
71a50b13
EL
396
397 // With problems of type error, throw exception, shouldn't happen if prechecks executed
398 if (array_key_exists('errors', $problems)) {
399 throw new restore_dbops_exception('restore_problems_processing_roles', null, implode(', ', $problems['errors']));
400 }
401 }
402
482aac65
EL
403 /**
404 * Load the needed users.xml file to backup_ids table for future reference
405 */
406 public static function load_users_to_tempids($restoreid, $usersfile) {
407
408 if (!file_exists($usersfile)) { // Shouldn't happen ever, but...
2df0f295 409 throw new backup_helper_exception('missing_users_xml_file', $usersfile);
482aac65
EL
410 }
411 // Let's parse, custom processor will do its work, sending info to DB
412 $xmlparser = new progressive_parser();
413 $xmlparser->set_file($usersfile);
414 $xmlprocessor = new restore_users_parser_processor($restoreid);
415 $xmlparser->set_processor($xmlprocessor);
416 $xmlparser->process();
417 }
418
41941110
EL
419 /**
420 * Load the needed questions.xml file to backup_ids table for future reference
421 */
422 public static function load_categories_and_questions_to_tempids($restoreid, $questionsfile) {
423
424 if (!file_exists($questionsfile)) { // Shouldn't happen ever, but...
425 throw new backup_helper_exception('missing_questions_xml_file', $questionsfile);
426 }
427 // Let's parse, custom processor will do its work, sending info to DB
428 $xmlparser = new progressive_parser();
429 $xmlparser->set_file($questionsfile);
430 $xmlprocessor = new restore_questions_parser_processor($restoreid);
431 $xmlparser->set_processor($xmlprocessor);
432 $xmlparser->process();
433 }
434
435 /**
436 * Check all the included categories and questions, deciding the action to perform
437 * for each one (mapping / creation) and returning one array of problems in case
438 * something is wrong.
439 *
440 * There are some basic rules that the method below will always try to enforce:
441 *
442 * Rule1: Targets will be, always, calculated for *whole* question banks (a.k.a. contexid source),
443 * so, given 2 question categories belonging to the same bank, their target bank will be
444 * always the same. If not, we can be incurring into "fragmentation", leading to random/cloze
445 * problems (qtypes having "child" questions).
446 *
447 * Rule2: The 'moodle/question:managecategory' and 'moodle/question:add' capabilities will be
448 * checked before creating any category/question respectively and, if the cap is not allowed
449 * into upper contexts (system, coursecat)) but in lower ones (course), the *whole* question bank
450 * will be created there.
451 *
452 * Rule3: Coursecat question banks not existing in the target site will be created as course
453 * (lower ctx) question banks, never as "guessed" coursecat question banks base on depth or so.
454 *
455 * Rule4: System question banks will be created at system context if user has perms to do so. Else they
456 * will created as course (lower ctx) question banks (similary to rule3). In other words, course ctx
457 * if always a fallback for system and coursecat question banks.
458 *
459 * Also, there are some notes to clarify the scope of this method:
460 *
461 * Note1: This method won't create any question category nor question at all. It simply will calculate
462 * which actions (create/map) must be performed for each element and where, validating that all those
463 * actions are doable by the user executing the restore operation. Any problem found will be
464 * returned in the problems array, causing the restore process to stop with error.
465 *
466 * Note2: To decide if one question bank (all its question categories and questions) is going to be remapped,
467 * then all the categories and questions must exist in the same target bank. If able to do so, missing
468 * qcats and qs will be created (rule2). But if, at the end, something is missing, the whole question bank
469 * will be recreated at course ctx (rule1), no matter if that duplicates some categories/questions.
470 *
471 * Note3: We'll be using the newitemid column in the temp_ids table to store the action to be performed
472 * with each question category and question. newitemid = 0 means the qcat/q needs to be created and
473 * any other value means the qcat/q is mapped. Also, for qcats, parentitemid will contain the target
474 * context where the categories have to be created (but for module contexts where we'll keep the old
475 * one until the activity is created)
476 *
477 * Note4: All these "actions" will be "executed" later by {@link restore_create_categories_and_questions}
478 */
479 public static function precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite) {
480
481 $problems = array();
482
483 // TODO: Check all qs, looking their qtypes are restorable
484
485 // Precheck all qcats and qs looking for target contexts / warnings / errors
486 list($syserr, $syswarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_SYSTEM);
487 list($caterr, $catwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_COURSECAT);
488 list($couerr, $couwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_COURSE);
489 list($moderr, $modwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_MODULE);
490
491 // Acummulate and handle errors and warnings
492 $errors = array_merge($syserr, $caterr, $couerr, $moderr);
493 $warnings = array_merge($syswarn, $catwarn, $couwarn, $modwarn);
494 if (!empty($errors)) {
495 $problems['errors'] = $errors;
496 }
497 if (!empty($warnings)) {
498 $problems['warnings'] = $warnings;
499 }
500 return $problems;
501 }
502
503 /**
504 * This function will process all the question banks present in restore
505 * at some contextlevel (from CONTEXT_SYSTEM to CONTEXT_MODULE), finding
506 * the target contexts where each bank will be restored and returning
507 * warnings/errors as needed.
508 *
509 * Some contextlevels (system, coursecat), will delegate process to
510 * course level if any problem is found (lack of permissions, non-matching
511 * target context...). Other contextlevels (course, module) will
512 * cause return error if some problem is found.
513 *
514 * At the end, if no errors were found, all the categories in backup_temp_ids
515 * will be pointing (parentitemid) to the target context where they must be
516 * created later in the restore process.
517 *
518 * Note: at the time these prechecks are executed, activities haven't been
519 * created yet so, for CONTEXT_MODULE banks, we keep the old contextid
520 * in the parentitemid field. Once the activity (and its context) has been
521 * created, we'll update that context in the required qcats
522 *
523 * Caller {@link precheck_categories_and_questions} will, simply, execute
524 * this function for all the contextlevels, acting as a simple controller
525 * of warnings and errors.
526 *
527 * The function returns 2 arrays, one containing errors and another containing
528 * warnings. Both empty if no errors/warnings are found.
529 */
530 public static function prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, $contextlevel) {
531 global $CFG, $DB;
532
533 // To return any errors and warnings found
534 $errors = array();
535 $warnings = array();
536
537 // Specify which fallbacks must be performed
538 $fallbacks = array(
539 CONTEXT_SYSTEM => CONTEXT_COURSE,
540 CONTEXT_COURSECAT => CONTEXT_COURSE);
541
542 // For any contextlevel, follow this process logic:
543 //
544 // 0) Iterate over each context (qbank)
545 // 1) Iterate over each qcat in the context, matching by stamp for the found target context
546 // 2a) No match, check if user can create qcat and q
547 // 3a) User can, mark the qcat and all dependent qs to be created in that target context
548 // 3b) User cannot, check if we are in some contextlevel with fallback
549 // 4a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
550 // 4b) No fallback, error. End qcat loop.
551 // 2b) Match, mark qcat to be mapped and iterate over each q, matching by stamp and version
552 // 5a) No match, check if user can add q
553 // 6a) User can, mark the q to be created
554 // 6b) User cannot, check if we are in some contextlevel with fallback
555 // 7a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
556 // 7b) No fallback, error. End qcat loop
557 // 5b) Match, mark q to be mapped
558
559 // Get all the contexts (question banks) in restore for the given contextlevel
560 $contexts = self::restore_get_question_banks($restoreid, $contextlevel);
561
562 // 0) Iterate over each context (qbank)
563 foreach ($contexts as $contextid => $contextlevel) {
564 // Init some perms
565 $canmanagecategory = false;
566 $canadd = false;
567 // get categories in context (bank)
568 $categories = self::restore_get_question_categories($restoreid, $contextid);
569 // cache permissions if $targetcontext is found
570 if ($targetcontext = self::restore_find_best_target_context($categories, $courseid, $contextlevel)) {
571 $canmanagecategory = has_capability('moodle/question:managecategory', $targetcontext, $userid);
572 $canadd = has_capability('moodle/question:add', $targetcontext, $userid);
573 }
574 // 1) Iterate over each qcat in the context, matching by stamp for the found target context
575 foreach ($categories as $category) {
576 $matchcat = false;
577 if ($targetcontext) {
578 $matchcat = $DB->get_record('question_categories', array(
579 'contextid' => $targetcontext->id,
580 'stamp' => $category->stamp));
581 }
582 // 2a) No match, check if user can create qcat and q
583 if (!$matchcat) {
584 // 3a) User can, mark the qcat and all dependent qs to be created in that target context
585 if ($canmanagecategory && $canadd) {
586 // Set parentitemid to targetcontext, BUT for CONTEXT_MODULE categories, where
587 // we keep the source contextid unmodified (for easier matching later when the
588 // activities are created)
589 $parentitemid = $targetcontext->id;
590 if ($contextlevel == CONTEXT_MODULE) {
591 $parentitemid = null; // null means "not modify" a.k.a. leave original contextid
592 }
593 self::set_backup_ids_record($restoreid, 'question_category', $category->id, 0, $parentitemid);
594 // Nothing else to mark, newitemid = 0 means create
595
596 // 3b) User cannot, check if we are in some contextlevel with fallback
597 } else {
598 // 4a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
599 if (array_key_exists($contextlevel, $fallbacks)) {
600 foreach ($categories as $movedcat) {
601 $movedcat->contextlevel = $fallbacks[$contextlevel];
602 self::set_backup_ids_record($restoreid, 'question_category', $movedcat->id, 0, $contextid, $movedcat);
603 // Warn about the performed fallback
604 $warnings[] = get_string('qcategory2coursefallback', 'backup', $movedcat);
605 }
606
607 // 4b) No fallback, error. End qcat loop.
608 } else {
609 $errors[] = get_string('qcategorycannotberestored', 'backup', $category);
610 }
611 break; // out from qcat loop (both 4a and 4b), we have decided about ALL categories in context (bank)
612 }
613
614 // 2b) Match, mark qcat to be mapped and iterate over each q, matching by stamp and version
615 } else {
616 self::set_backup_ids_record($restoreid, 'question_category', $category->id, $matchcat->id, $targetcontext->id);
617 $questions = self::restore_get_questions($restoreid, $category->id);
618 foreach ($questions as $question) {
619 $matchq = $DB->get_record('question', array(
620 'category' => $matchcat->id,
621 'stamp' => $question->stamp,
622 'version' => $question->version));
623 // 5a) No match, check if user can add q
624 if (!$matchq) {
625 // 6a) User can, mark the q to be created
626 if ($canadd) {
627 // Nothing to mark, newitemid means create
628
629 // 6b) User cannot, check if we are in some contextlevel with fallback
630 } else {
631 // 7a) There is fallback, move ALL the qcats to fallback, warn. End qcat loo
632 if (array_key_exists($contextlevel, $fallbacks)) {
633 foreach ($categories as $movedcat) {
634 $movedcat->contextlevel = $fallbacks[$contextlevel];
635 self::set_backup_ids_record($restoreid, 'question_category', $movedcat->id, 0, $contextid, $movedcat);
636 // Warn about the performed fallback
637 $warnings[] = get_string('question2coursefallback', 'backup', $movedcat);
638 }
639
640 // 7b) No fallback, error. End qcat loop
641 } else {
642 $errors[] = get_string('questioncannotberestored', 'backup', $question);
643 }
644 break 2; // out from qcat loop (both 7a and 7b), we have decided about ALL categories in context (bank)
645 }
646
647 // 5b) Match, mark q to be mapped
648 } else {
649 self::set_backup_ids_record($restoreid, 'question', $question->id, $matchq->id);
650 }
651 }
652 }
653 }
654 }
655
656 return array($errors, $warnings);
657 }
658
659 /**
660 * Return one array of contextid => contextlevel pairs
661 * of question banks to be checked for one given restore operation
662 * ordered from CONTEXT_SYSTEM downto CONTEXT_MODULE
663 * If contextlevel is specified, then only banks corresponding to
664 * that level are returned
665 */
666 public static function restore_get_question_banks($restoreid, $contextlevel = null) {
667 global $DB;
668
669 $results = array();
670 $qcats = $DB->get_records_sql("SELECT itemid, parentitemid AS contextid
671 FROM {backup_ids_temp}
672 WHERE backupid = ?
673 AND itemname = 'question_category'", array($restoreid));
674 foreach ($qcats as $qcat) {
675 // If this qcat context haven't been acummulated yet, do that
676 if (!isset($results[$qcat->contextid])) {
677 $temprec = self::get_backup_ids_record($restoreid, 'question_category', $qcat->itemid);
678 // Filter by contextlevel if necessary
679 if (is_null($contextlevel) || $contextlevel == $temprec->info->contextlevel) {
680 $results[$qcat->contextid] = $temprec->info->contextlevel;
681 }
682 }
683 }
684 // Sort by value (contextlevel from CONTEXT_SYSTEM downto CONTEXT_MODULE)
685 asort($results);
686 return $results;
687 }
688
689 /**
690 * Return one array of question_category records for
691 * a given restore operation and one restore context (question bank)
692 */
693 public static function restore_get_question_categories($restoreid, $contextid) {
694 global $DB;
695
696 $results = array();
697 $qcats = $DB->get_records_sql("SELECT itemid
698 FROM {backup_ids_temp}
699 WHERE backupid = ?
700 AND itemname = 'question_category'
701 AND parentitemid = ?", array($restoreid, $contextid));
702 foreach ($qcats as $qcat) {
703 $temprec = self::get_backup_ids_record($restoreid, 'question_category', $qcat->itemid);
704 $results[$qcat->itemid] = $temprec->info;
705 }
706 return $results;
707 }
708
709 /**
710 * Calculates the best context found to restore one collection of qcats,
711 * al them belonging to the same context (question bank), returning the
712 * target context found (object) or false
713 */
714 public static function restore_find_best_target_context($categories, $courseid, $contextlevel) {
715 global $DB;
716
717 $targetcontext = false;
718
719 // Depending of $contextlevel, we perform different actions
720 switch ($contextlevel) {
721 // For system is easy, the best context is the system context
722 case CONTEXT_SYSTEM:
723 $targetcontext = get_context_instance(CONTEXT_SYSTEM);
724 break;
725
726 // For coursecat, we are going to look for stamps in all the
727 // course categories between CONTEXT_SYSTEM and CONTEXT_COURSE
728 // (i.e. in all the course categories in the path)
729 //
730 // And only will return one "best" target context if all the
731 // matches belong to ONE and ONLY ONE context. If multiple
732 // matches are found, that means that there is some annoying
733 // qbank "fragmentation" in the categories, so we'll fallback
734 // to create the qbank at course level
735 case CONTEXT_COURSECAT:
736 // Build the array of stamps we are going to match
737 $stamps = array();
738 foreach ($categories as $category) {
739 $stamps[] = $category->stamp;
740 }
741 $contexts = array();
742 // Build the array of contexts we are going to look
743 $systemctx = get_context_instance(CONTEXT_SYSTEM);
744 $coursectx = get_context_instance(CONTEXT_COURSE, $courseid);
745 $parentctxs= get_parent_contexts($coursectx);
746 foreach ($parentctxs as $parentctx) {
747 // Exclude system context
748 if ($parentctx == $systemctx->id) {
749 continue;
750 }
751 $contexts[] = $parentctx;
752 }
753 if (!empty($stamps) && !empty($contexts)) {
754 // Prepare the query
755 list($stamp_sql, $stamp_params) = $DB->get_in_or_equal($stamps);
756 list($context_sql, $context_params) = $DB->get_in_or_equal($contexts);
757 $sql = "SELECT contextid
758 FROM {question_categories}
759 WHERE stamp $stamp_sql
760 AND contextid $context_sql";
761 $params = array_merge($stamp_params, $context_params);
762 $matchingcontexts = $DB->get_records_sql($sql, $params);
763 // Only if ONE and ONLY ONE context is found, use it as valid target
764 if (count($matchingcontexts) == 1) {
765 $targetcontext = get_context_instance_by_id(reset($matchingcontexts)->contextid);
766 }
767 }
768 break;
769
770 // For course is easy, the best context is the course context
771 case CONTEXT_COURSE:
772 $targetcontext = get_context_instance(CONTEXT_COURSE, $courseid);
773 break;
774
775 // For module is easy, there is not best context, as far as the
776 // activity hasn't been created yet. So we return context course
777 // for them, so permission checks and friends will work. Note this
778 // case is handled by {@link prechek_precheck_qbanks_by_level}
779 // in an special way
780 case CONTEXT_MODULE:
781 $targetcontext = get_context_instance(CONTEXT_COURSE, $courseid);
782 break;
783 }
784 return $targetcontext;
785 }
786
787 /**
788 * Return one array of question records for
789 * a given restore operation and one question category
790 */
791 public static function restore_get_questions($restoreid, $qcatid) {
792 global $DB;
793
794 $results = array();
795 $qs = $DB->get_records_sql("SELECT itemid
796 FROM {backup_ids_temp}
797 WHERE backupid = ?
798 AND itemname = 'question'
799 AND parentitemid = ?", array($restoreid, $qcatid));
800 foreach ($qs as $q) {
801 $temprec = self::get_backup_ids_record($restoreid, 'question', $q->itemid);
802 $results[$q->itemid] = $temprec->info;
803 }
804 return $results;
805 }
806
2df0f295
EL
807 /**
808 * Given one component/filearea/context and
809 * optionally one source itemname to match itemids
810 * put the corresponding files in the pool
4b6b087f
DM
811 *
812 * @param string $basepath the full path to the root of unzipped backup file
813 * @param string $restoreid the restore job's identification
814 * @param string $component
815 * @param string $filearea
816 * @param int $oldcontextid
817 * @param int $dfltuserid default $file->user if the old one can't be mapped
818 * @param string|null $itemname
819 * @param int|null $olditemid
820 * @param int|null $forcenewcontextid explicit value for the new contextid (skip mapping)
821 * @param bool $skipparentitemidctxmatch
16ee63b4 822 * @return array of result object
2df0f295 823 */
41941110 824 public static function send_files_to_pool($basepath, $restoreid, $component, $filearea, $oldcontextid, $dfltuserid, $itemname = null, $olditemid = null, $forcenewcontextid = null, $skipparentitemidctxmatch = false) {
2df0f295
EL
825 global $DB;
826
16ee63b4
FM
827 $results = array();
828
41941110
EL
829 if ($forcenewcontextid) {
830 // Some components can have "forced" new contexts (example: questions can end belonging to non-standard context mappings,
831 // with questions originally at system/coursecat context in source being restored to course context in target). So we need
832 // to be able to force the new contextid
833 $newcontextid = $forcenewcontextid;
834 } else {
835 // Get new context, must exist or this will fail
836 if (!$newcontextid = self::get_backup_ids_record($restoreid, 'context', $oldcontextid)->newitemid) {
837 throw new restore_dbops_exception('unknown_context_mapping', $oldcontextid);
838 }
839 }
840
841 // Sometimes it's possible to have not the oldcontextids stored into backup_ids_temp->parentitemid
842 // columns (because we have used them to store other information). This happens usually with
843 // all the question related backup_ids_temp records. In that case, it's safe to ignore that
844 // matching as far as we are always restoring for well known oldcontexts and olditemids
845 $parentitemctxmatchsql = ' AND i.parentitemid = f.contextid ';
846 if ($skipparentitemidctxmatch) {
847 $parentitemctxmatchsql = '';
2df0f295
EL
848 }
849
b212f87e 850 // Important: remember how files have been loaded to backup_files_temp
2df0f295
EL
851 // - info: contains the whole original object (times, names...)
852 // (all them being original ids as loaded from xml)
853
854 // itemname = null, we are going to match only by context, no need to use itemid (all them are 0)
855 if ($itemname == null) {
83b2cc56 856 $sql = "SELECT id AS bftid, contextid, component, filearea, itemid, itemid AS newitemid, info
b8bb45b0 857 FROM {backup_files_temp}
2df0f295 858 WHERE backupid = ?
b8bb45b0
EL
859 AND contextid = ?
860 AND component = ?
83b2cc56 861 AND filearea = ?";
b8bb45b0 862 $params = array($restoreid, $oldcontextid, $component, $filearea);
2df0f295 863
b8bb45b0 864 // itemname not null, going to join with backup_ids to perform the old-new mapping of itemids
2df0f295 865 } else {
83b2cc56 866 $sql = "SELECT f.id AS bftid, f.contextid, f.component, f.filearea, f.itemid, i.newitemid, f.info
b8bb45b0 867 FROM {backup_files_temp} f
2df0f295 868 JOIN {backup_ids_temp} i ON i.backupid = f.backupid
41941110 869 $parentitemctxmatchsql
b8bb45b0 870 AND i.itemid = f.itemid
2df0f295 871 WHERE f.backupid = ?
b8bb45b0
EL
872 AND f.contextid = ?
873 AND f.component = ?
874 AND f.filearea = ?
41941110 875 AND i.itemname = ?";
b8bb45b0 876 $params = array($restoreid, $oldcontextid, $component, $filearea, $itemname);
f2745cbe
EL
877 if ($olditemid !== null) { // Just process ONE olditemid intead of the whole itemname
878 $sql .= ' AND i.itemid = ?';
879 $params[] = $olditemid;
880 }
2df0f295
EL
881 }
882
2df0f295
EL
883 $fs = get_file_storage(); // Get moodle file storage
884 $basepath = $basepath . '/files/';// Get backup file pool base
71a50b13 885 $rs = $DB->get_recordset_sql($sql, $params);
2df0f295 886 foreach ($rs as $rec) {
b8bb45b0 887 $file = (object)unserialize(base64_decode($rec->info));
67233725 888
2df0f295
EL
889 // ignore root dirs (they are created automatically)
890 if ($file->filepath == '/' && $file->filename == '.') {
891 continue;
892 }
4b6b087f 893
84cdf7de
EL
894 // set the best possible user
895 $mappeduser = self::get_backup_ids_record($restoreid, 'user', $file->userid);
4b6b087f
DM
896 $mappeduserid = !empty($mappeduser) ? $mappeduser->newitemid : $dfltuserid;
897
898 // dir found (and not root one), let's create it
2df0f295 899 if ($file->filename == '.') {
4b6b087f 900 $fs->create_directory($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $mappeduserid);
2df0f295
EL
901 continue;
902 }
67233725 903
4b6b087f
DM
904 if (empty($file->repositoryid)) {
905 // this is a regular file, it must be present in the backup pool
906 $backuppath = $basepath . backup_file_manager::get_backup_content_file_location($file->contenthash);
67233725 907
16ee63b4 908 // The file is not found in the backup.
4b6b087f 909 if (!file_exists($backuppath)) {
16ee63b4
FM
910 $result = new stdClass();
911 $result->code = 'file_missing_in_backup';
912 $result->message = sprintf('missing file %s%s in backup', $file->filepath, $file->filename);
913 $result->level = backup::LOG_WARNING;
914 $results[] = $result;
915 continue;
4b6b087f
DM
916 }
917
918 // create the file in the filepool if it does not exist yet
919 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
920 $file_record = array(
921 'contextid' => $newcontextid,
922 'component' => $component,
923 'filearea' => $filearea,
924 'itemid' => $rec->newitemid,
925 'filepath' => $file->filepath,
926 'filename' => $file->filename,
927 'timecreated' => $file->timecreated,
928 'timemodified'=> $file->timemodified,
929 'userid' => $mappeduserid,
930 'author' => $file->author,
931 'license' => $file->license,
932 'sortorder' => $file->sortorder
933 );
67233725
DC
934 $fs->create_file_from_pathname($file_record, $backuppath);
935 }
4b6b087f 936
83b2cc56
DM
937 // store the the new contextid and the new itemid in case we need to remap
938 // references to this file later
939 $DB->update_record('backup_files_temp', array(
940 'id' => $rec->bftid,
941 'newcontextid' => $newcontextid,
942 'newitemid' => $rec->newitemid), true);
943
4b6b087f
DM
944 } else {
945 // this is an alias - we can't create it yet so we stash it in a temp
946 // table and will let the final task to deal with it
947 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
948 $info = new stdClass();
949 // oldfile holds the raw information stored in MBZ (including reference-related info)
950 $info->oldfile = $file;
951 // newfile holds the info for the new file_record with the context, user and itemid mapped
952 $info->newfile = (object)array(
953 'contextid' => $newcontextid,
954 'component' => $component,
955 'filearea' => $filearea,
956 'itemid' => $rec->newitemid,
957 'filepath' => $file->filepath,
958 'filename' => $file->filename,
959 'timecreated' => $file->timecreated,
960 'timemodified'=> $file->timemodified,
961 'userid' => $mappeduserid,
962 'author' => $file->author,
963 'license' => $file->license,
964 'sortorder' => $file->sortorder
965 );
966
967 restore_dbops::set_backup_ids_record($restoreid, 'file_aliases_queue', $file->id, 0, null, $info);
968 }
2df0f295
EL
969 }
970 }
971 $rs->close();
16ee63b4 972 return $results;
2df0f295
EL
973 }
974
482aac65
EL
975 /**
976 * Given one restoreid, create in DB all the users present
977 * in backup_ids having newitemid = 0, as far as
978 * precheck_included_users() have left them there
979 * ready to be created. Also, annotate their newids
980 * once created for later reference
981 */
ac6dc09c 982 public static function create_included_users($basepath, $restoreid, $userid) {
482aac65
EL
983 global $CFG, $DB;
984
985 $authcache = array(); // Cache to get some bits from authentication plugins
986 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search later
987 $themes = get_list_of_themes(); // Get themes for quick search later
988
989 // Iterate over all the included users with newitemid = 0, have to create them
990 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid');
991 foreach ($rs as $recuser) {
992 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
993
994 // if user lang doesn't exist here, use site default
995 if (!array_key_exists($user->lang, $languages)) {
996 $user->lang = $CFG->lang;
997 }
998
999 // if user theme isn't available on target site or they are disabled, reset theme
1000 if (!empty($user->theme)) {
1001 if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) {
1002 $user->theme = '';
1003 }
1004 }
1005
1006 // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id
1007 // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual
1008 if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
1009 // Respect registerauth
1010 if ($CFG->registerauth == 'email') {
1011 $user->auth = 'email';
1012 } else {
1013 $user->auth = 'manual';
1014 }
1015 }
1016 unset($user->mnethosturl); // Not needed anymore
1017
1018 // Disable pictures based on global setting
1019 if (!empty($CFG->disableuserimages)) {
1020 $user->picture = 0;
1021 }
1022
1023 // We need to analyse the AUTH field to recode it:
1024 // - if the auth isn't enabled in target site, $CFG->registerauth will decide
1025 // - finally, if the auth resulting isn't enabled, default to 'manual'
1026 if (!is_enabled_auth($user->auth)) {
1027 if ($CFG->registerauth == 'email') {
1028 $user->auth = 'email';
1029 } else {
1030 $user->auth = 'manual';
1031 }
1032 }
1033 if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled
1034 $user->auth = 'manual';
1035 }
1036
1037 // Now that we know the auth method, for users to be created without pass
1038 // if password handling is internal and reset password is available
1039 // we set the password to "restored" (plain text), so the login process
1040 // will know how to handle that situation in order to allow the user to
1041 // recover the password. MDL-20846
1042 if (empty($user->password)) { // Only if restore comes without password
1043 if (!array_key_exists($user->auth, $authcache)) { // Not in cache
1044 $userauth = new stdClass();
1045 $authplugin = get_auth_plugin($user->auth);
1046 $userauth->preventpassindb = $authplugin->prevent_local_passwords();
1047 $userauth->isinternal = $authplugin->is_internal();
1048 $userauth->canresetpwd = $authplugin->can_reset_password();
1049 $authcache[$user->auth] = $userauth;
1050 } else {
1051 $userauth = $authcache[$user->auth]; // Get from cache
1052 }
1053
1054 // Most external plugins do not store passwords locally
1055 if (!empty($userauth->preventpassindb)) {
1056 $user->password = 'not cached';
1057
1058 // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
1059 } else if ($userauth->isinternal and $userauth->canresetpwd) {
1060 $user->password = 'restored';
1061 }
1062 }
1063
1064 // Creating new user, we must reset the policyagreed always
1065 $user->policyagreed = 0;
1066
1067 // Set time created if empty
1068 if (empty($user->timecreated)) {
1069 $user->timecreated = time();
1070 }
1071
1072 // Done, let's create the user and annotate its id
1073 $newuserid = $DB->insert_record('user', $user);
1074 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid);
1075 // Let's create the user context and annotate it (we need it for sure at least for files)
1acad8ee
EL
1076 // but for deleted users that don't have a context anymore (MDL-30192). We are done for them
1077 // and nothing else (custom fields, prefs, tags, files...) will be created.
1078 if (empty($user->deleted)) {
1079 $newuserctxid = $user->deleted ? 0 : get_context_instance(CONTEXT_USER, $newuserid)->id;
1080 self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid);
1081
1082 // Process custom fields
1083 if (isset($user->custom_fields)) { // if present in backup
1084 foreach($user->custom_fields['custom_field'] as $udata) {
1085 $udata = (object)$udata;
1086 // If the profile field has data and the profile shortname-datatype is defined in server
1087 if ($udata->field_data) {
1088 if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) {
1089 /// Insert the user_custom_profile_field
1090 $rec = new stdClass();
1091 $rec->userid = $newuserid;
1092 $rec->fieldid = $field->id;
1093 $rec->data = $udata->field_data;
1094 $DB->insert_record('user_info_data', $rec);
1095 }
482aac65
EL
1096 }
1097 }
1098 }
482aac65 1099
1acad8ee
EL
1100 // Process tags
1101 if (!empty($CFG->usetags) && isset($user->tags)) { // if enabled in server and present in backup
1102 $tags = array();
1103 foreach($user->tags['tag'] as $usertag) {
1104 $usertag = (object)$usertag;
1105 $tags[] = $usertag->rawname;
1106 }
1107 tag_set('user', $newuserid, $tags);
482aac65 1108 }
482aac65 1109
1acad8ee
EL
1110 // Process preferences
1111 if (isset($user->preferences)) { // if present in backup
1112 foreach($user->preferences['preference'] as $preference) {
1113 $preference = (object)$preference;
1114 // Prepare the record and insert it
1115 $preference->userid = $newuserid;
1116 $status = $DB->insert_record('user_preferences', $preference);
1117 }
482aac65 1118 }
482aac65 1119
1acad8ee
EL
1120 // Create user files in pool (profile, icon, private) by context
1121 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon', $recuser->parentitemid, $userid);
1122 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile', $recuser->parentitemid, $userid);
1acad8ee 1123 }
482aac65
EL
1124 }
1125 $rs->close();
1126 }
1127
1128 /**
1129 * Given one user object (from backup file), perform all the neccesary
1130 * checks is order to decide how that user will be handled on restore.
1131 *
1132 * Note the function requires $user->mnethostid to be already calculated
1133 * so it's caller responsibility to set it
1134 *
1135 * This function is used both by @restore_precheck_users() and
1136 * @restore_create_users() to get consistent results in both places
1137 *
1138 * It returns:
1139 * - one user object (from DB), if match has been found and user will be remapped
1140 * - boolean true if the user needs to be created
1141 * - boolean false if some conflict happened and the user cannot be handled
1142 *
1143 * Each test is responsible for returning its results and interrupt
1144 * execution. At the end, boolean true (user needs to be created) will be
1145 * returned if no test has interrupted that.
1146 *
1147 * Here it's the logic applied, keep it updated:
1148 *
1149 * If restoring users from same site backup:
1150 * 1A - Normal check: If match by id and username and mnethost => ok, return target user
1d8066e2
DS
1151 * 1B - If restoring an 'anonymous' user (created via the 'Anonymize user information' option) try to find a
1152 * match by username only => ok, return target user MDL-31484
1153 * 1C - Handle users deleted in DB and "alive" in backup file:
482aac65
EL
1154 * If match by id and mnethost and user is deleted in DB and
1155 * (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user
1d8066e2 1156 * 1D - Handle users deleted in backup file and "alive" in DB:
482aac65
EL
1157 * If match by id and mnethost and user is deleted in backup file
1158 * and match by email = email_without_time(backup_email) => ok, return target user
1d8066e2
DS
1159 * 1E - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false
1160 * 1F - None of the above, return true => User needs to be created
482aac65
EL
1161 *
1162 * if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination):
1163 * 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user
1164 * 2B - Handle users deleted in DB and "alive" in backup file:
1165 * 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
1166 * (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
1167 * 2B2 - If match by mnethost and user is deleted in DB and
1168 * username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
1169 * (to cover situations were md5(username) wasn't implemented on delete we requiere both)
1170 * 2C - Handle users deleted in backup file and "alive" in DB:
1171 * If match mnethost and user is deleted in backup file
1172 * and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
1173 * 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
1174 * 2E - None of the above, return true => User needs to be created
1175 *
1176 * Note: for DB deleted users email is stored in username field, hence we
1177 * are looking there for emails. See delete_user()
1178 * Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1179 * hence we are looking there for usernames if not empty. See delete_user()
1180 */
1181 protected static function precheck_user($user, $samesite) {
1182 global $CFG, $DB;
1183
1184 // Handle checks from same site backups
1185 if ($samesite && empty($CFG->forcedifferentsitecheckingusersonrestore)) {
1186
1187 // 1A - If match by id and username and mnethost => ok, return target user
1188 if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
1189 return $rec; // Matching user found, return it
1190 }
1191
1d8066e2
DS
1192 // 1B - If restoring an 'anonymous' user (created via the 'Anonymize user information' option) try to find a
1193 // match by username only => ok, return target user MDL-31484
1194 // This avoids username / id mis-match problems when restoring subsequent anonymized backups.
1195 if (backup_anonymizer_helper::is_anonymous_user($user)) {
1196 if ($rec = $DB->get_record('user', array('username' => $user->username))) {
1197 return $rec; // Matching anonymous user found - return it
1198 }
1199 }
1200
1201 // 1C - Handle users deleted in DB and "alive" in backup file
482aac65
EL
1202 // Note: for DB deleted users email is stored in username field, hence we
1203 // are looking there for emails. See delete_user()
1204 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1205 // hence we are looking there for usernames if not empty. See delete_user()
1206 // If match by id and mnethost and user is deleted in DB and
1207 // match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user
1208 if ($rec = $DB->get_record_sql("SELECT *
1209 FROM {user} u
1210 WHERE id = ?
1211 AND mnethostid = ?
1212 AND deleted = 1
1213 AND (
ef6b3ba1 1214 UPPER(username) LIKE UPPER(?)
482aac65
EL
1215 OR (
1216 ".$DB->sql_isnotempty('user', 'email', false, false)."
1217 AND email = ?
1218 )
1219 )",
1220 array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) {
1221 return $rec; // Matching user, deleted in DB found, return it
1222 }
1223
1d8066e2 1224 // 1D - Handle users deleted in backup file and "alive" in DB
482aac65
EL
1225 // If match by id and mnethost and user is deleted in backup file
1226 // and match by email = email_without_time(backup_email) => ok, return target user
1227 if ($user->deleted) {
1228 // Note: for DB deleted users email is stored in username field, hence we
1229 // are looking there for emails. See delete_user()
1230 // Trim time() from email
1231 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
1232 if ($rec = $DB->get_record_sql("SELECT *
1233 FROM {user} u
1234 WHERE id = ?
1235 AND mnethostid = ?
ef6b3ba1 1236 AND UPPER(email) = UPPER(?)",
482aac65
EL
1237 array($user->id, $user->mnethostid, $trimemail))) {
1238 return $rec; // Matching user, deleted in backup file found, return it
1239 }
1240 }
1241
1d8066e2 1242 // 1E - If match by username and mnethost and doesn't match by id => conflict, return false
482aac65
EL
1243 if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
1244 if ($user->id != $rec->id) {
1245 return false; // Conflict, username already exists and belongs to another id
1246 }
1247 }
1248
1249 // Handle checks from different site backups
1250 } else {
1251
1252 // 2A - If match by username and mnethost and
1253 // (email or non-zero firstaccess) => ok, return target user
1254 if ($rec = $DB->get_record_sql("SELECT *
1255 FROM {user} u
1256 WHERE username = ?
1257 AND mnethostid = ?
1258 AND (
ef6b3ba1 1259 UPPER(email) = UPPER(?)
482aac65
EL
1260 OR (
1261 firstaccess != 0
1262 AND firstaccess = ?
1263 )
1264 )",
1265 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
1266 return $rec; // Matching user found, return it
1267 }
1268
1269 // 2B - Handle users deleted in DB and "alive" in backup file
1270 // Note: for DB deleted users email is stored in username field, hence we
1271 // are looking there for emails. See delete_user()
1272 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1273 // hence we are looking there for usernames if not empty. See delete_user()
1274 // 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
1275 // (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
1276 if ($rec = $DB->get_record_sql("SELECT *
1277 FROM {user} u
1278 WHERE mnethostid = ?
1279 AND deleted = 1
1280 AND ".$DB->sql_isnotempty('user', 'email', false, false)."
1281 AND email = ?
1282 AND (
ef6b3ba1 1283 UPPER(username) LIKE UPPER(?)
482aac65
EL
1284 OR (
1285 firstaccess != 0
1286 AND firstaccess = ?
1287 )
1288 )",
1289 array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) {
1290 return $rec; // Matching user found, return it
1291 }
1292
1293 // 2B2 - If match by mnethost and user is deleted in DB and
1294 // username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
1295 // (this covers situations where md5(username) wasn't being stored so we require both
1296 // the email & non-zero firstaccess to match)
1297 if ($rec = $DB->get_record_sql("SELECT *
1298 FROM {user} u
1299 WHERE mnethostid = ?
1300 AND deleted = 1
ef6b3ba1 1301 AND UPPER(username) LIKE UPPER(?)
482aac65
EL
1302 AND firstaccess != 0
1303 AND firstaccess = ?",
1304 array($user->mnethostid, $user->email.'.%', $user->firstaccess))) {
1305 return $rec; // Matching user found, return it
1306 }
1307
1308 // 2C - Handle users deleted in backup file and "alive" in DB
1309 // If match mnethost and user is deleted in backup file
1310 // and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
1311 if ($user->deleted) {
1312 // Note: for DB deleted users email is stored in username field, hence we
1313 // are looking there for emails. See delete_user()
1314 // Trim time() from email
1315 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
1316 if ($rec = $DB->get_record_sql("SELECT *
1317 FROM {user} u
1318 WHERE mnethostid = ?
ef6b3ba1 1319 AND UPPER(email) = UPPER(?)
482aac65
EL
1320 AND firstaccess != 0
1321 AND firstaccess = ?",
1322 array($user->mnethostid, $trimemail, $user->firstaccess))) {
1323 return $rec; // Matching user, deleted in backup file found, return it
1324 }
1325 }
1326
1327 // 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
1328 if ($rec = $DB->get_record_sql("SELECT *
1329 FROM {user} u
1330 WHERE username = ?
1331 AND mnethostid = ?
1332 AND NOT (
ef6b3ba1 1333 UPPER(email) = UPPER(?)
482aac65
EL
1334 OR (
1335 firstaccess != 0
1336 AND firstaccess = ?
1337 )
1338 )",
1339 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
1340 return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess)
1341 }
1342 }
1343
1344 // Arrived here, return true as the user will need to be created and no
1345 // conflicts have been found in the logic above. This covers:
1346 // 1E - else => user needs to be created, return true
1347 // 2E - else => user needs to be created, return true
1348 return true;
1349 }
1350
1351 /**
1352 * Check all the included users, deciding the action to perform
1353 * for each one (mapping / creation) and returning one array
1354 * of problems in case something is wrong (lack of permissions,
1355 * conficts)
1356 */
1357 public static function precheck_included_users($restoreid, $courseid, $userid, $samesite) {
1358 global $CFG, $DB;
1359
1360 // To return any problem found
1361 $problems = array();
1362
1363 // We are going to map mnethostid, so load all the available ones
1364 $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id');
1365
1366 // Calculate the context we are going to use for capability checking
1367 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1368
1369 // Calculate if we have perms to create users, by checking:
1370 // to 'moodle/restore:createuser' and 'moodle/restore:userinfo'
1371 // and also observe $CFG->disableusercreationonrestore
1372 $cancreateuser = false;
1373 if (has_capability('moodle/restore:createuser', $context, $userid) and
1374 has_capability('moodle/restore:userinfo', $context, $userid) and
1375 empty($CFG->disableusercreationonrestore)) { // Can create users
1376
1377 $cancreateuser = true;
1378 }
1379
1380 // Iterate over all the included users
1381 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user'), '', 'itemid');
1382 foreach ($rs as $recuser) {
1383 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
1384
1385 // Find the correct mnethostid for user before performing any further check
1386 if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
1387 $user->mnethostid = $CFG->mnet_localhost_id;
1388 } else {
1389 // fast url-to-id lookups
1390 if (isset($mnethosts[$user->mnethosturl])) {
1391 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
1392 } else {
1393 $user->mnethostid = $CFG->mnet_localhost_id;
1394 }
1395 }
1396
1397 // Now, precheck that user and, based on returned results, annotate action/problem
1398 $usercheck = self::precheck_user($user, $samesite);
1399
1400 if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to
1401 // Annotate it, for later process. Set newitemid to mapping user->id
1402 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $usercheck->id);
1403
1404 } else if ($usercheck === false) { // Found conflict, report it as problem
1405 $problems[] = get_string('restoreuserconflict', '', $user->username);
1406
1407 } else if ($usercheck === true) { // User needs to be created, check if we are able
1408 if ($cancreateuser) { // Can create user, set newitemid to 0 so will be created later
1409 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, 0, null, (array)$user);
1410
1411 } else { // Cannot create user, report it as problem
1412 $problems[] = get_string('restorecannotcreateuser', '', $user->username);
1413 }
1414
1415 } else { // Shouldn't arrive here ever, something is for sure wrong. Exception
1416 throw new restore_dbops_exception('restore_error_processing_user', $user->username);
1417 }
1418 }
1419 $rs->close();
1420 return $problems;
1421 }
1422
1423 /**
41941110
EL
1424 * Process the needed users in order to decide
1425 * which action to perform with them (create/map)
482aac65
EL
1426 *
1427 * Just wrap over precheck_included_users(), returning
41941110 1428 * exception if any problem is found
482aac65
EL
1429 */
1430 public static function process_included_users($restoreid, $courseid, $userid, $samesite) {
1431 global $DB;
1432
1433 // Just let precheck_included_users() to do all the hard work
1434 $problems = self::precheck_included_users($restoreid, $courseid, $userid, $samesite);
1435
1436 // With problems, throw exception, shouldn't happen if prechecks were originally
1437 // executed, so be radical here.
1438 if (!empty($problems)) {
1439 throw new restore_dbops_exception('restore_problems_processing_users', null, implode(', ', $problems));
1440 }
482aac65
EL
1441 }
1442
41941110
EL
1443 /**
1444 * Process the needed question categories and questions
1445 * to check all them, deciding about the action to perform
1446 * (create/map) and target.
1447 *
1448 * Just wrap over precheck_categories_and_questions(), returning
1449 * exception if any problem is found
1450 */
1451 public static function process_categories_and_questions($restoreid, $courseid, $userid, $samesite) {
1452 global $DB;
1453
1454 // Just let precheck_included_users() to do all the hard work
1455 $problems = self::precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite);
1456
1457 // With problems of type error, throw exception, shouldn't happen if prechecks were originally
1458 // executed, so be radical here.
1459 if (array_key_exists('errors', $problems)) {
ede7105f 1460 throw new restore_dbops_exception('restore_problems_processing_questions', null, implode(', ', $problems['errors']));
41941110
EL
1461 }
1462 }
1463
b8bb45b0
EL
1464 public static function set_backup_files_record($restoreid, $filerec) {
1465 global $DB;
1466
67233725 1467 // Store external files info in `info` field
b8bb45b0
EL
1468 $filerec->info = base64_encode(serialize($filerec)); // Serialize the whole rec in info
1469 $filerec->backupid = $restoreid;
1470 $DB->insert_record('backup_files_temp', $filerec);
1471 }
1472
482aac65 1473 public static function set_backup_ids_record($restoreid, $itemname, $itemid, $newitemid = 0, $parentitemid = null, $info = null) {
482aac65
EL
1474 // Build conditionally the extra record info
1475 $extrarecord = array();
1476 if ($newitemid != 0) {
1477 $extrarecord['newitemid'] = $newitemid;
1478 }
1479 if ($parentitemid != null) {
1480 $extrarecord['parentitemid'] = $parentitemid;
1481 }
1482 if ($info != null) {
1483 $extrarecord['info'] = base64_encode(serialize($info));
1484 }
1485
7f98b12f 1486 self::set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord);
482aac65
EL
1487 }
1488
1489 public static function get_backup_ids_record($restoreid, $itemname, $itemid) {
7f98b12f 1490 $dbrec = self::get_backup_ids_cached($restoreid, $itemname, $itemid);
482aac65 1491
7f98b12f
TL
1492 if ($dbrec && isset($dbrec->info) && is_string($dbrec->info)) {
1493 $dbrec->info = unserialize(base64_decode($dbrec->info));
482aac65 1494 }
7f98b12f 1495
482aac65
EL
1496 return $dbrec;
1497 }
4bca307a
EL
1498
1499 /**
1500 * Given on courseid, fullname and shortname, calculate the correct fullname/shortname to avoid dupes
1501 */
1502 public static function calculate_course_names($courseid, $fullname, $shortname) {
1503 global $CFG, $DB;
1504
1505 $currentfullname = '';
1506 $currentshortname = '';
1507 $counter = 0;
1508 // Iteratere while the name exists
1509 do {
1510 if ($counter) {
1511 $suffixfull = ' ' . get_string('copyasnoun') . ' ' . $counter;
1512 $suffixshort = '_' . $counter;
1513 } else {
1514 $suffixfull = '';
1515 $suffixshort = '';
1516 }
1517 $currentfullname = $fullname.$suffixfull;
1518 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; // < 100cc
6e763244
MN
1519 $coursefull = $DB->get_record_select('course', 'fullname = ? AND id != ?',
1520 array($currentfullname, $courseid), '*', IGNORE_MULTIPLE);
4bca307a
EL
1521 $courseshort = $DB->get_record_select('course', 'shortname = ? AND id != ?', array($currentshortname, $courseid));
1522 $counter++;
1523 } while ($coursefull || $courseshort);
1524
1525 // Return results
1526 return array($currentfullname, $currentshortname);
1527 }
1528
1529 /**
1530 * For the target course context, put as many custom role names as possible
1531 */
1532 public static function set_course_role_names($restoreid, $courseid) {
1533 global $DB;
1534
1535 // Get the course context
1536 $coursectx = get_context_instance(CONTEXT_COURSE, $courseid);
1537 // Get all the mapped roles we have
1538 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid');
1539 foreach ($rs as $recrole) {
1540 // Get the complete temp_ids record
1541 $role = (object)self::get_backup_ids_record($restoreid, 'role', $recrole->itemid);
024c288d
EL
1542 // If it's one mapped role and we have one name for it
1543 if (!empty($role->newitemid) && !empty($role->info['nameincourse'])) {
4bca307a
EL
1544 // If role name doesn't exist, add it
1545 $rolename = new stdclass();
1546 $rolename->roleid = $role->newitemid;
1547 $rolename->contextid = $coursectx->id;
1548 if (!$DB->record_exists('role_names', (array)$rolename)) {
1549 $rolename->name = $role->info['nameincourse'];
1550 $DB->insert_record('role_names', $rolename);
1551 }
1552 }
1553 }
1554 $rs->close();
1555 }
785d6603 1556
3acc9b81
SH
1557 /**
1558 * Creates a skeleton record within the database using the passed parameters
1559 * and returns the new course id.
1560 *
1561 * @global moodle_database $DB
1562 * @param string $fullname
1563 * @param string $shortname
1564 * @param int $categoryid
1565 * @return int The new course id
1566 */
785d6603
SH
1567 public static function create_new_course($fullname, $shortname, $categoryid) {
1568 global $DB;
1569 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1570
1571 $course = new stdClass;
1572 $course->fullname = $fullname;
1573 $course->shortname = $shortname;
1574 $course->category = $category->id;
1575 $course->sortorder = 0;
1576 $course->timecreated = time();
1577 $course->timemodified = $course->timecreated;
ed6a14eb
AB
1578 // forcing skeleton courses to be hidden instead of going by $category->visible , until MDL-27790 is resolved.
1579 $course->visible = 0;
785d6603 1580
593fc4a9
SH
1581 $courseid = $DB->insert_record('course', $course);
1582
1583 $category->coursecount++;
1584 $DB->update_record('course_categories', $category);
1585
1586 return $courseid;
785d6603
SH
1587 }
1588
3acc9b81
SH
1589 /**
1590 * Deletes all of the content associated with the given course (courseid)
1591 * @param int $courseid
d53e3298 1592 * @param array $options
3acc9b81
SH
1593 * @return bool True for success
1594 */
d53e3298
PS
1595 public static function delete_course_content($courseid, array $options = null) {
1596 return remove_course_contents($courseid, false, $options);
785d6603 1597 }
482aac65 1598}
fbc2778d
EL
1599
1600/*
1601 * Exception class used by all the @dbops stuff
1602 */
1603class restore_dbops_exception extends backup_exception {
1604
1605 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
1606 parent::__construct($errorcode, 'error', '', $a, null, $debuginfo);
1607 }
1608}