MDL-27120: Cache dirname transformations in progressive_parser::dirname
[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));
67233725
DC
688
689 $isreference = !empty($file->repositoryid);
690
2df0f295
EL
691 // ignore root dirs (they are created automatically)
692 if ($file->filepath == '/' && $file->filename == '.') {
693 continue;
694 }
84cdf7de
EL
695 // set the best possible user
696 $mappeduser = self::get_backup_ids_record($restoreid, 'user', $file->userid);
697 $file->userid = !empty($mappeduser) ? $mappeduser->newitemid : $dfltuserid;
2df0f295
EL
698 // dir found (and not root one), let's create if
699 if ($file->filename == '.') {
84cdf7de 700 $fs->create_directory($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->userid);
2df0f295
EL
701 continue;
702 }
67233725 703
2df0f295
EL
704 // arrived here, file found
705 // Find file in backup pool
2b199e7c 706 $backuppath = $basepath . backup_file_manager::get_backup_content_file_location($file->contenthash);
67233725
DC
707
708 if (!file_exists($backuppath) && !$isreference) {
2df0f295
EL
709 throw new restore_dbops_exception('file_not_found_in_pool', $file);
710 }
711 if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
712 $file_record = array(
713 'contextid' => $newcontextid,
714 'component' => $component,
715 'filearea' => $filearea,
716 'itemid' => $rec->newitemid,
717 'filepath' => $file->filepath,
718 'filename' => $file->filename,
719 'timecreated' => $file->timecreated,
720 'timemodified'=> $file->timemodified,
84cdf7de 721 'userid' => $file->userid,
2df0f295 722 'author' => $file->author,
84cdf7de
EL
723 'license' => $file->license,
724 'sortorder' => $file->sortorder);
67233725
DC
725 if ($isreference) {
726 $fs->create_file_from_reference($file_record, $file->repositoryid, $file->reference);
727 } else {
728 $fs->create_file_from_pathname($file_record, $backuppath);
729 }
2df0f295
EL
730 }
731 }
732 $rs->close();
733 }
734
482aac65
EL
735 /**
736 * Given one restoreid, create in DB all the users present
737 * in backup_ids having newitemid = 0, as far as
738 * precheck_included_users() have left them there
739 * ready to be created. Also, annotate their newids
740 * once created for later reference
741 */
ac6dc09c 742 public static function create_included_users($basepath, $restoreid, $userid) {
482aac65
EL
743 global $CFG, $DB;
744
745 $authcache = array(); // Cache to get some bits from authentication plugins
746 $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search later
747 $themes = get_list_of_themes(); // Get themes for quick search later
748
749 // Iterate over all the included users with newitemid = 0, have to create them
750 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid');
751 foreach ($rs as $recuser) {
752 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
753
754 // if user lang doesn't exist here, use site default
755 if (!array_key_exists($user->lang, $languages)) {
756 $user->lang = $CFG->lang;
757 }
758
759 // if user theme isn't available on target site or they are disabled, reset theme
760 if (!empty($user->theme)) {
761 if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) {
762 $user->theme = '';
763 }
764 }
765
766 // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id
767 // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual
768 if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
769 // Respect registerauth
770 if ($CFG->registerauth == 'email') {
771 $user->auth = 'email';
772 } else {
773 $user->auth = 'manual';
774 }
775 }
776 unset($user->mnethosturl); // Not needed anymore
777
778 // Disable pictures based on global setting
779 if (!empty($CFG->disableuserimages)) {
780 $user->picture = 0;
781 }
782
783 // We need to analyse the AUTH field to recode it:
784 // - if the auth isn't enabled in target site, $CFG->registerauth will decide
785 // - finally, if the auth resulting isn't enabled, default to 'manual'
786 if (!is_enabled_auth($user->auth)) {
787 if ($CFG->registerauth == 'email') {
788 $user->auth = 'email';
789 } else {
790 $user->auth = 'manual';
791 }
792 }
793 if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled
794 $user->auth = 'manual';
795 }
796
797 // Now that we know the auth method, for users to be created without pass
798 // if password handling is internal and reset password is available
799 // we set the password to "restored" (plain text), so the login process
800 // will know how to handle that situation in order to allow the user to
801 // recover the password. MDL-20846
802 if (empty($user->password)) { // Only if restore comes without password
803 if (!array_key_exists($user->auth, $authcache)) { // Not in cache
804 $userauth = new stdClass();
805 $authplugin = get_auth_plugin($user->auth);
806 $userauth->preventpassindb = $authplugin->prevent_local_passwords();
807 $userauth->isinternal = $authplugin->is_internal();
808 $userauth->canresetpwd = $authplugin->can_reset_password();
809 $authcache[$user->auth] = $userauth;
810 } else {
811 $userauth = $authcache[$user->auth]; // Get from cache
812 }
813
814 // Most external plugins do not store passwords locally
815 if (!empty($userauth->preventpassindb)) {
816 $user->password = 'not cached';
817
818 // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
819 } else if ($userauth->isinternal and $userauth->canresetpwd) {
820 $user->password = 'restored';
821 }
822 }
823
824 // Creating new user, we must reset the policyagreed always
825 $user->policyagreed = 0;
826
827 // Set time created if empty
828 if (empty($user->timecreated)) {
829 $user->timecreated = time();
830 }
831
832 // Done, let's create the user and annotate its id
833 $newuserid = $DB->insert_record('user', $user);
834 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid);
835 // Let's create the user context and annotate it (we need it for sure at least for files)
1acad8ee
EL
836 // but for deleted users that don't have a context anymore (MDL-30192). We are done for them
837 // and nothing else (custom fields, prefs, tags, files...) will be created.
838 if (empty($user->deleted)) {
839 $newuserctxid = $user->deleted ? 0 : get_context_instance(CONTEXT_USER, $newuserid)->id;
840 self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid);
841
842 // Process custom fields
843 if (isset($user->custom_fields)) { // if present in backup
844 foreach($user->custom_fields['custom_field'] as $udata) {
845 $udata = (object)$udata;
846 // If the profile field has data and the profile shortname-datatype is defined in server
847 if ($udata->field_data) {
848 if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) {
849 /// Insert the user_custom_profile_field
850 $rec = new stdClass();
851 $rec->userid = $newuserid;
852 $rec->fieldid = $field->id;
853 $rec->data = $udata->field_data;
854 $DB->insert_record('user_info_data', $rec);
855 }
482aac65
EL
856 }
857 }
858 }
482aac65 859
1acad8ee
EL
860 // Process tags
861 if (!empty($CFG->usetags) && isset($user->tags)) { // if enabled in server and present in backup
862 $tags = array();
863 foreach($user->tags['tag'] as $usertag) {
864 $usertag = (object)$usertag;
865 $tags[] = $usertag->rawname;
866 }
867 tag_set('user', $newuserid, $tags);
482aac65 868 }
482aac65 869
1acad8ee
EL
870 // Process preferences
871 if (isset($user->preferences)) { // if present in backup
872 foreach($user->preferences['preference'] as $preference) {
873 $preference = (object)$preference;
874 // Prepare the record and insert it
875 $preference->userid = $newuserid;
876 $status = $DB->insert_record('user_preferences', $preference);
877 }
482aac65 878 }
482aac65 879
1acad8ee
EL
880 // Create user files in pool (profile, icon, private) by context
881 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon', $recuser->parentitemid, $userid);
882 restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile', $recuser->parentitemid, $userid);
1acad8ee 883 }
482aac65
EL
884 }
885 $rs->close();
886 }
887
888 /**
889 * Given one user object (from backup file), perform all the neccesary
890 * checks is order to decide how that user will be handled on restore.
891 *
892 * Note the function requires $user->mnethostid to be already calculated
893 * so it's caller responsibility to set it
894 *
895 * This function is used both by @restore_precheck_users() and
896 * @restore_create_users() to get consistent results in both places
897 *
898 * It returns:
899 * - one user object (from DB), if match has been found and user will be remapped
900 * - boolean true if the user needs to be created
901 * - boolean false if some conflict happened and the user cannot be handled
902 *
903 * Each test is responsible for returning its results and interrupt
904 * execution. At the end, boolean true (user needs to be created) will be
905 * returned if no test has interrupted that.
906 *
907 * Here it's the logic applied, keep it updated:
908 *
909 * If restoring users from same site backup:
910 * 1A - Normal check: If match by id and username and mnethost => ok, return target user
911 * 1B - Handle users deleted in DB and "alive" in backup file:
912 * If match by id and mnethost and user is deleted in DB and
913 * (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user
914 * 1C - Handle users deleted in backup file and "alive" in DB:
915 * If match by id and mnethost and user is deleted in backup file
916 * and match by email = email_without_time(backup_email) => ok, return target user
917 * 1D - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false
918 * 1E - None of the above, return true => User needs to be created
919 *
920 * if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination):
921 * 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user
922 * 2B - Handle users deleted in DB and "alive" in backup file:
923 * 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
924 * (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
925 * 2B2 - If match by mnethost and user is deleted in DB and
926 * username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
927 * (to cover situations were md5(username) wasn't implemented on delete we requiere both)
928 * 2C - Handle users deleted in backup file and "alive" in DB:
929 * If match mnethost and user is deleted in backup file
930 * and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
931 * 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
932 * 2E - None of the above, return true => User needs to be created
933 *
934 * Note: for DB deleted users email is stored in username field, hence we
935 * are looking there for emails. See delete_user()
936 * Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
937 * hence we are looking there for usernames if not empty. See delete_user()
938 */
939 protected static function precheck_user($user, $samesite) {
940 global $CFG, $DB;
941
942 // Handle checks from same site backups
943 if ($samesite && empty($CFG->forcedifferentsitecheckingusersonrestore)) {
944
945 // 1A - If match by id and username and mnethost => ok, return target user
946 if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
947 return $rec; // Matching user found, return it
948 }
949
950 // 1B - Handle users deleted in DB and "alive" in backup file
951 // Note: for DB deleted users email is stored in username field, hence we
952 // are looking there for emails. See delete_user()
953 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
954 // hence we are looking there for usernames if not empty. See delete_user()
955 // If match by id and mnethost and user is deleted in DB and
956 // match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user
957 if ($rec = $DB->get_record_sql("SELECT *
958 FROM {user} u
959 WHERE id = ?
960 AND mnethostid = ?
961 AND deleted = 1
962 AND (
ef6b3ba1 963 UPPER(username) LIKE UPPER(?)
482aac65
EL
964 OR (
965 ".$DB->sql_isnotempty('user', 'email', false, false)."
966 AND email = ?
967 )
968 )",
969 array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) {
970 return $rec; // Matching user, deleted in DB found, return it
971 }
972
973 // 1C - Handle users deleted in backup file and "alive" in DB
974 // If match by id and mnethost and user is deleted in backup file
975 // and match by email = email_without_time(backup_email) => ok, return target user
976 if ($user->deleted) {
977 // Note: for DB deleted users email is stored in username field, hence we
978 // are looking there for emails. See delete_user()
979 // Trim time() from email
980 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
981 if ($rec = $DB->get_record_sql("SELECT *
982 FROM {user} u
983 WHERE id = ?
984 AND mnethostid = ?
ef6b3ba1 985 AND UPPER(email) = UPPER(?)",
482aac65
EL
986 array($user->id, $user->mnethostid, $trimemail))) {
987 return $rec; // Matching user, deleted in backup file found, return it
988 }
989 }
990
991 // 1D - If match by username and mnethost and doesn't match by id => conflict, return false
992 if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
993 if ($user->id != $rec->id) {
994 return false; // Conflict, username already exists and belongs to another id
995 }
996 }
997
998 // Handle checks from different site backups
999 } else {
1000
1001 // 2A - If match by username and mnethost and
1002 // (email or non-zero firstaccess) => ok, return target user
1003 if ($rec = $DB->get_record_sql("SELECT *
1004 FROM {user} u
1005 WHERE username = ?
1006 AND mnethostid = ?
1007 AND (
ef6b3ba1 1008 UPPER(email) = UPPER(?)
482aac65
EL
1009 OR (
1010 firstaccess != 0
1011 AND firstaccess = ?
1012 )
1013 )",
1014 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
1015 return $rec; // Matching user found, return it
1016 }
1017
1018 // 2B - Handle users deleted in DB and "alive" in backup file
1019 // Note: for DB deleted users email is stored in username field, hence we
1020 // are looking there for emails. See delete_user()
1021 // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
1022 // hence we are looking there for usernames if not empty. See delete_user()
1023 // 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
1024 // (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
1025 if ($rec = $DB->get_record_sql("SELECT *
1026 FROM {user} u
1027 WHERE mnethostid = ?
1028 AND deleted = 1
1029 AND ".$DB->sql_isnotempty('user', 'email', false, false)."
1030 AND email = ?
1031 AND (
ef6b3ba1 1032 UPPER(username) LIKE UPPER(?)
482aac65
EL
1033 OR (
1034 firstaccess != 0
1035 AND firstaccess = ?
1036 )
1037 )",
1038 array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) {
1039 return $rec; // Matching user found, return it
1040 }
1041
1042 // 2B2 - If match by mnethost and user is deleted in DB and
1043 // username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
1044 // (this covers situations where md5(username) wasn't being stored so we require both
1045 // the email & non-zero firstaccess to match)
1046 if ($rec = $DB->get_record_sql("SELECT *
1047 FROM {user} u
1048 WHERE mnethostid = ?
1049 AND deleted = 1
ef6b3ba1 1050 AND UPPER(username) LIKE UPPER(?)
482aac65
EL
1051 AND firstaccess != 0
1052 AND firstaccess = ?",
1053 array($user->mnethostid, $user->email.'.%', $user->firstaccess))) {
1054 return $rec; // Matching user found, return it
1055 }
1056
1057 // 2C - Handle users deleted in backup file and "alive" in DB
1058 // If match mnethost and user is deleted in backup file
1059 // and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
1060 if ($user->deleted) {
1061 // Note: for DB deleted users email is stored in username field, hence we
1062 // are looking there for emails. See delete_user()
1063 // Trim time() from email
1064 $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
1065 if ($rec = $DB->get_record_sql("SELECT *
1066 FROM {user} u
1067 WHERE mnethostid = ?
ef6b3ba1 1068 AND UPPER(email) = UPPER(?)
482aac65
EL
1069 AND firstaccess != 0
1070 AND firstaccess = ?",
1071 array($user->mnethostid, $trimemail, $user->firstaccess))) {
1072 return $rec; // Matching user, deleted in backup file found, return it
1073 }
1074 }
1075
1076 // 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
1077 if ($rec = $DB->get_record_sql("SELECT *
1078 FROM {user} u
1079 WHERE username = ?
1080 AND mnethostid = ?
1081 AND NOT (
ef6b3ba1 1082 UPPER(email) = UPPER(?)
482aac65
EL
1083 OR (
1084 firstaccess != 0
1085 AND firstaccess = ?
1086 )
1087 )",
1088 array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
1089 return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess)
1090 }
1091 }
1092
1093 // Arrived here, return true as the user will need to be created and no
1094 // conflicts have been found in the logic above. This covers:
1095 // 1E - else => user needs to be created, return true
1096 // 2E - else => user needs to be created, return true
1097 return true;
1098 }
1099
1100 /**
1101 * Check all the included users, deciding the action to perform
1102 * for each one (mapping / creation) and returning one array
1103 * of problems in case something is wrong (lack of permissions,
1104 * conficts)
1105 */
1106 public static function precheck_included_users($restoreid, $courseid, $userid, $samesite) {
1107 global $CFG, $DB;
1108
1109 // To return any problem found
1110 $problems = array();
1111
1112 // We are going to map mnethostid, so load all the available ones
1113 $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id');
1114
1115 // Calculate the context we are going to use for capability checking
1116 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1117
1118 // Calculate if we have perms to create users, by checking:
1119 // to 'moodle/restore:createuser' and 'moodle/restore:userinfo'
1120 // and also observe $CFG->disableusercreationonrestore
1121 $cancreateuser = false;
1122 if (has_capability('moodle/restore:createuser', $context, $userid) and
1123 has_capability('moodle/restore:userinfo', $context, $userid) and
1124 empty($CFG->disableusercreationonrestore)) { // Can create users
1125
1126 $cancreateuser = true;
1127 }
1128
1129 // Iterate over all the included users
1130 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user'), '', 'itemid');
1131 foreach ($rs as $recuser) {
1132 $user = (object)self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
1133
1134 // Find the correct mnethostid for user before performing any further check
1135 if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
1136 $user->mnethostid = $CFG->mnet_localhost_id;
1137 } else {
1138 // fast url-to-id lookups
1139 if (isset($mnethosts[$user->mnethosturl])) {
1140 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
1141 } else {
1142 $user->mnethostid = $CFG->mnet_localhost_id;
1143 }
1144 }
1145
1146 // Now, precheck that user and, based on returned results, annotate action/problem
1147 $usercheck = self::precheck_user($user, $samesite);
1148
1149 if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to
1150 // Annotate it, for later process. Set newitemid to mapping user->id
1151 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $usercheck->id);
1152
1153 } else if ($usercheck === false) { // Found conflict, report it as problem
1154 $problems[] = get_string('restoreuserconflict', '', $user->username);
1155
1156 } else if ($usercheck === true) { // User needs to be created, check if we are able
1157 if ($cancreateuser) { // Can create user, set newitemid to 0 so will be created later
1158 self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, 0, null, (array)$user);
1159
1160 } else { // Cannot create user, report it as problem
1161 $problems[] = get_string('restorecannotcreateuser', '', $user->username);
1162 }
1163
1164 } else { // Shouldn't arrive here ever, something is for sure wrong. Exception
1165 throw new restore_dbops_exception('restore_error_processing_user', $user->username);
1166 }
1167 }
1168 $rs->close();
1169 return $problems;
1170 }
1171
1172 /**
41941110
EL
1173 * Process the needed users in order to decide
1174 * which action to perform with them (create/map)
482aac65
EL
1175 *
1176 * Just wrap over precheck_included_users(), returning
41941110 1177 * exception if any problem is found
482aac65
EL
1178 */
1179 public static function process_included_users($restoreid, $courseid, $userid, $samesite) {
1180 global $DB;
1181
1182 // Just let precheck_included_users() to do all the hard work
1183 $problems = self::precheck_included_users($restoreid, $courseid, $userid, $samesite);
1184
1185 // With problems, throw exception, shouldn't happen if prechecks were originally
1186 // executed, so be radical here.
1187 if (!empty($problems)) {
1188 throw new restore_dbops_exception('restore_problems_processing_users', null, implode(', ', $problems));
1189 }
482aac65
EL
1190 }
1191
41941110
EL
1192 /**
1193 * Process the needed question categories and questions
1194 * to check all them, deciding about the action to perform
1195 * (create/map) and target.
1196 *
1197 * Just wrap over precheck_categories_and_questions(), returning
1198 * exception if any problem is found
1199 */
1200 public static function process_categories_and_questions($restoreid, $courseid, $userid, $samesite) {
1201 global $DB;
1202
1203 // Just let precheck_included_users() to do all the hard work
1204 $problems = self::precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite);
1205
1206 // With problems of type error, throw exception, shouldn't happen if prechecks were originally
1207 // executed, so be radical here.
1208 if (array_key_exists('errors', $problems)) {
ede7105f 1209 throw new restore_dbops_exception('restore_problems_processing_questions', null, implode(', ', $problems['errors']));
41941110
EL
1210 }
1211 }
1212
b8bb45b0
EL
1213 public static function set_backup_files_record($restoreid, $filerec) {
1214 global $DB;
1215
67233725 1216 // Store external files info in `info` field
b8bb45b0
EL
1217 $filerec->info = base64_encode(serialize($filerec)); // Serialize the whole rec in info
1218 $filerec->backupid = $restoreid;
1219 $DB->insert_record('backup_files_temp', $filerec);
1220 }
1221
482aac65
EL
1222
1223 public static function set_backup_ids_record($restoreid, $itemname, $itemid, $newitemid = 0, $parentitemid = null, $info = null) {
1224 global $DB;
1225
1226 // Build the basic (mandatory) record info
1227 $record = array(
1228 'backupid' => $restoreid,
1229 'itemname' => $itemname,
1230 'itemid' => $itemid
1231 );
1232 // Build conditionally the extra record info
1233 $extrarecord = array();
1234 if ($newitemid != 0) {
1235 $extrarecord['newitemid'] = $newitemid;
1236 }
1237 if ($parentitemid != null) {
1238 $extrarecord['parentitemid'] = $parentitemid;
1239 }
1240 if ($info != null) {
1241 $extrarecord['info'] = base64_encode(serialize($info));
1242 }
1243
1244 // TODO: Analyze if some static (and limited) cache by the 3 params could save us a bunch of get_record() calls
1245 // Note: Sure it will! And also will improve getter
1246 if (!$dbrec = $DB->get_record('backup_ids_temp', $record)) { // Need to insert the complete record
1247 $DB->insert_record('backup_ids_temp', array_merge($record, $extrarecord));
1248
1249 } else { // Need to update the extra record info if there is something to
1250 if (!empty($extrarecord)) {
1251 $extrarecord['id'] = $dbrec->id;
1252 $DB->update_record('backup_ids_temp', $extrarecord);
1253 }
1254 }
1255 }
1256
1257 public static function get_backup_ids_record($restoreid, $itemname, $itemid) {
1258 global $DB;
1259
1260 // Build the basic (mandatory) record info to look for
1261 $record = array(
1262 'backupid' => $restoreid,
1263 'itemname' => $itemname,
1264 'itemid' => $itemid
1265 );
1266 // TODO: Analyze if some static (and limited) cache by the 3 params could save us a bunch of get_record() calls
1267 if ($dbrec = $DB->get_record('backup_ids_temp', $record)) {
1268 if ($dbrec->info != null) {
1269 $dbrec->info = unserialize(base64_decode($dbrec->info));
1270 }
1271 }
1272 return $dbrec;
1273 }
4bca307a
EL
1274
1275 /**
1276 * Given on courseid, fullname and shortname, calculate the correct fullname/shortname to avoid dupes
1277 */
1278 public static function calculate_course_names($courseid, $fullname, $shortname) {
1279 global $CFG, $DB;
1280
1281 $currentfullname = '';
1282 $currentshortname = '';
1283 $counter = 0;
1284 // Iteratere while the name exists
1285 do {
1286 if ($counter) {
1287 $suffixfull = ' ' . get_string('copyasnoun') . ' ' . $counter;
1288 $suffixshort = '_' . $counter;
1289 } else {
1290 $suffixfull = '';
1291 $suffixshort = '';
1292 }
1293 $currentfullname = $fullname.$suffixfull;
1294 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; // < 100cc
1295 $coursefull = $DB->get_record_select('course', 'fullname = ? AND id != ?', array($currentfullname, $courseid));
1296 $courseshort = $DB->get_record_select('course', 'shortname = ? AND id != ?', array($currentshortname, $courseid));
1297 $counter++;
1298 } while ($coursefull || $courseshort);
1299
1300 // Return results
1301 return array($currentfullname, $currentshortname);
1302 }
1303
1304 /**
1305 * For the target course context, put as many custom role names as possible
1306 */
1307 public static function set_course_role_names($restoreid, $courseid) {
1308 global $DB;
1309
1310 // Get the course context
1311 $coursectx = get_context_instance(CONTEXT_COURSE, $courseid);
1312 // Get all the mapped roles we have
1313 $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid');
1314 foreach ($rs as $recrole) {
1315 // Get the complete temp_ids record
1316 $role = (object)self::get_backup_ids_record($restoreid, 'role', $recrole->itemid);
024c288d
EL
1317 // If it's one mapped role and we have one name for it
1318 if (!empty($role->newitemid) && !empty($role->info['nameincourse'])) {
4bca307a
EL
1319 // If role name doesn't exist, add it
1320 $rolename = new stdclass();
1321 $rolename->roleid = $role->newitemid;
1322 $rolename->contextid = $coursectx->id;
1323 if (!$DB->record_exists('role_names', (array)$rolename)) {
1324 $rolename->name = $role->info['nameincourse'];
1325 $DB->insert_record('role_names', $rolename);
1326 }
1327 }
1328 }
1329 $rs->close();
1330 }
785d6603 1331
3acc9b81
SH
1332 /**
1333 * Creates a skeleton record within the database using the passed parameters
1334 * and returns the new course id.
1335 *
1336 * @global moodle_database $DB
1337 * @param string $fullname
1338 * @param string $shortname
1339 * @param int $categoryid
1340 * @return int The new course id
1341 */
785d6603
SH
1342 public static function create_new_course($fullname, $shortname, $categoryid) {
1343 global $DB;
1344 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1345
1346 $course = new stdClass;
1347 $course->fullname = $fullname;
1348 $course->shortname = $shortname;
1349 $course->category = $category->id;
1350 $course->sortorder = 0;
1351 $course->timecreated = time();
1352 $course->timemodified = $course->timecreated;
ed6a14eb
AB
1353 // forcing skeleton courses to be hidden instead of going by $category->visible , until MDL-27790 is resolved.
1354 $course->visible = 0;
785d6603 1355
593fc4a9
SH
1356 $courseid = $DB->insert_record('course', $course);
1357
1358 $category->coursecount++;
1359 $DB->update_record('course_categories', $category);
1360
1361 return $courseid;
785d6603
SH
1362 }
1363
3acc9b81
SH
1364 /**
1365 * Deletes all of the content associated with the given course (courseid)
1366 * @param int $courseid
d53e3298 1367 * @param array $options
3acc9b81
SH
1368 * @return bool True for success
1369 */
d53e3298
PS
1370 public static function delete_course_content($courseid, array $options = null) {
1371 return remove_course_contents($courseid, false, $options);
785d6603 1372 }
482aac65 1373}
fbc2778d
EL
1374
1375/*
1376 * Exception class used by all the @dbops stuff
1377 */
1378class restore_dbops_exception extends backup_exception {
1379
1380 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
1381 parent::__construct($errorcode, 'error', '', $a, null, $debuginfo);
1382 }
1383}