PageRenderTime 40ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/kudutest1/moodlegit
PHP | 305 lines | 190 code | 30 blank | 85 comment | 42 complexity | 2ff67a99d8cd3b14c1ccf2e11c4b8f9d MD5 | raw 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-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(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. $info->type = $infoarr['details']['detail'][0]['type'];
  141. $info->format = $infoarr['details']['detail'][0]['format'];
  142. $info->mode = $infoarr['details']['detail'][0]['mode'];
  143. // Build the role mappings custom object
  144. $rolemappings = new stdclass();
  145. $rolemappings->modified = false;
  146. $rolemappings->mappings = array();
  147. $info->role_mappings = $rolemappings;
  148. // Some initially empty containers
  149. $info->sections = array();
  150. $info->activities = array();
  151. // Now the contents
  152. $contentsarr = $infoarr['contents'];
  153. if (isset($contentsarr['course']) && isset($contentsarr['course'][0])) {
  154. $info->course = new stdclass();
  155. $info->course = (object)$contentsarr['course'][0];
  156. $info->course->settings = array();
  157. }
  158. if (isset($contentsarr['sections']) && isset($contentsarr['sections']['section'])) {
  159. $sectionarr = $contentsarr['sections']['section'];
  160. foreach ($sectionarr as $section) {
  161. $section = (object)$section;
  162. $section->settings = array();
  163. $sections[basename($section->directory)] = $section;
  164. }
  165. $info->sections = $sections;
  166. }
  167. if (isset($contentsarr['activities']) && isset($contentsarr['activities']['activity'])) {
  168. $activityarr = $contentsarr['activities']['activity'];
  169. foreach ($activityarr as $activity) {
  170. $activity = (object)$activity;
  171. $activity->settings = array();
  172. $activities[basename($activity->directory)] = $activity;
  173. }
  174. $info->activities = $activities;
  175. }
  176. $info->root_settings = array(); // For root settings
  177. // Now the settings, putting each one under its owner
  178. $settingsarr = $infoarr['settings']['setting'];
  179. foreach($settingsarr as $setting) {
  180. switch ($setting['level']) {
  181. case 'root':
  182. $info->root_settings[$setting['name']] = $setting['value'];
  183. break;
  184. case 'course':
  185. $info->course->settings[$setting['name']] = $setting['value'];
  186. break;
  187. case 'section':
  188. $info->sections[$setting['section']]->settings[$setting['name']] = $setting['value'];
  189. break;
  190. case 'activity':
  191. $info->activities[$setting['activity']]->settings[$setting['name']] = $setting['value'];
  192. break;
  193. default: // Shouldn't happen
  194. throw new backup_helper_exception('wrong_setting_level_moodle_backup_xml_file', $setting['level']);
  195. }
  196. }
  197. return $info;
  198. }
  199. /**
  200. * Load and format all the needed information from a backup file.
  201. *
  202. * This will only extract the moodle_backup.xml file from an MBZ
  203. * file and then call {@link self::get_backup_information()}.
  204. *
  205. * @param string $filepath absolute path to the MBZ file.
  206. * @return stdClass containing information.
  207. * @since 2.4
  208. */
  209. public static function get_backup_information_from_mbz($filepath) {
  210. global $CFG;
  211. if (!is_readable($filepath)) {
  212. throw new backup_helper_exception('missing_moodle_backup_file', $filepath);
  213. }
  214. // Extract moodle_backup.xml.
  215. $tmpname = 'info_from_mbz_' . time() . '_' . random_string(4);
  216. $tmpdir = $CFG->tempdir . '/backup/' . $tmpname;
  217. $fp = get_file_packer('application/vnd.moodle.backup');
  218. $extracted = $fp->extract_to_pathname($filepath, $tmpdir, array('moodle_backup.xml'));
  219. $moodlefile = $tmpdir . '/' . 'moodle_backup.xml';
  220. if (!$extracted || !is_readable($moodlefile)) {
  221. throw new backup_helper_exception('missing_moodle_backup_xml_file', $moodlefile);
  222. }
  223. // Read the information and delete the temporary directory.
  224. $info = self::get_backup_information($tmpname);
  225. remove_dir($tmpdir);
  226. return $info;
  227. }
  228. /**
  229. * Given the information fetched from moodle_backup.xml file
  230. * decide if we are restoring in the same site the backup was
  231. * generated or no. Behavior of various parts of restore are
  232. * dependent of this.
  233. *
  234. * Backups created natively in 2.0 and later declare the hashed
  235. * site identifier. Backups created by conversion from a 1.9
  236. * backup do not declare such identifier, so there is a fallback
  237. * to wwwroot comparison. See MDL-16614.
  238. */
  239. public static function backup_is_samesite($info) {
  240. global $CFG;
  241. $hashedsiteid = md5(get_site_identifier());
  242. if (isset($info->original_site_identifier_hash) && !empty($info->original_site_identifier_hash)) {
  243. return $info->original_site_identifier_hash == $hashedsiteid;
  244. } else {
  245. return $info->original_wwwroot == $CFG->wwwroot;
  246. }
  247. }
  248. /**
  249. * Detects the format of the given unpacked backup directory
  250. *
  251. * @param string $tempdir the name of the backup directory
  252. * @return string one of backup::FORMAT_xxx constants
  253. */
  254. public static function detect_backup_format($tempdir) {
  255. global $CFG;
  256. require_once($CFG->dirroot . '/backup/util/helper/convert_helper.class.php');
  257. if (convert_helper::detect_moodle2_format($tempdir)) {
  258. return backup::FORMAT_MOODLE;
  259. }
  260. // see if a converter can identify the format
  261. $converters = convert_helper::available_converters();
  262. foreach ($converters as $name) {
  263. $classname = "{$name}_converter";
  264. if (!class_exists($classname)) {
  265. throw new coding_exception("available_converters() is supposed to load
  266. converter classes but class $classname not found");
  267. }
  268. $detected = call_user_func($classname .'::detect_format', $tempdir);
  269. if (!empty($detected)) {
  270. return $detected;
  271. }
  272. }
  273. return backup::FORMAT_UNKNOWN;
  274. }
  275. }