MDL-29793 Advanced grading - do not execute the restore step if the grading.xml is...
[moodle.git] / backup / util / helper / convert_helper.class.php
CommitLineData
17252e2d 1<?php
e48477d9
DM
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/**
1e2c7351 19 * Provides {@link convert_helper} and {@link convert_helper_exception} classes
0164592b 20 *
e48477d9
DM
21 * @package core
22 * @subpackage backup-convert
23 * @copyright 2011 Mark Nielsen <mark@moodlerooms.com>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
1e2c7351
DM
29require_once($CFG->dirroot . '/backup/util/includes/convert_includes.php');
30
17252e2d 31/**
0164592b 32 * Provides various functionality via its static methods
17252e2d
MN
33 */
34abstract class convert_helper {
0164592b
DM
35
36 /**
37 * @param string $entropy
38 * @return string random identifier
39 */
17252e2d
MN
40 public static function generate_id($entropy) {
41 return md5(time() . '-' . $entropy . '-' . random_string(20));
42 }
c5c8b350
MN
43
44 /**
0164592b
DM
45 * Returns the list of all available converters and loads their classes
46 *
47 * Converter must be installed as a directory in backup/converter/ and its
48 * method is_available() must return true to get to the list.
49 *
50 * @see base_converter::is_available()
51 * @return array of strings
52 */
53 public static function available_converters() {
54 global $CFG;
55
56 $converters = array();
57 $plugins = get_list_of_plugins('backup/converter');
58 foreach ($plugins as $name) {
1e2c7351 59 $classfile = "$CFG->dirroot/backup/converter/$name/lib.php";
0164592b
DM
60 $classname = "{$name}_converter";
61
62 if (!file_exists($classfile)) {
1e2c7351 63 throw new convert_helper_exception('converter_classfile_not_found', $classfile);
0164592b
DM
64 }
65 require_once($classfile);
66
67 if (!class_exists($classname)) {
1e2c7351 68 throw new convert_helper_exception('converter_classname_not_found', $classname);
0164592b
DM
69 }
70
71 if (call_user_func($classname .'::is_available')) {
72 $converters[] = $name;
73 }
74 }
75
76 return $converters;
77 }
78
79 /**
80 * Detects if the given folder contains an unpacked moodle2 backup
81 *
82 * @param string $tempdir the name of the backup directory
83 * @return boolean true if moodle2 format detected, false otherwise
84 */
85 public static function detect_moodle2_format($tempdir) {
86 global $CFG;
87
7aa06e6d 88 $dirpath = $CFG->tempdir . '/backup/' . $tempdir;
0164592b
DM
89 $filepath = $dirpath . '/moodle_backup.xml';
90
91 if (!is_dir($dirpath)) {
477f1d2b 92 throw new convert_helper_exception('tmp_backup_directory_not_found', $dirpath);
0164592b
DM
93 }
94
95 if (!file_exists($filepath)) {
96 return false;
97 }
98
99 $handle = fopen($filepath, 'r');
100 $firstchars = fread($handle, 200);
101 $status = fclose($handle);
102
103 if (strpos($firstchars,'<?xml version="1.0" encoding="UTF-8"?>') !== false and
104 strpos($firstchars,'<moodle_backup>') !== false and
105 strpos($firstchars,'<information>') !== false) {
106 return true;
107 }
108
109 return false;
110 }
111
112 /**
113 * Converts the given directory with the backup into moodle2 format
114 *
c5c8b350
MN
115 * @param string $tempdir The directory to convert
116 * @param string $format The current format, if already detected
fe50f530 117 * @param base_logger|null if the conversion should be logged, use this logger
1e2c7351
DM
118 * @throws convert_helper_exception
119 * @return bool false if unable to find the conversion path, true otherwise
c5c8b350 120 */
fe50f530 121 public static function to_moodle2_format($tempdir, $format = null, $logger = null) {
0164592b 122
c5c8b350
MN
123 if (is_null($format)) {
124 $format = backup_general_helper::detect_backup_format($tempdir);
125 }
c5c8b350 126
0164592b 127 // get the supported conversion paths from all available converters
d51345c7 128 $converters = self::available_converters();
0164592b
DM
129 $descriptions = array();
130 foreach ($converters as $name) {
131 $classname = "{$name}_converter";
132 if (!class_exists($classname)) {
1e2c7351 133 throw new convert_helper_exception('class_not_loaded', $classname);
c5c8b350 134 }
fe50f530
DM
135 if ($logger instanceof base_logger) {
136 backup_helper::log('available converter', backup::LOG_DEBUG, $classname, 1, false, $logger);
137 }
0164592b
DM
138 $descriptions[$name] = call_user_func($classname .'::description');
139 }
c5c8b350 140
0164592b
DM
141 // choose the best conversion path for the given format
142 $path = self::choose_conversion_path($format, $descriptions);
143
144 if (empty($path)) {
fe50f530
DM
145 if ($logger instanceof base_logger) {
146 backup_helper::log('unable to find the conversion path', backup::LOG_ERROR, null, 0, false, $logger);
147 }
1e2c7351 148 return false;
c5c8b350 149 }
0164592b 150
fe50f530
DM
151 if ($logger instanceof base_logger) {
152 backup_helper::log('conversion path established', backup::LOG_INFO,
153 implode(' => ', array_merge($path, array('moodle2'))), 0, false, $logger);
154 }
155
0164592b 156 foreach ($path as $name) {
fe50f530
DM
157 if ($logger instanceof base_logger) {
158 backup_helper::log('running converter', backup::LOG_INFO, $name, 0, false, $logger);
159 }
160 $converter = convert_factory::get_converter($name, $tempdir, $logger);
0164592b
DM
161 $converter->convert();
162 }
163
164 // make sure we ended with moodle2 format
165 if (!self::detect_moodle2_format($tempdir)) {
1e2c7351 166 throw new convert_helper_exception('conversion_failed');
c5c8b350 167 }
1e2c7351
DM
168
169 return true;
c5c8b350 170 }
142ec51f
PC
171
172 /**
173 * Inserts an inforef into the conversion temp table
174 */
175 public static function set_inforef($contextid) {
176 global $DB;
142ec51f
PC
177 }
178
179 public static function get_inforef($contextid) {
180 }
181
0164592b
DM
182 /// end of public API //////////////////////////////////////////////////////
183
184 /**
185 * Choose the best conversion path for the given format
186 *
187 * Given the source format and the list of available converters and their properties,
188 * this methods picks the most effective way how to convert the source format into
189 * the target moodle2 format. The method returns a list of converters that should be
190 * called, in order.
191 *
192 * This implementation uses Dijkstra's algorithm to find the shortest way through
193 * the oriented graph.
194 *
195 * @see http://en.wikipedia.org/wiki/Dijkstra's_algorithm
1e2c7351 196 * @author David Mudrak <david@moodle.com>
0164592b
DM
197 * @param string $format the source backup format, one of backup::FORMAT_xxx
198 * @param array $descriptions list of {@link base_converter::description()} indexed by the converter name
199 * @return array ordered list of converter names to call (may be empty if not reachable)
200 */
201 protected static function choose_conversion_path($format, array $descriptions) {
202
203 // construct an oriented graph of conversion paths. backup formats are nodes
204 // and the the converters are edges of the graph.
205 $paths = array(); // [fromnode][tonode] => converter
206 foreach ($descriptions as $converter => $description) {
207 $from = $description['from'];
208 $to = $description['to'];
209 $cost = $description['cost'];
210
211 if (is_null($from) or $from === backup::FORMAT_UNKNOWN or
212 is_null($to) or $to === backup::FORMAT_UNKNOWN or
213 is_null($cost) or $cost <= 0) {
1e2c7351 214 throw new convert_helper_exception('invalid_converter_description', $converter);
0164592b
DM
215 }
216
217 if (!isset($paths[$from][$to])) {
218 $paths[$from][$to] = $converter;
219 } else {
220 // if there are two converters available for the same conversion
221 // path, choose the one with the lowest cost. if there are more
222 // available converters with the same cost, the chosen one is
223 // undefined (depends on the order of processing)
224 if ($descriptions[$paths[$from][$to]]['cost'] > $cost) {
225 $paths[$from][$to] = $converter;
226 }
227 }
228 }
229
230 if (empty($paths)) {
231 // no conversion paths available
232 return array();
233 }
234
235 // now use Dijkstra's algorithm and find the shortest conversion path
236
237 $dist = array(); // list of nodes and their distances from the source format
238 $prev = array(); // list of previous nodes in optimal path from the source format
239 foreach ($paths as $fromnode => $tonodes) {
240 $dist[$fromnode] = null; // infinitive distance, can't be reached
241 $prev[$fromnode] = null; // unknown
242 foreach ($tonodes as $tonode => $converter) {
243 $dist[$tonode] = null; // infinitive distance, can't be reached
244 $prev[$tonode] = null; // unknown
245 }
246 }
247
248 if (!array_key_exists($format, $dist)) {
249 return array();
250 } else {
251 $dist[$format] = 0;
252 }
253
254 $queue = array_flip(array_keys($dist));
255 while (!empty($queue)) {
256 // find the node with the smallest distance from the source in the queue
257 // in the first iteration, this will find the original format node itself
258 $closest = null;
259 foreach ($queue as $node => $undefined) {
260 if (is_null($dist[$node])) {
261 continue;
262 }
263 if (is_null($closest) or ($dist[$node] < $dist[$closest])) {
264 $closest = $node;
265 }
266 }
267
268 if (is_null($closest) or is_null($dist[$closest])) {
269 // all remaining nodes are inaccessible from source
270 break;
271 }
272
273 if ($closest === backup::FORMAT_MOODLE) {
274 // bingo we can break now
275 break;
276 }
277
278 unset($queue[$closest]);
279
280 // visit all neighbors and update distances to them eventually
281
282 if (!isset($paths[$closest])) {
283 continue;
284 }
285 $neighbors = array_keys($paths[$closest]);
286 // keep just neighbors that are in the queue yet
287 foreach ($neighbors as $ix => $neighbor) {
288 if (!array_key_exists($neighbor, $queue)) {
289 unset($neighbors[$ix]);
290 }
291 }
292
293 foreach ($neighbors as $neighbor) {
294 // the alternative distance to the neighbor if we went thru the
295 // current $closest node
296 $alt = $dist[$closest] + $descriptions[$paths[$closest][$neighbor]]['cost'];
297
298 if (is_null($dist[$neighbor]) or $alt < $dist[$neighbor]) {
299 // we found a shorter way to the $neighbor, remember it
300 $dist[$neighbor] = $alt;
301 $prev[$neighbor] = $closest;
302 }
303 }
304 }
305
306 if (is_null($dist[backup::FORMAT_MOODLE])) {
307 // unable to find a conversion path, the target format not reachable
308 return array();
309 }
310
311 // reconstruct the optimal path from the source format to the target one
312 $conversionpath = array();
313 $target = backup::FORMAT_MOODLE;
314 while (isset($prev[$target])) {
315 array_unshift($conversionpath, $paths[$prev[$target]][$target]);
316 $target = $prev[$target];
317 }
318
319 return $conversionpath;
320 }
142ec51f 321}
1e2c7351
DM
322
323/**
324 * General convert_helper related exception
325 *
326 * @author David Mudrak <david@moodle.com>
327 */
328class convert_helper_exception extends moodle_exception {
329
330 /**
331 * Constructor
332 *
333 * @param string $errorcode key for the corresponding error string
334 * @param object $a extra words and phrases that might be required in the error string
335 * @param string $debuginfo optional debugging information
336 */
337 public function __construct($errorcode, $a = null, $debuginfo = null) {
338 parent::__construct($errorcode, '', '', $a, $debuginfo);
339 }
340}