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