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