PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/backup/util/helper/backup_general_helper.class.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 312 lines | 195 code | 31 blank | 86 comment | 44 complexity | dcf5580fe1974ac45b6fcd6fe539ffb1 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-helper
  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. defined('MOODLE_INTERNAL') || die();
  23. /**
  24. * Non instantiable helper class providing general helper methods for backup/restore
  25. *
  26. * This class contains various general helper static methods available for backup/restore
  27. *
  28. * TODO: Finish phpdocs
  29. */
  30. abstract class backup_general_helper extends backup_helper {
  31. /**
  32. * Calculate one checksum for any array/object. Works recursively
  33. */
  34. public static function array_checksum_recursive($arr) {
  35. $checksum = ''; // Init checksum
  36. // Check we are going to process one array always, objects must be cast before
  37. if (!is_array($arr)) {
  38. throw new backup_helper_exception('array_expected');
  39. }
  40. foreach ($arr as $key => $value) {
  41. if ($value instanceof checksumable) {
  42. $checksum = md5($checksum . '-' . $key . '-' . $value->calculate_checksum());
  43. } else if (is_object($value)) {
  44. $checksum = md5($checksum . '-' . $key . '-' . self::array_checksum_recursive((array)$value));
  45. } else if (is_array($value)) {
  46. $checksum = md5($checksum . '-' . $key . '-' . self::array_checksum_recursive($value));
  47. } else {
  48. $checksum = md5($checksum . '-' . $key . '-' . $value);
  49. }
  50. }
  51. return $checksum;
  52. }
  53. /**
  54. * Load all the blocks information needed for a given path within moodle2 backup
  55. *
  56. * This function, given one full path (course, activities/xxxx) will look for all the
  57. * blocks existing in the backup file, returning one array used to build the
  58. * proper restore plan by the @restore_plan_builder
  59. */
  60. public static function get_blocks_from_path($path) {
  61. global $DB;
  62. $blocks = array(); // To return results
  63. static $availableblocks = array(); // Get and cache available blocks
  64. if (empty($availableblocks)) {
  65. $availableblocks = array_keys(core_component::get_plugin_list('block'));
  66. }
  67. $path = $path . '/blocks'; // Always look under blocks subdir
  68. if (!is_dir($path)) {
  69. return array();
  70. }
  71. if (!$dir = opendir($path)) {
  72. return array();
  73. }
  74. while (false !== ($file = readdir($dir))) {
  75. if ($file == '.' || $file == '..') { // Skip dots
  76. continue;
  77. }
  78. if (is_dir($path .'/' . $file)) { // Dir found, check it's a valid block
  79. if (!file_exists($path .'/' . $file . '/block.xml')) { // Skip if xml file not found
  80. continue;
  81. }
  82. // Extract block name
  83. $blockname = preg_replace('/(.*)_\d+/', '\\1', $file);
  84. // Check block exists and is installed
  85. if (in_array($blockname, $availableblocks) && $DB->record_exists('block', array('name' => $blockname))) {
  86. $blocks[$path .'/' . $file] = $blockname;
  87. }
  88. }
  89. }
  90. closedir($dir);
  91. return $blocks;
  92. }
  93. /**
  94. * Load and format all the needed information from moodle_backup.xml
  95. *
  96. * This function loads and process all the moodle_backup.xml
  97. * information, composing a big information structure that will
  98. * be the used by the plan builder in order to generate the
  99. * appropiate tasks / steps / settings
  100. */
  101. public static function get_backup_information($tempdir) {
  102. global $CFG;
  103. $info = new stdclass(); // Final information goes here
  104. $moodlefile = $CFG->tempdir . '/backup/' . $tempdir . '/moodle_backup.xml';
  105. if (!file_exists($moodlefile)) { // Shouldn't happen ever, but...
  106. throw new backup_helper_exception('missing_moodle_backup_xml_file', $moodlefile);
  107. }
  108. // Load the entire file to in-memory array
  109. $xmlparser = new progressive_parser();
  110. $xmlparser->set_file($moodlefile);
  111. $xmlprocessor = new restore_moodlexml_parser_processor();
  112. $xmlparser->set_processor($xmlprocessor);
  113. $xmlparser->process();
  114. $infoarr = $xmlprocessor->get_all_chunks();
  115. if (count($infoarr) !== 1) { // Shouldn't happen ever, but...
  116. throw new backup_helper_exception('problem_parsing_moodle_backup_xml_file');
  117. }
  118. $infoarr = $infoarr[0]['tags']; // for commodity
  119. // Let's build info
  120. $info->moodle_version = $infoarr['moodle_version'];
  121. $info->moodle_release = $infoarr['moodle_release'];
  122. $info->backup_version = $infoarr['backup_version'];
  123. $info->backup_release = $infoarr['backup_release'];
  124. $info->backup_date = $infoarr['backup_date'];
  125. $info->mnet_remoteusers = $infoarr['mnet_remoteusers'];
  126. $info->original_wwwroot = $infoarr['original_wwwroot'];
  127. $info->original_site_identifier_hash = $infoarr['original_site_identifier_hash'];
  128. $info->original_course_id = $infoarr['original_course_id'];
  129. $info->original_course_fullname = $infoarr['original_course_fullname'];
  130. $info->original_course_shortname= $infoarr['original_course_shortname'];
  131. $info->original_course_startdate= $infoarr['original_course_startdate'];
  132. $info->original_course_contextid= $infoarr['original_course_contextid'];
  133. $info->original_system_contextid= $infoarr['original_system_contextid'];
  134. // Moodle backup file don't have this option before 2.3
  135. if (!empty($infoarr['include_file_references_to_external_content'])) {
  136. $info->include_file_references_to_external_content = 1;
  137. } else {
  138. $info->include_file_references_to_external_content = 0;
  139. }
  140. // include_files is a new setting in 2.6.
  141. if (isset($infoarr['include_files'])) {
  142. $info->include_files = $infoarr['include_files'];
  143. } else {
  144. $info->include_files = 1;
  145. }
  146. $info->type = $infoarr['details']['detail'][0]['type'];
  147. $info->format = $infoarr['details']['detail'][0]['format'];
  148. $info->mode = $infoarr['details']['detail'][0]['mode'];
  149. // Build the role mappings custom object
  150. $rolemappings = new stdclass();
  151. $rolemappings->modified = false;
  152. $rolemappings->mappings = array();
  153. $info->role_mappings = $rolemappings;
  154. // Some initially empty containers
  155. $info->sections = array();
  156. $info->activities = array();
  157. // Now the contents
  158. $contentsarr = $infoarr['contents'];
  159. if (isset($contentsarr['course']) && isset($contentsarr['course'][0])) {
  160. $info->course = new stdclass();
  161. $info->course = (object)$contentsarr['course'][0];
  162. $info->course->settings = array();
  163. }
  164. if (isset($contentsarr['sections']) && isset($contentsarr['sections']['section'])) {
  165. $sectionarr = $contentsarr['sections']['section'];
  166. foreach ($sectionarr as $section) {
  167. $section = (object)$section;
  168. $section->settings = array();
  169. $sections[basename($section->directory)] = $section;
  170. }
  171. $info->sections = $sections;
  172. }
  173. if (isset($contentsarr['activities']) && isset($contentsarr['activities']['activity'])) {
  174. $activityarr = $contentsarr['activities']['activity'];
  175. foreach ($activityarr as $activity) {
  176. $activity = (object)$activity;
  177. $activity->settings = array();
  178. $activities[basename($activity->directory)] = $activity;
  179. }
  180. $info->activities = $activities;
  181. }
  182. $info->root_settings = array(); // For root settings
  183. // Now the settings, putting each one under its owner
  184. $settingsarr = $infoarr['settings']['setting'];
  185. foreach($settingsarr as $setting) {
  186. switch ($setting['level']) {
  187. case 'root':
  188. $info->root_settings[$setting['name']] = $setting['value'];
  189. break;
  190. case 'course':
  191. $info->course->settings[$setting['name']] = $setting['value'];
  192. break;
  193. case 'section':
  194. $info->sections[$setting['section']]->settings[$setting['name']] = $setting['value'];
  195. break;
  196. case 'activity':
  197. $info->activities[$setting['activity']]->settings[$setting['name']] = $setting['value'];
  198. break;
  199. default: // Shouldn't happen
  200. throw new backup_helper_exception('wrong_setting_level_moodle_backup_xml_file', $setting['level']);
  201. }
  202. }
  203. return $info;
  204. }
  205. /**
  206. * Load and format all the needed information from a backup file.
  207. *
  208. * This will only extract the moodle_backup.xml file from an MBZ
  209. * file and then call {@link self::get_backup_information()}.
  210. *
  211. * @param string $filepath absolute path to the MBZ file.
  212. * @return stdClass containing information.
  213. * @since 2.4
  214. */
  215. public static function get_backup_information_from_mbz($filepath) {
  216. global $CFG;
  217. if (!is_readable($filepath)) {
  218. throw new backup_helper_exception('missing_moodle_backup_file', $filepath);
  219. }
  220. // Extract moodle_backup.xml.
  221. $tmpname = 'info_from_mbz_' . time() . '_' . random_string(4);
  222. $tmpdir = $CFG->tempdir . '/backup/' . $tmpname;
  223. $fp = get_file_packer('application/vnd.moodle.backup');
  224. $extracted = $fp->extract_to_pathname($filepath, $tmpdir, array('moodle_backup.xml'));
  225. $moodlefile = $tmpdir . '/' . 'moodle_backup.xml';
  226. if (!$extracted || !is_readable($moodlefile)) {
  227. throw new backup_helper_exception('missing_moodle_backup_xml_file', $moodlefile);
  228. }
  229. // Read the information and delete the temporary directory.
  230. $info = self::get_backup_information($tmpname);
  231. remove_dir($tmpdir);
  232. return $info;
  233. }
  234. /**
  235. * Given the information fetched from moodle_backup.xml file
  236. * decide if we are restoring in the same site the backup was
  237. * generated or no. Behavior of various parts of restore are
  238. * dependent of this.
  239. *
  240. * Backups created natively in 2.0 and later declare the hashed
  241. * site identifier. Backups created by conversion from a 1.9
  242. * backup do not declare such identifier, so there is a fallback
  243. * to wwwroot comparison. See MDL-16614.
  244. */
  245. public static function backup_is_samesite($info) {
  246. global $CFG;
  247. $hashedsiteid = md5(get_site_identifier());
  248. if (isset($info->original_site_identifier_hash) && !empty($info->original_site_identifier_hash)) {
  249. return $info->original_site_identifier_hash == $hashedsiteid;
  250. } else {
  251. return $info->original_wwwroot == $CFG->wwwroot;
  252. }
  253. }
  254. /**
  255. * Detects the format of the given unpacked backup directory
  256. *
  257. * @param string $tempdir the name of the backup directory
  258. * @return string one of backup::FORMAT_xxx constants
  259. */
  260. public static function detect_backup_format($tempdir) {
  261. global $CFG;
  262. require_once($CFG->dirroot . '/backup/util/helper/convert_helper.class.php');
  263. if (convert_helper::detect_moodle2_format($tempdir)) {
  264. return backup::FORMAT_MOODLE;
  265. }
  266. // see if a converter can identify the format
  267. $converters = convert_helper::available_converters();
  268. foreach ($converters as $name) {
  269. $classname = "{$name}_converter";
  270. if (!class_exists($classname)) {
  271. throw new coding_exception("available_converters() is supposed to load
  272. converter classes but class $classname not found");
  273. }
  274. $detected = call_user_func($classname .'::detect_format', $tempdir);
  275. if (!empty($detected)) {
  276. return $detected;
  277. }
  278. }
  279. return backup::FORMAT_UNKNOWN;
  280. }
  281. }