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