PageRenderTime 61ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/synergylearning/campusconnect
PHP | 1755 lines | 932 code | 181 blank | 642 comment | 196 complexity | ec8a4c1cf373026af2d145f3f1baa1a5 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-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[] = $task;
  96. }
  97. }
  98. return $includedtasks;
  99. }
  100. /**
  101. * Load one inforef.xml file to backup_ids table for future reference
  102. *
  103. * @param string $restoreid Restore id
  104. * @param string $inforeffile File path
  105. * @param core_backup_progress $progress Progress tracker
  106. */
  107. public static function load_inforef_to_tempids($restoreid, $inforeffile,
  108. core_backup_progress $progress = null) {
  109. if (!file_exists($inforeffile)) { // Shouldn't happen ever, but...
  110. throw new backup_helper_exception('missing_inforef_xml_file', $inforeffile);
  111. }
  112. // Set up progress tracking (indeterminate).
  113. if (!$progress) {
  114. $progress = new core_backup_null_progress();
  115. }
  116. $progress->start_progress('Loading inforef.xml file');
  117. // Let's parse, custom processor will do its work, sending info to DB
  118. $xmlparser = new progressive_parser();
  119. $xmlparser->set_file($inforeffile);
  120. $xmlprocessor = new restore_inforef_parser_processor($restoreid);
  121. $xmlparser->set_processor($xmlprocessor);
  122. $xmlparser->set_progress($progress);
  123. $xmlparser->process();
  124. // Finish progress
  125. $progress->end_progress();
  126. }
  127. /**
  128. * Load the needed role.xml file to backup_ids table for future reference
  129. */
  130. public static function load_roles_to_tempids($restoreid, $rolesfile) {
  131. if (!file_exists($rolesfile)) { // Shouldn't happen ever, but...
  132. throw new backup_helper_exception('missing_roles_xml_file', $rolesfile);
  133. }
  134. // Let's parse, custom processor will do its work, sending info to DB
  135. $xmlparser = new progressive_parser();
  136. $xmlparser->set_file($rolesfile);
  137. $xmlprocessor = new restore_roles_parser_processor($restoreid);
  138. $xmlparser->set_processor($xmlprocessor);
  139. $xmlparser->process();
  140. }
  141. /**
  142. * Precheck the loaded roles, return empty array if everything is ok, and
  143. * array with 'errors', 'warnings' elements (suitable to be used by restore_prechecks)
  144. * with any problem found. At the same time, store all the mapping into backup_ids_temp
  145. * and also put the information into $rolemappings (controller->info), so it can be reworked later by
  146. * post-precheck stages while at the same time accept modified info in the same object coming from UI
  147. */
  148. public static function precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings) {
  149. global $DB;
  150. $problems = array(); // To store warnings/errors
  151. // Get loaded roles from backup_ids
  152. $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid, info');
  153. foreach ($rs as $recrole) {
  154. // If the rolemappings->modified flag is set, that means that we are coming from
  155. // manually modified mappings (by UI), so accept those mappings an put them to backup_ids
  156. if ($rolemappings->modified) {
  157. $target = $rolemappings->mappings[$recrole->itemid]->targetroleid;
  158. self::set_backup_ids_record($restoreid, 'role', $recrole->itemid, $target);
  159. // Else, we haven't any info coming from UI, let's calculate the mappings, matching
  160. // in multiple ways and checking permissions. Note mapping to 0 means "skip"
  161. } else {
  162. $role = (object)backup_controller_dbops::decode_backup_temp_info($recrole->info);
  163. $match = self::get_best_assignable_role($role, $courseid, $userid, $samesite);
  164. // Send match to backup_ids
  165. self::set_backup_ids_record($restoreid, 'role', $recrole->itemid, $match);
  166. // Build the rolemappings element for controller
  167. unset($role->id);
  168. unset($role->nameincourse);
  169. $role->targetroleid = $match;
  170. $rolemappings->mappings[$recrole->itemid] = $role;
  171. // Prepare warning if no match found
  172. if (!$match) {
  173. $problems['warnings'][] = get_string('cannotfindassignablerole', 'backup', $role->name);
  174. }
  175. }
  176. }
  177. $rs->close();
  178. return $problems;
  179. }
  180. /**
  181. * Return cached backup id's
  182. *
  183. * @param int $restoreid id of backup
  184. * @param string $itemname name of the item
  185. * @param int $itemid id of item
  186. * @return array backup id's
  187. * @todo MDL-25290 replace static backupids* with MUC code
  188. */
  189. protected static function get_backup_ids_cached($restoreid, $itemname, $itemid) {
  190. global $DB;
  191. $key = "$itemid $itemname $restoreid";
  192. // If record exists in cache then return.
  193. if (isset(self::$backupidsexist[$key]) && isset(self::$backupidscache[$key])) {
  194. // Return a copy of cached data, to avoid any alterations in cached data.
  195. return clone self::$backupidscache[$key];
  196. }
  197. // Clean cache, if it's full.
  198. if (self::$backupidscachesize <= 0) {
  199. // Remove some records, to keep memory in limit.
  200. self::$backupidscache = array_slice(self::$backupidscache, self::$backupidsslice, null, true);
  201. self::$backupidscachesize = self::$backupidscachesize + self::$backupidsslice;
  202. }
  203. if (self::$backupidsexistsize <= 0) {
  204. self::$backupidsexist = array_slice(self::$backupidsexist, self::$backupidsslice, null, true);
  205. self::$backupidsexistsize = self::$backupidsexistsize + self::$backupidsslice;
  206. }
  207. // Retrive record from database.
  208. $record = array(
  209. 'backupid' => $restoreid,
  210. 'itemname' => $itemname,
  211. 'itemid' => $itemid
  212. );
  213. if ($dbrec = $DB->get_record('backup_ids_temp', $record)) {
  214. self::$backupidsexist[$key] = $dbrec->id;
  215. self::$backupidscache[$key] = $dbrec;
  216. self::$backupidscachesize--;
  217. self::$backupidsexistsize--;
  218. return $dbrec;
  219. } else {
  220. return false;
  221. }
  222. }
  223. /**
  224. * Cache backup ids'
  225. *
  226. * @param int $restoreid id of backup
  227. * @param string $itemname name of the item
  228. * @param int $itemid id of item
  229. * @param array $extrarecord extra record which needs to be updated
  230. * @return void
  231. * @todo MDL-25290 replace static BACKUP_IDS_* with MUC code
  232. */
  233. protected static function set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord) {
  234. global $DB;
  235. $key = "$itemid $itemname $restoreid";
  236. $record = array(
  237. 'backupid' => $restoreid,
  238. 'itemname' => $itemname,
  239. 'itemid' => $itemid,
  240. );
  241. // If record is not cached then add one.
  242. if (!isset(self::$backupidsexist[$key])) {
  243. // If we have this record in db, then just update this.
  244. if ($existingrecord = $DB->get_record('backup_ids_temp', $record)) {
  245. self::$backupidsexist[$key] = $existingrecord->id;
  246. self::$backupidsexistsize--;
  247. self::update_backup_cached_record($record, $extrarecord, $key, $existingrecord);
  248. } else {
  249. // Add new record to cache and db.
  250. $recorddefault = array (
  251. 'newitemid' => 0,
  252. 'parentitemid' => null,
  253. 'info' => null);
  254. $record = array_merge($record, $recorddefault, $extrarecord);
  255. $record['id'] = $DB->insert_record('backup_ids_temp', $record);
  256. self::$backupidsexist[$key] = $record['id'];
  257. self::$backupidsexistsize--;
  258. if (self::$backupidscachesize > 0) {
  259. // Cache new records if we haven't got many yet.
  260. self::$backupidscache[$key] = (object) $record;
  261. self::$backupidscachesize--;
  262. }
  263. }
  264. } else {
  265. self::update_backup_cached_record($record, $extrarecord, $key);
  266. }
  267. }
  268. /**
  269. * Updates existing backup record
  270. *
  271. * @param array $record record which needs to be updated
  272. * @param array $extrarecord extra record which needs to be updated
  273. * @param string $key unique key which is used to identify cached record
  274. * @param stdClass $existingrecord (optional) existing record
  275. */
  276. protected static function update_backup_cached_record($record, $extrarecord, $key, $existingrecord = null) {
  277. global $DB;
  278. // Update only if extrarecord is not empty.
  279. if (!empty($extrarecord)) {
  280. $extrarecord['id'] = self::$backupidsexist[$key];
  281. $DB->update_record('backup_ids_temp', $extrarecord);
  282. // Update existing cache or add new record to cache.
  283. if (isset(self::$backupidscache[$key])) {
  284. $record = array_merge((array)self::$backupidscache[$key], $extrarecord);
  285. self::$backupidscache[$key] = (object) $record;
  286. } else if (self::$backupidscachesize > 0) {
  287. if ($existingrecord) {
  288. self::$backupidscache[$key] = $existingrecord;
  289. } else {
  290. // Retrive record from database and cache updated records.
  291. self::$backupidscache[$key] = $DB->get_record('backup_ids_temp', $record);
  292. }
  293. $record = array_merge((array)self::$backupidscache[$key], $extrarecord);
  294. self::$backupidscache[$key] = (object) $record;
  295. self::$backupidscachesize--;
  296. }
  297. }
  298. }
  299. /**
  300. * Reset the ids caches completely
  301. *
  302. * Any destructive operation (partial delete, truncate, drop or recreate) performed
  303. * with the backup_ids table must cause the backup_ids caches to be
  304. * invalidated by calling this method. See MDL-33630.
  305. *
  306. * Note that right now, the only operation of that type is the recreation
  307. * (drop & restore) of the table that may happen once the prechecks have ended. All
  308. * the rest of operations are always routed via {@link set_backup_ids_record()}, 1 by 1,
  309. * keeping the caches on sync.
  310. *
  311. * @todo MDL-25290 static should be replaced with MUC code.
  312. */
  313. public static function reset_backup_ids_cached() {
  314. // Reset the ids cache.
  315. $cachetoadd = count(self::$backupidscache);
  316. self::$backupidscache = array();
  317. self::$backupidscachesize = self::$backupidscachesize + $cachetoadd;
  318. // Reset the exists cache.
  319. $existstoadd = count(self::$backupidsexist);
  320. self::$backupidsexist = array();
  321. self::$backupidsexistsize = self::$backupidsexistsize + $existstoadd;
  322. }
  323. /**
  324. * Given one role, as loaded from XML, perform the best possible matching against the assignable
  325. * roles, using different fallback alternatives (shortname, archetype, editingteacher => teacher, defaultcourseroleid)
  326. * returning the id of the best matching role or 0 if no match is found
  327. */
  328. protected static function get_best_assignable_role($role, $courseid, $userid, $samesite) {
  329. global $CFG, $DB;
  330. // Gather various information about roles
  331. $coursectx = context_course::instance($courseid);
  332. $assignablerolesshortname = get_assignable_roles($coursectx, ROLENAME_SHORT, false, $userid);
  333. // Note: under 1.9 we had one function restore_samerole() that performed one complete
  334. // matching of roles (all caps) and if match was found the mapping was availabe bypassing
  335. // any assignable_roles() security. IMO that was wrong and we must not allow such
  336. // mappings anymore. So we have left that matching strategy out in 2.0
  337. // Empty assignable roles, mean no match possible
  338. if (empty($assignablerolesshortname)) {
  339. return 0;
  340. }
  341. // Match by shortname
  342. if ($match = array_search($role->shortname, $assignablerolesshortname)) {
  343. return $match;
  344. }
  345. // Match by archetype
  346. list($in_sql, $in_params) = $DB->get_in_or_equal(array_keys($assignablerolesshortname));
  347. $params = array_merge(array($role->archetype), $in_params);
  348. if ($rec = $DB->get_record_select('role', "archetype = ? AND id $in_sql", $params, 'id', IGNORE_MULTIPLE)) {
  349. return $rec->id;
  350. }
  351. // Match editingteacher to teacher (happens a lot, from 1.9)
  352. if ($role->shortname == 'editingteacher' && in_array('teacher', $assignablerolesshortname)) {
  353. return array_search('teacher', $assignablerolesshortname);
  354. }
  355. // No match, return 0
  356. return 0;
  357. }
  358. /**
  359. * Process the loaded roles, looking for their best mapping or skipping
  360. * Any error will cause exception. Note this is one wrapper over
  361. * precheck_included_roles, that contains all the logic, but returns
  362. * errors/warnings instead and is executed as part of the restore prechecks
  363. */
  364. public static function process_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings) {
  365. global $DB;
  366. // Just let precheck_included_roles() to do all the hard work
  367. $problems = self::precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings);
  368. // With problems of type error, throw exception, shouldn't happen if prechecks executed
  369. if (array_key_exists('errors', $problems)) {
  370. throw new restore_dbops_exception('restore_problems_processing_roles', null, implode(', ', $problems['errors']));
  371. }
  372. }
  373. /**
  374. * Load the needed users.xml file to backup_ids table for future reference
  375. *
  376. * @param string $restoreid Restore id
  377. * @param string $usersfile File path
  378. * @param core_backup_progress $progress Progress tracker
  379. */
  380. public static function load_users_to_tempids($restoreid, $usersfile,
  381. core_backup_progress $progress = null) {
  382. if (!file_exists($usersfile)) { // Shouldn't happen ever, but...
  383. throw new backup_helper_exception('missing_users_xml_file', $usersfile);
  384. }
  385. // Set up progress tracking (indeterminate).
  386. if (!$progress) {
  387. $progress = new core_backup_null_progress();
  388. }
  389. $progress->start_progress('Loading users into temporary table');
  390. // Let's parse, custom processor will do its work, sending info to DB
  391. $xmlparser = new progressive_parser();
  392. $xmlparser->set_file($usersfile);
  393. $xmlprocessor = new restore_users_parser_processor($restoreid);
  394. $xmlparser->set_processor($xmlprocessor);
  395. $xmlparser->set_progress($progress);
  396. $xmlparser->process();
  397. // Finish progress.
  398. $progress->end_progress();
  399. }
  400. /**
  401. * Load the needed questions.xml file to backup_ids table for future reference
  402. */
  403. public static function load_categories_and_questions_to_tempids($restoreid, $questionsfile) {
  404. if (!file_exists($questionsfile)) { // Shouldn't happen ever, but...
  405. throw new backup_helper_exception('missing_questions_xml_file', $questionsfile);
  406. }
  407. // Let's parse, custom processor will do its work, sending info to DB
  408. $xmlparser = new progressive_parser();
  409. $xmlparser->set_file($questionsfile);
  410. $xmlprocessor = new restore_questions_parser_processor($restoreid);
  411. $xmlparser->set_processor($xmlprocessor);
  412. $xmlparser->process();
  413. }
  414. /**
  415. * Check all the included categories and questions, deciding the action to perform
  416. * for each one (mapping / creation) and returning one array of problems in case
  417. * something is wrong.
  418. *
  419. * There are some basic rules that the method below will always try to enforce:
  420. *
  421. * Rule1: Targets will be, always, calculated for *whole* question banks (a.k.a. contexid source),
  422. * so, given 2 question categories belonging to the same bank, their target bank will be
  423. * always the same. If not, we can be incurring into "fragmentation", leading to random/cloze
  424. * problems (qtypes having "child" questions).
  425. *
  426. * Rule2: The 'moodle/question:managecategory' and 'moodle/question:add' capabilities will be
  427. * checked before creating any category/question respectively and, if the cap is not allowed
  428. * into upper contexts (system, coursecat)) but in lower ones (course), the *whole* question bank
  429. * will be created there.
  430. *
  431. * Rule3: Coursecat question banks not existing in the target site will be created as course
  432. * (lower ctx) question banks, never as "guessed" coursecat question banks base on depth or so.
  433. *
  434. * Rule4: System question banks will be created at system context if user has perms to do so. Else they
  435. * will created as course (lower ctx) question banks (similary to rule3). In other words, course ctx
  436. * if always a fallback for system and coursecat question banks.
  437. *
  438. * Also, there are some notes to clarify the scope of this method:
  439. *
  440. * Note1: This method won't create any question category nor question at all. It simply will calculate
  441. * which actions (create/map) must be performed for each element and where, validating that all those
  442. * actions are doable by the user executing the restore operation. Any problem found will be
  443. * returned in the problems array, causing the restore process to stop with error.
  444. *
  445. * Note2: To decide if one question bank (all its question categories and questions) is going to be remapped,
  446. * then all the categories and questions must exist in the same target bank. If able to do so, missing
  447. * qcats and qs will be created (rule2). But if, at the end, something is missing, the whole question bank
  448. * will be recreated at course ctx (rule1), no matter if that duplicates some categories/questions.
  449. *
  450. * Note3: We'll be using the newitemid column in the temp_ids table to store the action to be performed
  451. * with each question category and question. newitemid = 0 means the qcat/q needs to be created and
  452. * any other value means the qcat/q is mapped. Also, for qcats, parentitemid will contain the target
  453. * context where the categories have to be created (but for module contexts where we'll keep the old
  454. * one until the activity is created)
  455. *
  456. * Note4: All these "actions" will be "executed" later by {@link restore_create_categories_and_questions}
  457. */
  458. public static function precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite) {
  459. $problems = array();
  460. // TODO: Check all qs, looking their qtypes are restorable
  461. // Precheck all qcats and qs looking for target contexts / warnings / errors
  462. list($syserr, $syswarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_SYSTEM);
  463. list($caterr, $catwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_COURSECAT);
  464. list($couerr, $couwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_COURSE);
  465. list($moderr, $modwarn) = self::prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, CONTEXT_MODULE);
  466. // Acummulate and handle errors and warnings
  467. $errors = array_merge($syserr, $caterr, $couerr, $moderr);
  468. $warnings = array_merge($syswarn, $catwarn, $couwarn, $modwarn);
  469. if (!empty($errors)) {
  470. $problems['errors'] = $errors;
  471. }
  472. if (!empty($warnings)) {
  473. $problems['warnings'] = $warnings;
  474. }
  475. return $problems;
  476. }
  477. /**
  478. * This function will process all the question banks present in restore
  479. * at some contextlevel (from CONTEXT_SYSTEM to CONTEXT_MODULE), finding
  480. * the target contexts where each bank will be restored and returning
  481. * warnings/errors as needed.
  482. *
  483. * Some contextlevels (system, coursecat), will delegate process to
  484. * course level if any problem is found (lack of permissions, non-matching
  485. * target context...). Other contextlevels (course, module) will
  486. * cause return error if some problem is found.
  487. *
  488. * At the end, if no errors were found, all the categories in backup_temp_ids
  489. * will be pointing (parentitemid) to the target context where they must be
  490. * created later in the restore process.
  491. *
  492. * Note: at the time these prechecks are executed, activities haven't been
  493. * created yet so, for CONTEXT_MODULE banks, we keep the old contextid
  494. * in the parentitemid field. Once the activity (and its context) has been
  495. * created, we'll update that context in the required qcats
  496. *
  497. * Caller {@link precheck_categories_and_questions} will, simply, execute
  498. * this function for all the contextlevels, acting as a simple controller
  499. * of warnings and errors.
  500. *
  501. * The function returns 2 arrays, one containing errors and another containing
  502. * warnings. Both empty if no errors/warnings are found.
  503. */
  504. public static function prechek_precheck_qbanks_by_level($restoreid, $courseid, $userid, $samesite, $contextlevel) {
  505. global $CFG, $DB;
  506. // To return any errors and warnings found
  507. $errors = array();
  508. $warnings = array();
  509. // Specify which fallbacks must be performed
  510. $fallbacks = array(
  511. CONTEXT_SYSTEM => CONTEXT_COURSE,
  512. CONTEXT_COURSECAT => CONTEXT_COURSE);
  513. // For any contextlevel, follow this process logic:
  514. //
  515. // 0) Iterate over each context (qbank)
  516. // 1) Iterate over each qcat in the context, matching by stamp for the found target context
  517. // 2a) No match, check if user can create qcat and q
  518. // 3a) User can, mark the qcat and all dependent qs to be created in that target context
  519. // 3b) User cannot, check if we are in some contextlevel with fallback
  520. // 4a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
  521. // 4b) No fallback, error. End qcat loop.
  522. // 2b) Match, mark qcat to be mapped and iterate over each q, matching by stamp and version
  523. // 5a) No match, check if user can add q
  524. // 6a) User can, mark the q to be created
  525. // 6b) User cannot, check if we are in some contextlevel with fallback
  526. // 7a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
  527. // 7b) No fallback, error. End qcat loop
  528. // 5b) Match, mark q to be mapped
  529. // Get all the contexts (question banks) in restore for the given contextlevel
  530. $contexts = self::restore_get_question_banks($restoreid, $contextlevel);
  531. // 0) Iterate over each context (qbank)
  532. foreach ($contexts as $contextid => $contextlevel) {
  533. // Init some perms
  534. $canmanagecategory = false;
  535. $canadd = false;
  536. // get categories in context (bank)
  537. $categories = self::restore_get_question_categories($restoreid, $contextid);
  538. // cache permissions if $targetcontext is found
  539. if ($targetcontext = self::restore_find_best_target_context($categories, $courseid, $contextlevel)) {
  540. $canmanagecategory = has_capability('moodle/question:managecategory', $targetcontext, $userid);
  541. $canadd = has_capability('moodle/question:add', $targetcontext, $userid);
  542. }
  543. // 1) Iterate over each qcat in the context, matching by stamp for the found target context
  544. foreach ($categories as $category) {
  545. $matchcat = false;
  546. if ($targetcontext) {
  547. $matchcat = $DB->get_record('question_categories', array(
  548. 'contextid' => $targetcontext->id,
  549. 'stamp' => $category->stamp));
  550. }
  551. // 2a) No match, check if user can create qcat and q
  552. if (!$matchcat) {
  553. // 3a) User can, mark the qcat and all dependent qs to be created in that target context
  554. if ($canmanagecategory && $canadd) {
  555. // Set parentitemid to targetcontext, BUT for CONTEXT_MODULE categories, where
  556. // we keep the source contextid unmodified (for easier matching later when the
  557. // activities are created)
  558. $parentitemid = $targetcontext->id;
  559. if ($contextlevel == CONTEXT_MODULE) {
  560. $parentitemid = null; // null means "not modify" a.k.a. leave original contextid
  561. }
  562. self::set_backup_ids_record($restoreid, 'question_category', $category->id, 0, $parentitemid);
  563. // Nothing else to mark, newitemid = 0 means create
  564. // 3b) User cannot, check if we are in some contextlevel with fallback
  565. } else {
  566. // 4a) There is fallback, move ALL the qcats to fallback, warn. End qcat loop
  567. if (array_key_exists($contextlevel, $fallbacks)) {
  568. foreach ($categories as $movedcat) {
  569. $movedcat->contextlevel = $fallbacks[$contextlevel];
  570. self::set_backup_ids_record($restoreid, 'question_category', $movedcat->id, 0, $contextid, $movedcat);
  571. // Warn about the performed fallback
  572. $warnings[] = get_string('qcategory2coursefallback', 'backup', $movedcat);
  573. }
  574. // 4b) No fallback, error. End qcat loop.
  575. } else {
  576. $errors[] = get_string('qcategorycannotberestored', 'backup', $category);
  577. }
  578. break; // out from qcat loop (both 4a and 4b), we have decided about ALL categories in context (bank)
  579. }
  580. // 2b) Match, mark qcat to be mapped and iterate over each q, matching by stamp and version
  581. } else {
  582. self::set_backup_ids_record($restoreid, 'question_category', $category->id, $matchcat->id, $targetcontext->id);
  583. $questions = self::restore_get_questions($restoreid, $category->id);
  584. // Collect all the questions for this category into memory so we only talk to the DB once.
  585. $questioncache = $DB->get_records_sql_menu("SELECT ".$DB->sql_concat('stamp', "' '", 'version').", id
  586. FROM {question}
  587. WHERE category = ?", array($matchcat->id));
  588. foreach ($questions as $question) {
  589. if (isset($questioncache[$question->stamp." ".$question->version])) {
  590. $matchqid = $questioncache[$question->stamp." ".$question->version];
  591. } else {
  592. $matchqid = false;
  593. }
  594. // 5a) No match, check if user can add q
  595. if (!$matchqid) {
  596. // 6a) User can, mark the q to be created
  597. if ($canadd) {
  598. // Nothing to mark, newitemid means create
  599. // 6b) User cannot, check if we are in some contextlevel with fallback
  600. } else {
  601. // 7a) There is fallback, move ALL the qcats to fallback, warn. End qcat loo
  602. if (array_key_exists($contextlevel, $fallbacks)) {
  603. foreach ($categories as $movedcat) {
  604. $movedcat->contextlevel = $fallbacks[$contextlevel];
  605. self::set_backup_ids_record($restoreid, 'question_category', $movedcat->id, 0, $contextid, $movedcat);
  606. // Warn about the performed fallback
  607. $warnings[] = get_string('question2coursefallback', 'backup', $movedcat);
  608. }
  609. // 7b) No fallback, error. End qcat loop
  610. } else {
  611. $errors[] = get_string('questioncannotberestored', 'backup', $question);
  612. }
  613. break 2; // out from qcat loop (both 7a and 7b), we have decided about ALL categories in context (bank)
  614. }
  615. // 5b) Match, mark q to be mapped
  616. } else {
  617. self::set_backup_ids_record($restoreid, 'question', $question->id, $matchqid);
  618. }
  619. }
  620. }
  621. }
  622. }
  623. return array($errors, $warnings);
  624. }
  625. /**
  626. * Return one array of contextid => contextlevel pairs
  627. * of question banks to be checked for one given restore operation
  628. * ordered from CONTEXT_SYSTEM downto CONTEXT_MODULE
  629. * If contextlevel is specified, then only banks corresponding to
  630. * that level are returned
  631. */
  632. public static function restore_get_question_banks($restoreid, $contextlevel = null) {
  633. global $DB;
  634. $results = array();
  635. $qcats = $DB->get_recordset_sql("SELECT itemid, parentitemid AS contextid, info
  636. FROM {backup_ids_temp}
  637. WHERE backupid = ?
  638. AND itemname = 'question_category'", array($restoreid));
  639. foreach ($qcats as $qcat) {
  640. // If this qcat context haven't been acummulated yet, do that
  641. if (!isset($results[$qcat->contextid])) {
  642. $info = backup_controller_dbops::decode_backup_temp_info($qcat->info);
  643. // Filter by contextlevel if necessary
  644. if (is_null($contextlevel) || $contextlevel == $info->contextlevel) {
  645. $results[$qcat->contextid] = $info->contextlevel;
  646. }
  647. }
  648. }
  649. $qcats->close();
  650. // Sort by value (contextlevel from CONTEXT_SYSTEM downto CONTEXT_MODULE)
  651. asort($results);
  652. return $results;
  653. }
  654. /**
  655. * Return one array of question_category records for
  656. * a given restore operation and one restore context (question bank)
  657. */
  658. public static function restore_get_question_categories($restoreid, $contextid) {
  659. global $DB;
  660. $results = array();
  661. $qcats = $DB->get_recordset_sql("SELECT itemid, info
  662. FROM {backup_ids_temp}
  663. WHERE backupid = ?
  664. AND itemname = 'question_category'
  665. AND parentitemid = ?", array($restoreid, $contextid));
  666. foreach ($qcats as $qcat) {
  667. $results[$qcat->itemid] = backup_controller_dbops::decode_backup_temp_info($qcat->info);
  668. }
  669. $qcats->close();
  670. return $results;
  671. }
  672. /**
  673. * Calculates the best context found to restore one collection of qcats,
  674. * al them belonging to the same context (question bank), returning the
  675. * target context found (object) or false
  676. */
  677. public static function restore_find_best_target_context($categories, $courseid, $contextlevel) {
  678. global $DB;
  679. $targetcontext = false;
  680. // Depending of $contextlevel, we perform different actions
  681. switch ($contextlevel) {
  682. // For system is easy, the best context is the system context
  683. case CONTEXT_SYSTEM:
  684. $targetcontext = context_system::instance();
  685. break;
  686. // For coursecat, we are going to look for stamps in all the
  687. // course categories between CONTEXT_SYSTEM and CONTEXT_COURSE
  688. // (i.e. in all the course categories in the path)
  689. //
  690. // And only will return one "best" target context if all the
  691. // matches belong to ONE and ONLY ONE context. If multiple
  692. // matches are found, that means that there is some annoying
  693. // qbank "fragmentation" in the categories, so we'll fallback
  694. // to create the qbank at course level
  695. case CONTEXT_COURSECAT:
  696. // Build the array of stamps we are going to match
  697. $stamps = array();
  698. foreach ($categories as $category) {
  699. $stamps[] = $category->stamp;
  700. }
  701. $contexts = array();
  702. // Build the array of contexts we are going to look
  703. $systemctx = context_system::instance();
  704. $coursectx = context_course::instance($courseid);
  705. $parentctxs = $coursectx->get_parent_context_ids();
  706. foreach ($parentctxs as $parentctx) {
  707. // Exclude system context
  708. if ($parentctx == $systemctx->id) {
  709. continue;
  710. }
  711. $contexts[] = $parentctx;
  712. }
  713. if (!empty($stamps) && !empty($contexts)) {
  714. // Prepare the query
  715. list($stamp_sql, $stamp_params) = $DB->get_in_or_equal($stamps);
  716. list($context_sql, $context_params) = $DB->get_in_or_equal($contexts);
  717. $sql = "SELECT contextid
  718. FROM {question_categories}
  719. WHERE stamp $stamp_sql
  720. AND contextid $context_sql";
  721. $params = array_merge($stamp_params, $context_params);
  722. $matchingcontexts = $DB->get_records_sql($sql, $params);
  723. // Only if ONE and ONLY ONE context is found, use it as valid target
  724. if (count($matchingcontexts) == 1) {
  725. $targetcontext = context::instance_by_id(reset($matchingcontexts)->contextid);
  726. }
  727. }
  728. break;
  729. // For course is easy, the best context is the course context
  730. case CONTEXT_COURSE:
  731. $targetcontext = context_course::instance($courseid);
  732. break;
  733. // For module is easy, there is not best context, as far as the
  734. // activity hasn't been created yet. So we return context course
  735. // for them, so permission checks and friends will work. Note this
  736. // case is handled by {@link prechek_precheck_qbanks_by_level}
  737. // in an special way
  738. case CONTEXT_MODULE:
  739. $targetcontext = context_course::instance($courseid);
  740. break;
  741. }
  742. return $targetcontext;
  743. }
  744. /**
  745. * Return one array of question records for
  746. * a given restore operation and one question category
  747. */
  748. public static function restore_get_questions($restoreid, $qcatid) {
  749. global $DB;
  750. $results = array();
  751. $qs = $DB->get_recordset_sql("SELECT itemid, info
  752. FROM {backup_ids_temp}
  753. WHERE backupid = ?
  754. AND itemname = 'question'
  755. AND parentitemid = ?", array($restoreid, $qcatid));
  756. foreach ($qs as $q) {
  757. $results[$q->itemid] = backup_controller_dbops::decode_backup_temp_info($q->info);
  758. }
  759. $qs->close();
  760. return $results;
  761. }
  762. /**
  763. * Given one component/filearea/context and
  764. * optionally one source itemname to match itemids
  765. * put the corresponding files in the pool
  766. *
  767. * If you specify a progress reporter, it will get called once per file with
  768. * indeterminate progress.
  769. *
  770. * @param string $basepath the full path to the root of unzipped backup file
  771. * @param string $restoreid the restore job's identification
  772. * @param string $component
  773. * @param string $filearea
  774. * @param int $oldcontextid
  775. * @param int $dfltuserid default $file->user if the old one can't be mapped
  776. * @param string|null $itemname
  777. * @param int|null $olditemid
  778. * @param int|null $forcenewcontextid explicit value for the new contextid (skip mapping)
  779. * @param bool $skipparentitemidctxmatch
  780. * @param core_backup_progress $progress Optional progress reporter
  781. * @return array of result object
  782. */
  783. public static function send_files_to_pool($basepath, $restoreid, $component, $filearea,
  784. $oldcontextid, $dfltuserid, $itemname = null, $olditemid = null,
  785. $forcenewcontextid = null, $skipparentitemidctxmatch = false,
  786. core_backup_progress $progress = null) {
  787. global $DB, $CFG;
  788. $backupinfo = backup_general_helper::get_backup_information(basename($basepath));
  789. $includesfiles = $backupinfo->include_files;
  790. $results = array();
  791. if ($forcenewcontextid) {
  792. // Some components can have "forced" new contexts (example: questions can end belonging to non-standard context mappings,
  793. // with questions originally at system/coursecat context in source being restored to course context in target). So we need
  794. // to be able to force the new contextid
  795. $newcontextid = $forcenewcontextid;
  796. } else {
  797. // Get new context, must exist or this will fail
  798. $newcontextrecord = self::get_backup_ids_record($restoreid, 'context', $oldcontextid);
  799. if (!$newcontextrecord || !$newcontextrecord->newitemid) {
  800. throw new restore_dbops_exception('unknown_context_mapping', $oldcontextid);
  801. }
  802. $newcontextid = $newcontextrecord->newitemid;
  803. }
  804. // Sometimes it's possible to have not the oldcontextids stored into backup_ids_temp->parentitemid
  805. // columns (because we have used them to store other information). This happens usually with
  806. // all the question related backup_ids_temp records. In that case, it's safe to ignore that
  807. // matching as far as we are always restoring for well known oldcontexts and olditemids
  808. $parentitemctxmatchsql = ' AND i.parentitemid = f.contextid ';
  809. if ($skipparentitemidctxmatch) {
  810. $parentitemctxmatchsql = '';
  811. }
  812. // Important: remember how files have been loaded to backup_files_temp
  813. // - info: contains the whole original object (times, names...)
  814. // (all them being original ids as loaded from xml)
  815. // itemname = null, we are going to match only by context, no need to use itemid (all them are 0)
  816. if ($itemname == null) {
  817. $sql = "SELECT id AS bftid, contextid, component, filearea, itemid, itemid AS newitemid, info
  818. FROM {backup_files_temp}
  819. WHERE backupid = ?
  820. AND contextid = ?
  821. AND component = ?
  822. AND filearea = ?";
  823. $params = array($restoreid, $oldcontextid, $component, $filearea);
  824. // itemname not null, going to join with backup_ids to perform the old-new mapping of itemids
  825. } else {
  826. $sql = "SELECT f.id AS bftid, f.contextid, f.component, f.filearea, f.itemid, i.newitemid, f.info
  827. FROM {backup_files_temp} f
  828. JOIN {backup_ids_temp} i ON i.backupid = f.backupid
  829. $parentitemctxmatchsql
  830. AND i.itemid = f.itemid
  831. WHERE f.backupid = ?
  832. AND f.contextid = ?
  833. AND f.component = ?
  834. AND f.filearea = ?
  835. AND i.itemname = ?";
  836. $params = array($restoreid, $oldcontextid, $component, $filearea, $itemname);
  837. if ($olditemid !== null) { // Just process ONE olditemid intead of the whole itemname
  838. $sql .= ' AND i.itemid = ?';
  839. $params[] = $olditemid;
  840. }
  841. }
  842. $fs = get_file_storage(); // Get moodle file storage
  843. $basepath = $basepath . '/files/';// Get backup file pool base
  844. // Report progress before query.
  845. if ($progress) {
  846. $progress->progress();
  847. }
  848. $rs = $DB->get_recordset_sql($sql, $params);
  849. foreach ($rs as $rec) {
  850. // Report progress each time around loop.
  851. if ($progress) {
  852. $progress->progress();
  853. }
  854. $file = (object)backup_controller_dbops::decode_backup_temp_info($rec->info);
  855. // ignore root dirs (they are created automatically)
  856. if ($file->filepath == '/' && $file->filename == '.') {
  857. continue;
  858. }
  859. // set the best possible user
  860. $mappeduser = self::get_backup_ids_record($restoreid, 'user', $file->userid);
  861. $mappeduserid = !empty($mappeduser) ? $mappeduser->newitemid : $dfltuserid;
  862. // dir found (and not root one), let's create it
  863. if ($file->filename == '.') {
  864. $fs->create_directory($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $mappeduserid);
  865. continue;
  866. }
  867. // The file record to restore.
  868. $file_record = array(
  869. 'contextid' => $newcontextid,
  870. 'component' => $component,
  871. 'filearea' => $filearea,
  872. 'itemid' => $rec->newitemid,
  873. 'filepath' => $file->filepath,
  874. 'filename' => $file->filename,
  875. 'timecreated' => $file->timecreated,
  876. 'timemodified'=> $file->timemodified,
  877. 'userid' => $mappeduserid,
  878. 'source' => $file->source,
  879. 'author' => $file->author,
  880. 'license' => $file->license,
  881. 'sortorder' => $file->sortorder
  882. );
  883. if (empty($file->repositoryid)) {
  884. // If contenthash is empty then gracefully skip adding file.
  885. if (empty($file->contenthash)) {
  886. $result = new stdClass();
  887. $result->code = 'file_missing_in_backup';
  888. $result->message = sprintf('missing file (%s) contenthash in backup for component %s', $file->filename, $component);
  889. $result->level = backup::LOG_WARNING;
  890. $results[] = $result;
  891. continue;
  892. }
  893. // this is a regular file, it must be present in the backup pool
  894. $backuppath = $basepath . backup_file_manager::get_backup_content_file_location($file->contenthash);
  895. // Some file types do not include the files as they should already be
  896. // present. We still need to create entries into the files table.
  897. if ($includesfiles) {
  898. // The file is not found in the backup.
  899. if (!file_exists($backuppath)) {
  900. $results[] = self::get_missing_file_result($file);
  901. continue;
  902. }
  903. // create the file in the filepool if it does not exist yet
  904. if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
  905. // If no license found, use default.
  906. if ($file->license == null){
  907. $file->license = $CFG->sitedefaultlicense;
  908. }
  909. $fs->create_file_from_pathname($file_record, $backuppath);
  910. }
  911. } else {
  912. // This backup does not include the files - they should be available in moodle filestorage already.
  913. // Create the file in the filepool if it does not exist yet.
  914. if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
  915. // Even if a file has been deleted since the backup was made, the file metadata will remain in the
  916. // files table, and the file will not be moved to the trashdir.
  917. // Files are not cleared from the files table by cron until several days after deletion.
  918. if ($foundfiles = $DB->get_records('files', array('contenthash' => $file->contenthash), '', '*', 0, 1)) {
  919. // Only grab one of the foundfiles - the file content should be the same for all entries.
  920. $foundfile = reset($foundfiles);
  921. $fs->create_file_from_storedfile($file_record, $foundfile->id);
  922. } else {
  923. // A matching existing file record was not found in the database.
  924. $results[] = self::get_missing_file_result($file);
  925. continue;
  926. }
  927. }
  928. }
  929. // store the t…

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