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