PageRenderTime 61ms CodeModel.GetById 23ms 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

Large files files are truncated, but you can click here to view the full file

  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, $fi

Large files files are truncated, but you can click here to view the full file