MDL-21432 backup - file handling and other changes. Saving before changes tomorrow...
[moodle.git] / backup / util / helper / backup_general_helper.class.php
CommitLineData
69dd0c8c
EL
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * @package moodlecore
20 * @subpackage backup-helper
21 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25/**
26 * Non instantiable helper class providing general helper methods for backup/restore
27 *
28 * This class contains various general helper static methods available for backup/restore
29 *
30 * TODO: Finish phpdocs
31 */
32abstract class backup_general_helper extends backup_helper {
33
34 /**
35 * Calculate one checksum for any array/object. Works recursively
36 */
37 public static function array_checksum_recursive($arr) {
38
39 $checksum = ''; // Init checksum
40
41 // Check we are going to process one array always, objects must be cast before
42 if (!is_array($arr)) {
43 throw new backup_helper_exception('array_expected');
44 }
45 foreach ($arr as $key => $value) {
46 if ($value instanceof checksumable) {
47 $checksum = md5($checksum . '-' . $key . '-' . $value->calculate_checksum());
48 } else if (is_object($value)) {
49 $checksum = md5($checksum . '-' . $key . '-' . self::array_checksum_recursive((array)$value));
50 } else if (is_array($value)) {
51 $checksum = md5($checksum . '-' . $key . '-' . self::array_checksum_recursive($value));
52 } else {
53 $checksum = md5($checksum . '-' . $key . '-' . $value);
54 }
55 }
56 return $checksum;
57 }
f60f4666 58
90338ad1
EL
59 /**
60 * Load all the blocks information needed for a given path within moodle2 backup
61 *
62 * This function, given one full path (course, activities/xxxx) will look for all the
63 * blocks existing in the backup file, returning one array used to build the
64 * proper restore plan by the @restore_plan_builder
65 */
66 public static function get_blocks_from_path($path) {
67 global $DB;
68
69 $blocks = array(); // To return results
70
71 static $availableblocks = array(); // Get and cache available blocks
72 if (empty($availableblocks)) {
73 $availableblocks = array_keys(get_plugin_list('block'));
74 }
75
76 $path = $path . '/blocks'; // Always look under blocks subdir
77
78 if (!is_dir($path)) {
79 return array();
80 }
81
82 $dir = opendir($path);
83 while (false !== ($file = readdir($dir))) {
84 if ($file == '.' || $file == '..') { // Skip dots
85 continue;
86 }
87 if (is_dir($path .'/' . $file)) { // Dir found, check it's a valid block
88 if (!file_exists($path .'/' . $file . '/block.xml')) { // Skip if xml file not found
89 continue;
90 }
91 // Extract block name
92 $blockname = preg_replace('/(.*)_\d+/', '\\1', $file);
93 // Check block exists and is installed
94 if (in_array($blockname, $availableblocks) && $DB->record_exists('block', array('name' => $blockname))) {
95 $blocks[$path .'/' . $file] = $blockname;
96 }
97 }
98 }
99 closedir($dir);
100
101 return $blocks;
102 }
103
dc5a2f8a
EL
104 /**
105 * Load and format all the needed information from moodle_backup.xml
106 *
107 * This function loads and process all the moodle_backup.xml
108 * information, composing a big information structure that will
109 * be the used by the plan builder in order to generate the
110 * appropiate tasks / steps / settings
111 */
112 public static function get_backup_information($tempdir) {
113 global $CFG;
114
115 $info = new stdclass(); // Final information goes here
116
117 $moodlefile = $CFG->dataroot . '/temp/backup/' . $tempdir . '/moodle_backup.xml';
118 if (!file_exists($moodlefile)) { // Shouldn't happen ever, but...
482aac65 119 throw new backup_helper_exception('missing_moodle_backup_xml_file', $moodlefile);
dc5a2f8a
EL
120 }
121 // Load the entire file to in-memory array
122 $xmlparser = new progressive_parser();
123 $xmlparser->set_file($moodlefile);
124 $xmlprocessor = new restore_moodlexml_parser_processor();
125 $xmlparser->set_processor($xmlprocessor);
126 $xmlparser->process();
127 $infoarr = $xmlprocessor->get_all_chunks();
128 if (count($infoarr) !== 1) { // Shouldn't happen ever, but...
129 throw new backup_helper_exception('problem_parsing_moodle_backup_xml_file');
130 }
131 $infoarr = $infoarr[0]['tags']; // for commodity
132
133 // Let's build info
134 $info->moodle_version = $infoarr['moodle_version'];
135 $info->moodle_release = $infoarr['moodle_release'];
136 $info->backup_version = $infoarr['backup_version'];
137 $info->backup_release = $infoarr['backup_release'];
138 $info->backup_date = $infoarr['backup_date'];
139 $info->original_wwwroot = $infoarr['original_wwwroot'];
482aac65 140 $info->original_site_identifier_hash = $infoarr['original_site_identifier_hash'];
dc5a2f8a 141 $info->original_course_id = $infoarr['original_course_id'];
2df0f295 142 $info->original_course_contextid= $infoarr['original_course_contextid'];
dc5a2f8a
EL
143 $info->type = $infoarr['details']['detail'][0]['type'];
144 $info->format = $infoarr['details']['detail'][0]['format'];
145 $info->mode = $infoarr['details']['detail'][0]['mode'];
146
147 // Now the contents
148 $contentsarr = $infoarr['contents'];
149 if (isset($contentsarr['course']) && isset($contentsarr['course'][0])) {
150 $info->course = new stdclass();
151 $info->course = (object)$contentsarr['course'][0];
152 $info->course->settings = array();
153 }
154 if (isset($contentsarr['sections']) && isset($contentsarr['sections']['section'])) {
155 $sectionarr = $contentsarr['sections']['section'];
156 $sections = array();
157 foreach ($sectionarr as $section) {
158 $section = (object)$section;
159 $section->settings = array();
160 $sections[basename($section->directory)] = $section;
161 }
162 $info->sections = $sections;
163 }
164 if (isset($contentsarr['activities']) && isset($contentsarr['activities']['activity'])) {
165 $activityarr = $contentsarr['activities']['activity'];
166 $activities = array();
167 foreach ($activityarr as $activity) {
168 $activity = (object)$activity;
169 $activity->settings = array();
170 $activities[basename($activity->directory)] = $activity;
171 }
172 $info->activities = $activities;
173 }
174 $info->root_settings = array(); // For root settings
175
176 // Now the settings, putting each one under its owner
177 $settingsarr = $infoarr['settings']['setting'];
178 foreach($settingsarr as $setting) {
179 switch ($setting['level']) {
180 case 'root':
181 $info->root_settings[$setting['name']] = $setting['value'];
182 break;
183 case 'course':
184 $info->course->settings[$setting['name']] = $setting['value'];
185 break;
186 case 'section':
187 $info->sections[$setting['section']]->settings[$setting['name']] = $setting['value'];
188 break;
189 case 'activity':
190 $info->activities[$setting['activity']]->settings[$setting['name']] = $setting['value'];
191 break;
192 default: // Shouldn't happen
193 throw new backup_helper_exception('wrong_setting_level_moodle_backup_xml_file', $setting['level']);
194 }
195 }
196
197 return $info;
198 }
199
482aac65
EL
200 /**
201 * Given the information fetched from moodle_backup.xml file
202 * decide if we are restoring in the same site the backup was
203 * generated or no. Behavior of various parts of restore are
204 * dependent of this.
205 *
206 * Use site_identifier (hashed) and fallback to wwwroot, thought
207 * any 2.0 backup should have the former. See MDL-16614
208 */
209 public static function backup_is_samesite($info) {
210 global $CFG;
211 $hashedsiteid = md5(get_site_identifier());
212 if (isset($info->original_site_identifier_hash) && !empty($info->original_site_identifier_hash)) {
213 return $info->original_site_identifier_hash == $hashedsiteid;
214 } else {
215 return $info->original_wwwroot == $CFG->wwwroot;
216 }
217 }
218
f60f4666
EL
219 /**
220 * Given one temp/backup/xxx dir, detect its format
221 *
222 * TODO: Move harcoded detection here to delegated classes under backup/format (moodle1, imscc..)
223 * conversion code will be there too.
224 */
225 public static function detect_backup_format($tempdir) {
226 global $CFG;
90338ad1
EL
227 $filepath = $CFG->dataroot . '/temp/backup/' . $tempdir . '/moodle_backup.xml';
228
229 // Does tempdir exist and is dir
230 if (!is_dir(dirname($filepath))) {
231 throw new backup_helper_exception('tmp_backup_directory_not_found', dirname($filepath));
232 }
f60f4666
EL
233
234 // First look for MOODLE (moodle2) format
f60f4666
EL
235 if (file_exists($filepath)) { // Looks promising, lets load some information
236 $handle = fopen ($filepath, "r");
237 $first_chars = fread($handle,200);
238 $status = fclose ($handle);
239 // Check if it has the required strings
240 if (strpos($first_chars,'<?xml version="1.0" encoding="UTF-8"?>') !== false &&
241 strpos($first_chars,'<moodle_backup>') !== false &&
242 strpos($first_chars,'<information>') !== false) {
243 return backup::FORMAT_MOODLE;
244 }
245 }
246
247 // Then look for MOODLE1 (moodle1) format
248 $filepath = $CFG->dataroot . '/temp/backup/' . $tempdir . '/moodle.xml';
249 if (file_exists($filepath)) { // Looks promising, lets load some information
250 $handle = fopen ($filepath, "r");
251 $first_chars = fread($handle,200);
252 $status = fclose ($handle);
253 // Check if it has the required strings
254 if (strpos($first_chars,'<?xml version="1.0" encoding="UTF-8"?>') !== false &&
255 strpos($first_chars,'<MOODLE_BACKUP>') !== false &&
256 strpos($first_chars,'<INFO>') !== false) {
257 return backup::FORMAT_MOODLE1;
258 }
259 }
260
261 // Other formats
262
263 // Arrived here, unknown format
264 return backup::FORMAT_UNKNOWN;
265 }
69dd0c8c 266}