PageRenderTime 30ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/backup/util/dbops/restore_dbops.class.php

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