PageRenderTime 66ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/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

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. 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->a

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