PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

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

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