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