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