PageRenderTime 143ms CodeModel.GetById 17ms RepoModel.GetById 2ms 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
  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 the new contextid and the new itemid in case we need to remap
  930. // references to this file later
  931. $DB->update_record('backup_files_temp', array(
  932. 'id' => $rec->bftid,
  933. 'newcontextid' => $newcontextid,
  934. 'newitemid' => $rec->newitemid), true);
  935. } else {
  936. // this is an alias - we can't create it yet so we stash it in a temp
  937. // table and will let the final task to deal with it
  938. if (!$fs->file_exists($newcontextid, $component, $filearea, $rec->newitemid, $file->filepath, $file->filename)) {
  939. $info = new stdClass();
  940. // oldfile holds the raw information stored in MBZ (including reference-related info)
  941. $info->oldfile = $file;
  942. // newfile holds the info for the new file_record with the context, user and itemid mapped
  943. $info->newfile = (object) $file_record;
  944. restore_dbops::set_backup_ids_record($restoreid, 'file_aliases_queue', $file->id, 0, null, $info);
  945. }
  946. }
  947. }
  948. $rs->close();
  949. return $results;
  950. }
  951. /**
  952. * Returns suitable entry to include in log when there is a missing file.
  953. *
  954. * @param stdClass $file File definition
  955. * @return stdClass Log entry
  956. */
  957. protected static function get_missing_file_result($file) {
  958. $result = new stdClass();
  959. $result->code = 'file_missing_in_backup';
  960. $result->message = 'Missing file in backup: ' . $file->filepath . $file->filename .
  961. ' (old context ' . $file->contextid . ', component ' . $file->component .
  962. ', filearea ' . $file->filearea . ', old itemid ' . $file->itemid . ')';
  963. $result->level = backup::LOG_WARNING;
  964. return $result;
  965. }
  966. /**
  967. * Given one restoreid, create in DB all the users present
  968. * in backup_ids having newitemid = 0, as far as
  969. * precheck_included_users() have left them there
  970. * ready to be created. Also, annotate their newids
  971. * once created for later reference.
  972. *
  973. * This function will start and end a new progress section in the progress
  974. * object.
  975. *
  976. * @param string $basepath Base path of unzipped backup
  977. * @param string $restoreid Restore ID
  978. * @param int $userid Default userid for files
  979. * @param core_backup_progress $progress Object used for progress tracking
  980. */
  981. public static function create_included_users($basepath, $restoreid, $userid,
  982. core_backup_progress $progress) {
  983. global $CFG, $DB;
  984. $progress->start_progress('Creating included users');
  985. $authcache = array(); // Cache to get some bits from authentication plugins
  986. $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search later
  987. $themes = get_list_of_themes(); // Get themes for quick search later
  988. // Iterate over all the included users with newitemid = 0, have to create them
  989. $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid, info');
  990. foreach ($rs as $recuser) {
  991. $progress->progress();
  992. $user = (object)backup_controller_dbops::decode_backup_temp_info($recuser->info);
  993. // if user lang doesn't exist here, use site default
  994. if (!array_key_exists($user->lang, $languages)) {
  995. $user->lang = $CFG->lang;
  996. }
  997. // if user theme isn't available on target site or they are disabled, reset theme
  998. if (!empty($user->theme)) {
  999. if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) {
  1000. $user->theme = '';
  1001. }
  1002. }
  1003. // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id
  1004. // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual
  1005. if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
  1006. // Respect registerauth
  1007. if ($CFG->registerauth == 'email') {
  1008. $user->auth = 'email';
  1009. } else {
  1010. $user->auth = 'manual';
  1011. }
  1012. }
  1013. unset($user->mnethosturl); // Not needed anymore
  1014. // Disable pictures based on global setting
  1015. if (!empty($CFG->disableuserimages)) {
  1016. $user->picture = 0;
  1017. }
  1018. // We need to analyse the AUTH field to recode it:
  1019. // - if the auth isn't enabled in target site, $CFG->registerauth will decide
  1020. // - finally, if the auth resulting isn't enabled, default to 'manual'
  1021. if (!is_enabled_auth($user->auth)) {
  1022. if ($CFG->registerauth == 'email') {
  1023. $user->auth = 'email';
  1024. } else {
  1025. $user->auth = 'manual';
  1026. }
  1027. }
  1028. if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled
  1029. $user->auth = 'manual';
  1030. }
  1031. // Now that we know the auth method, for users to be created without pass
  1032. // if password handling is internal and reset password is available
  1033. // we set the password to "restored" (plain text), so the login process
  1034. // will know how to handle that situation in order to allow the user to
  1035. // recover the password. MDL-20846
  1036. if (empty($user->password)) { // Only if restore comes without password
  1037. if (!array_key_exists($user->auth, $authcache)) { // Not in cache
  1038. $userauth = new stdClass();
  1039. $authplugin = get_auth_plugin($user->auth);
  1040. $userauth->preventpassindb = $authplugin->prevent_local_passwords();
  1041. $userauth->isinternal = $authplugin->is_internal();
  1042. $userauth->canresetpwd = $authplugin->can_reset_password();
  1043. $authcache[$user->auth] = $userauth;
  1044. } else {
  1045. $userauth = $authcache[$user->auth]; // Get from cache
  1046. }
  1047. // Most external plugins do not store passwords locally
  1048. if (!empty($userauth->preventpassindb)) {
  1049. $user->password = AUTH_PASSWORD_NOT_CACHED;
  1050. // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
  1051. } else if ($userauth->isinternal and $userauth->canresetpwd) {
  1052. $user->password = 'restored';
  1053. }
  1054. }
  1055. // Creating new user, we must reset the policyagreed always
  1056. $user->policyagreed = 0;
  1057. // Set time created if empty
  1058. if (empty($user->timecreated)) {
  1059. $user->timecreated = time();
  1060. }
  1061. // Done, let's create the user and annotate its id
  1062. $newuserid = $DB->insert_record('user', $user);
  1063. self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid);
  1064. // Let's create the user context and annotate it (we need it for sure at least for files)
  1065. // but for deleted users that don't have a context anymore (MDL-30192). We are done for them
  1066. // and nothing else (custom fields, prefs, tags, files...) will be created.
  1067. if (empty($user->deleted)) {
  1068. $newuserctxid = $user->deleted ? 0 : context_user::instance($newuserid)->id;
  1069. self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid);
  1070. // Process custom fields
  1071. if (isset($user->custom_fields)) { // if present in backup
  1072. foreach($user->custom_fields['custom_field'] as $udata) {
  1073. $udata = (object)$udata;
  1074. // If the profile field has data and the profile shortname-datatype is defined in server
  1075. if ($udata->field_data) {
  1076. if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) {
  1077. /// Insert the user_custom_profile_field
  1078. $rec = new stdClass();
  1079. $rec->userid = $newuserid;
  1080. $rec->fieldid = $field->id;
  1081. $rec->data = $udata->field_data;
  1082. $DB->insert_record('user_info_data', $rec);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. // Process tags
  1088. if (!empty($CFG->usetags) && isset($user->tags)) { // if enabled in server and present in backup
  1089. $tags = array();
  1090. foreach($user->tags['tag'] as $usertag) {
  1091. $usertag = (object)$usertag;
  1092. $tags[] = $usertag->rawname;
  1093. }
  1094. tag_set('user', $newuserid, $tags);
  1095. }
  1096. // Process preferences
  1097. if (isset($user->preferences)) { // if present in backup
  1098. foreach($user->preferences['preference'] as $preference) {
  1099. $preference = (object)$preference;
  1100. // Prepare the record and insert it
  1101. $preference->userid = $newuserid;
  1102. $status = $DB->insert_record('user_preferences', $preference);
  1103. }
  1104. }
  1105. // Special handling for htmleditor which was converted to a preference.
  1106. if (isset($user->htmleditor)) {
  1107. if ($user->htmleditor == 0) {
  1108. $preference = new stdClass();
  1109. $preference->userid = $newuserid;
  1110. $preference->name = 'htmleditor';
  1111. $preference->value = 'textarea';
  1112. $status = $DB->insert_record('user_preferences', $preference);
  1113. }
  1114. }
  1115. // Create user files in pool (profile, icon, private) by context
  1116. restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon',
  1117. $recuser->parentitemid, $userid, null, null, null, false, $progress);
  1118. restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile',
  1119. $recuser->parentitemid, $userid, null, null, null, false, $progress);
  1120. }
  1121. }
  1122. $rs->close();
  1123. $progress->end_progress();
  1124. }
  1125. /**
  1126. * Given one user object (from backup file), perform all the neccesary
  1127. * checks is order to decide how that user will be handled on restore.
  1128. *
  1129. * Note the function requires $user->mnethostid to be already calculated
  1130. * so it's caller responsibility to set it
  1131. *
  1132. * This function is used both by @restore_precheck_users() and
  1133. * @restore_create_users() to get consistent results in both places
  1134. *
  1135. * It returns:
  1136. * - one user object (from DB), if match has been found and user will be remapped
  1137. * - boolean true if the user needs to be created
  1138. * - boolean false if some conflict happened and the user cannot be handled
  1139. *
  1140. * Each test is responsible for returning its results and interrupt
  1141. * execution. At the end, boolean true (user needs to be created) will be
  1142. * returned if no test has interrupted that.
  1143. *
  1144. * Here it's the logic applied, keep it updated:
  1145. *
  1146. * If restoring users from same site backup:
  1147. * 1A - Normal check: If match by id and username and mnethost => ok, return target user
  1148. * 1B - If restoring an 'anonymous' user (created via the 'Anonymize user information' option) try to find a
  1149. * match by username only => ok, return target user MDL-31484
  1150. * 1C - Handle users deleted in DB and "alive" in backup file:
  1151. * If match by id and mnethost and user is deleted in DB and
  1152. * (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user
  1153. * 1D - Handle users deleted in backup file and "alive" in DB:
  1154. * If match by id and mnethost and user is deleted in backup file
  1155. * and match by email = email_without_time(backup_email) => ok, return target user
  1156. * 1E - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false
  1157. * 1F - None of the above, return true => User needs to be created
  1158. *
  1159. * if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination):
  1160. * 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user
  1161. * 2B - Handle users deleted in DB and "alive" in backup file:
  1162. * 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
  1163. * (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
  1164. * 2B2 - If match by mnethost and user is deleted in DB and
  1165. * username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
  1166. * (to cover situations were md5(username) wasn't implemented on delete we requiere both)
  1167. * 2C - Handle users deleted in backup file and "alive" in DB:
  1168. * If match mnethost and user is deleted in backup file
  1169. * and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
  1170. * 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
  1171. * 2E - None of the above, return true => User needs to be created
  1172. *
  1173. * Note: for DB deleted users email is stored in username field, hence we
  1174. * are looking there for emails. See delete_user()
  1175. * Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
  1176. * hence we are looking there for usernames if not empty. See delete_user()
  1177. */
  1178. protected static function precheck_user($user, $samesite) {
  1179. global $CFG, $DB;
  1180. // Handle checks from same site backups
  1181. if ($samesite && empty($CFG->forcedifferentsitecheckingusersonrestore)) {
  1182. // 1A - If match by id and username and mnethost => ok, return target user
  1183. if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
  1184. return $rec; // Matching user found, return it
  1185. }
  1186. // 1B - If restoring an 'anonymous' user (created via the 'Anonymize user information' option) try to find a
  1187. // match by username only => ok, return target user MDL-31484
  1188. // This avoids username / id mis-match problems when restoring subsequent anonymized backups.
  1189. if (backup_anonymizer_helper::is_anonymous_user($user)) {
  1190. if ($rec = $DB->get_record('user', array('username' => $user->username))) {
  1191. return $rec; // Matching anonymous user found - return it
  1192. }
  1193. }
  1194. // 1C - Handle users deleted in DB and "alive" in backup file
  1195. // Note: for DB deleted users email is stored in username field, hence we
  1196. // are looking there for emails. See delete_user()
  1197. // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
  1198. // hence we are looking there for usernames if not empty. See delete_user()
  1199. // If match by id and mnethost and user is deleted in DB and
  1200. // match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user
  1201. if ($rec = $DB->get_record_sql("SELECT *
  1202. FROM {user} u
  1203. WHERE id = ?
  1204. AND mnethostid = ?
  1205. AND deleted = 1
  1206. AND (
  1207. UPPER(username) LIKE UPPER(?)
  1208. OR (
  1209. ".$DB->sql_isnotempty('user', 'email', false, false)."
  1210. AND email = ?
  1211. )
  1212. )",
  1213. array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) {
  1214. return $rec; // Matching user, deleted in DB found, return it
  1215. }
  1216. // 1D - Handle users deleted in backup file and "alive" in DB
  1217. // If match by id and mnethost and user is deleted in backup file
  1218. // and match by email = email_without_time(backup_email) => ok, return target user
  1219. if ($user->deleted) {
  1220. // Note: for DB deleted users email is stored in username field, hence we
  1221. // are looking there for emails. See delete_user()
  1222. // Trim time() from email
  1223. $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
  1224. if ($rec = $DB->get_record_sql("SELECT *
  1225. FROM {user} u
  1226. WHERE id = ?
  1227. AND mnethostid = ?
  1228. AND UPPER(email) = UPPER(?)",
  1229. array($user->id, $user->mnethostid, $trimemail))) {
  1230. return $rec; // Matching user, deleted in backup file found, return it
  1231. }
  1232. }
  1233. // 1E - If match by username and mnethost and doesn't match by id => conflict, return false
  1234. if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
  1235. if ($user->id != $rec->id) {
  1236. return false; // Conflict, username already exists and belongs to another id
  1237. }
  1238. }
  1239. // Handle checks from different site backups
  1240. } else {
  1241. // 2A - If match by username and mnethost and
  1242. // (email or non-zero firstaccess) => ok, return target user
  1243. if ($rec = $DB->get_record_sql("SELECT *
  1244. FROM {user} u
  1245. WHERE username = ?
  1246. AND mnethostid = ?
  1247. AND (
  1248. UPPER(email) = UPPER(?)
  1249. OR (
  1250. firstaccess != 0
  1251. AND firstaccess = ?
  1252. )
  1253. )",
  1254. array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
  1255. return $rec; // Matching user found, return it
  1256. }
  1257. // 2B - Handle users deleted in DB and "alive" in backup file
  1258. // Note: for DB deleted users email is stored in username field, hence we
  1259. // are looking there for emails. See delete_user()
  1260. // Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
  1261. // hence we are looking there for usernames if not empty. See delete_user()
  1262. // 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
  1263. // (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
  1264. if ($rec = $DB->get_record_sql("SELECT *
  1265. FROM {user} u
  1266. WHERE mnethostid = ?
  1267. AND deleted = 1
  1268. AND ".$DB->sql_isnotempty('user', 'email', false, false)."
  1269. AND email = ?
  1270. AND (
  1271. UPPER(username) LIKE UPPER(?)
  1272. OR (
  1273. firstaccess != 0
  1274. AND firstaccess = ?
  1275. )
  1276. )",
  1277. array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) {
  1278. return $rec; // Matching user found, return it
  1279. }
  1280. // 2B2 - If match by mnethost and user is deleted in DB and
  1281. // username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
  1282. // (this covers situations where md5(username) wasn't being stored so we require both
  1283. // the email & non-zero firstaccess to match)
  1284. if ($rec = $DB->get_record_sql("SELECT *
  1285. FROM {user} u
  1286. WHERE mnethostid = ?
  1287. AND deleted = 1
  1288. AND UPPER(username) LIKE UPPER(?)
  1289. AND firstaccess != 0
  1290. AND firstaccess = ?",
  1291. array($user->mnethostid, $user->email.'.%', $user->firstaccess))) {
  1292. return $rec; // Matching user found, return it
  1293. }
  1294. // 2C - Handle users deleted in backup file and "alive" in DB
  1295. // If match mnethost and user is deleted in backup file
  1296. // and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
  1297. if ($user->deleted) {
  1298. // Note: for DB deleted users email is stored in username field, hence we
  1299. // are looking there for emails. See delete_user()
  1300. // Trim time() from email
  1301. $trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
  1302. if ($rec = $DB->get_record_sql("SELECT *
  1303. FROM {user} u
  1304. WHERE mnethostid = ?
  1305. AND UPPER(email) = UPPER(?)
  1306. AND firstaccess != 0
  1307. AND firstaccess = ?",
  1308. array($user->mnethostid, $trimemail, $user->firstaccess))) {
  1309. return $rec; // Matching user, deleted in backup file found, return it
  1310. }
  1311. }
  1312. // 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
  1313. if ($rec = $DB->get_record_sql("SELECT *
  1314. FROM {user} u
  1315. WHERE username = ?
  1316. AND mnethostid = ?
  1317. AND NOT (
  1318. UPPER(email) = UPPER(?)
  1319. OR (
  1320. firstaccess != 0
  1321. AND firstaccess = ?
  1322. )
  1323. )",
  1324. array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
  1325. return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess)
  1326. }
  1327. }
  1328. // Arrived here, return true as the user will need to be created and no
  1329. // conflicts have been found in the logic above. This covers:
  1330. // 1E - else => user needs to be created, return true
  1331. // 2E - else => user needs to be created, return true
  1332. return true;
  1333. }
  1334. /**
  1335. * Check all the included users, deciding the action to perform
  1336. * for each one (mapping / creation) and returning one array
  1337. * of problems in case something is wrong (lack of permissions,
  1338. * conficts)
  1339. *
  1340. * @param string $restoreid Restore id
  1341. * @param int $courseid Course id
  1342. * @param int $userid User id
  1343. * @param bool $samesite True if restore is to same site
  1344. * @param core_backup_progress $progress Progress reporter
  1345. */
  1346. public static function precheck_included_users($restoreid, $courseid, $userid, $samesite,
  1347. core_backup_progress $progress) {
  1348. global $CFG, $DB;
  1349. // To return any problem found
  1350. $problems = array();
  1351. // We are going to map mnethostid, so load all the available ones
  1352. $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id');
  1353. // Calculate the context we are going to use for capability checking
  1354. $context = context_course::instance($courseid);
  1355. // Calculate if we have perms to create users, by checking:
  1356. // to 'moodle/restore:createuser' and 'moodle/restore:userinfo'
  1357. // and also observe $CFG->disableusercreationonrestore
  1358. $cancreateuser = false;
  1359. if (has_capability('moodle/restore:createuser', $context, $userid) and
  1360. has_capability('moodle/restore:userinfo', $context, $userid) and
  1361. empty($CFG->disableusercreationonrestore)) { // Can create users
  1362. $cancreateuser = true;
  1363. }
  1364. // Prepare for reporting progress.
  1365. $conditions = array('backupid' => $restoreid, 'itemname' => 'user');
  1366. $max = $DB->count_records('backup_ids_temp', $conditions);
  1367. $done = 0;
  1368. $progress->start_progress('Checking users', $max);
  1369. // Iterate over all the included users
  1370. $rs = $DB->get_recordset('backup_ids_temp', $conditions, '', 'itemid, info');
  1371. foreach ($rs as $recuser) {
  1372. $user = (object)backup_controller_dbops::decode_backup_temp_info($recuser->info);
  1373. // Find the correct mnethostid for user before performing any further check
  1374. if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
  1375. $user->mnethostid = $CFG->mnet_localhost_id;
  1376. } else {
  1377. // fast url-to-id lookups
  1378. if (isset($mnethosts[$user->mnethosturl])) {
  1379. $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
  1380. } else {
  1381. $user->mnethostid = $CFG->mnet_localhost_id;
  1382. }
  1383. }
  1384. // Now, precheck that user and, based on returned results, annotate action/problem
  1385. $usercheck = self::precheck_user($user, $samesite);
  1386. if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to
  1387. // Annotate it, for later process. Set newitemid to mapping user->id
  1388. self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $usercheck->id);
  1389. } else if ($usercheck === false) { // Found conflict, report it as problem
  1390. $problems[] = get_string('restoreuserconflict', '', $user->username);
  1391. } else if ($usercheck === true) { // User needs to be created, check if we are able
  1392. if ($cancreateuser) { // Can create user, set newitemid to 0 so will be created later
  1393. self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, 0, null, (array)$user);
  1394. } else { // Cannot create user, report it as problem
  1395. $problems[] = get_string('restorecannotcreateuser', '', $user->username);
  1396. }
  1397. } else { // Shouldn't arrive here ever, something is for sure wrong. Exception
  1398. throw new restore_dbops_exception('restore_error_processing_user', $user->username);
  1399. }
  1400. $done++;
  1401. $progress->progress($done);
  1402. }
  1403. $rs->close();
  1404. $progress->end_progress();
  1405. return $problems;
  1406. }
  1407. /**
  1408. * Process the needed users in order to decide
  1409. * which action to perform with them (create/map)
  1410. *
  1411. * Just wrap over precheck_included_users(), returning
  1412. * exception if any problem is found
  1413. *
  1414. * @param string $restoreid Restore id
  1415. * @param int $courseid Course id
  1416. * @param int $userid User id
  1417. * @param bool $samesite True if restore is to same site
  1418. * @param core_backup_progress $progress Optional progress tracker
  1419. */
  1420. public static function process_included_users($restoreid, $courseid, $userid, $samesite,
  1421. core_backup_progress $progress = null) {
  1422. global $DB;
  1423. // Just let precheck_included_users() to do all the hard work
  1424. $problems = self::precheck_included_users($restoreid, $courseid, $userid, $samesite, $progress);
  1425. // With problems, throw exception, shouldn't happen if prechecks were originally
  1426. // executed, so be radical here.
  1427. if (!empty($problems)) {
  1428. throw new restore_dbops_exception('restore_problems_processing_users', null, implode(', ', $problems));
  1429. }
  1430. }
  1431. /**
  1432. * Process the needed question categories and questions
  1433. * to check all them, deciding about the action to perform
  1434. * (create/map) and target.
  1435. *
  1436. * Just wrap over precheck_categories_and_questions(), returning
  1437. * exception if any problem is found
  1438. */
  1439. public static function process_categories_and_questions($restoreid, $courseid, $userid, $samesite) {
  1440. global $DB;
  1441. // Just let precheck_included_users() to do all the hard work
  1442. $problems = self::precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite);
  1443. // With problems of type error, throw exception, shouldn't happen if prechecks were originally
  1444. // executed, so be radical here.
  1445. if (array_key_exists('errors', $problems)) {
  1446. throw new restore_dbops_exception('restore_problems_processing_questions', null, implode(', ', $problems['errors']));
  1447. }
  1448. }
  1449. public static function set_backup_files_record($restoreid, $filerec) {
  1450. global $DB;
  1451. // Store external files info in `info` field
  1452. $filerec->info = backup_controller_dbops::encode_backup_temp_info($filerec); // Encode the whole record into info.
  1453. $filerec->backupid = $restoreid;
  1454. $DB->insert_record('backup_files_temp', $filerec);
  1455. }
  1456. public static function set_backup_ids_record($restoreid, $itemname, $itemid, $newitemid = 0, $parentitemid = null, $info = null) {
  1457. // Build conditionally the extra record info
  1458. $extrarecord = array();
  1459. if ($newitemid != 0) {
  1460. $extrarecord['newitemid'] = $newitemid;
  1461. }
  1462. if ($parentitemid != null) {
  1463. $extrarecord['parentitemid'] = $parentitemid;
  1464. }
  1465. if ($info != null) {
  1466. $extrarecord['info'] = backup_controller_dbops::encode_backup_temp_info($info);
  1467. }
  1468. self::set_backup_ids_cached($restoreid, $itemname, $itemid, $extrarecord);
  1469. }
  1470. public static function get_backup_ids_record($restoreid, $itemname, $itemid) {
  1471. $dbrec = self::get_backup_ids_cached($restoreid, $itemname, $itemid);
  1472. // We must test if info is a string, as the cache stores info in object form.
  1473. if ($dbrec && isset($dbrec->info) && is_string($dbrec->info)) {
  1474. $dbrec->info = backup_controller_dbops::decode_backup_temp_info($dbrec->info);
  1475. }
  1476. return $dbrec;
  1477. }
  1478. /**
  1479. * Given on courseid, fullname and shortname, calculate the correct fullname/shortname to avoid dupes
  1480. */
  1481. public static function calculate_course_names($courseid, $fullname, $shortname) {
  1482. global $CFG, $DB;
  1483. $currentfullname = '';
  1484. $currentshortname = '';
  1485. $counter = 0;
  1486. // Iteratere while the name exists
  1487. do {
  1488. if ($counter) {
  1489. $suffixfull = ' ' . get_string('copyasnoun') . ' ' . $counter;
  1490. $suffixshort = '_' . $counter;
  1491. } else {
  1492. $suffixfull = '';
  1493. $suffixshort = '';
  1494. }
  1495. $currentfullname = $fullname.$suffixfull;
  1496. $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; // < 100cc
  1497. $coursefull = $DB->get_record_select('course', 'fullname = ? AND id != ?',
  1498. array($currentfullname, $courseid), '*', IGNORE_MULTIPLE);
  1499. $courseshort = $DB->get_record_select('course', 'shortname = ? AND id != ?', array($currentshortname, $courseid));
  1500. $counter++;
  1501. } while ($coursefull || $courseshort);
  1502. // Return results
  1503. return array($currentfullname, $currentshortname);
  1504. }
  1505. /**
  1506. * For the target course context, put as many custom role names as possible
  1507. */
  1508. public static function set_course_role_names($restoreid, $courseid) {
  1509. global $DB;
  1510. // Get the course context
  1511. $coursectx = context_course::instance($courseid);
  1512. // Get all the mapped roles we have
  1513. $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid, info, newitemid');
  1514. foreach ($rs as $recrole) {
  1515. $info = backup_controller_dbops::decode_backup_temp_info($recrole->info);
  1516. // If it's one mapped role and we have one name for it
  1517. if (!empty($recrole->newitemid) && !empty($info['nameincourse'])) {
  1518. // If role name doesn't exist, add it
  1519. $rolename = new stdclass();
  1520. $rolename->roleid = $recrole->newitemid;
  1521. $rolename->contextid = $coursectx->id;
  1522. if (!$DB->record_exists('role_names', (array)$rolename)) {
  1523. $rolename->name = $info['nameincourse'];
  1524. $DB->insert_record('role_names', $rolename);
  1525. }
  1526. }
  1527. }
  1528. $rs->close();
  1529. }
  1530. /**
  1531. * Creates a skeleton record within the database using the passed parameters
  1532. * and returns the new course id.
  1533. *
  1534. * @global moodle_database $DB
  1535. * @param string $fullname
  1536. * @param string $shortname
  1537. * @param int $categoryid
  1538. * @return int The new course id
  1539. */
  1540. public static function create_new_course($fullname, $shortname, $categoryid) {
  1541. global $DB;
  1542. $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
  1543. $course = new stdClass;
  1544. $course->fullname = $fullname;
  1545. $course->shortname = $shortname;
  1546. $course->category = $category->id;
  1547. $course->sortorder = 0;
  1548. $course->timecreated = time();
  1549. $course->timemodified = $course->timecreated;
  1550. // forcing skeleton courses to be hidden instead of going by $category->visible , until MDL-27790 is resolved.
  1551. $course->visible = 0;
  1552. $courseid = $DB->insert_record('course', $course);
  1553. $category->coursecount++;
  1554. $DB->update_record('course_categories', $category);
  1555. return $courseid;
  1556. }
  1557. /**
  1558. * Deletes all of the content associated with the given course (courseid)
  1559. * @param int $courseid
  1560. * @param array $options
  1561. * @return bool True for success
  1562. */
  1563. public static function delete_course_content($courseid, array $options = null) {
  1564. return remove_course_contents($courseid, false, $options);
  1565. }
  1566. }
  1567. /*
  1568. * Exception class used by all the @dbops stuff
  1569. */
  1570. class restore_dbops_exception extends backup_exception {
  1571. public function __construct($errorcode, $a=NULL, $debuginfo=null) {
  1572. parent::__construct($errorcode, 'error', '', $a, null, $debuginfo);
  1573. }
  1574. }