MDL-27444 The choice module backup converter now uses on-start and on-end handlers...
[moodle.git] / backup / converter / moodle1 / lib.php
CommitLineData
1e2c7351
DM
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 * Provides classes used by the moodle1 converter
20 *
21 * @package backup-convert
22 * @subpackage moodle1
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
29require_once($CFG->dirroot . '/backup/converter/convertlib.php');
30require_once($CFG->dirroot . '/backup/util/xml/parser/progressive_parser.class.php');
31require_once($CFG->dirroot . '/backup/util/xml/parser/processors/grouped_parser_processor.class.php');
a5fe5912
DM
32require_once($CFG->dirroot . '/backup/util/dbops/backup_dbops.class.php');
33require_once($CFG->dirroot . '/backup/util/dbops/backup_controller_dbops.class.php');
34require_once($CFG->dirroot . '/backup/util/dbops/restore_dbops.class.php');
96f7c7ad 35require_once($CFG->dirroot . '/backup/util/xml/contenttransformer/xml_contenttransformer.class.php');
1e2c7351
DM
36require_once(dirname(__FILE__) . '/handlerlib.php');
37
38/**
39 * Converter of Moodle 1.9 backup into Moodle 2.x format
40 */
41class moodle1_converter extends base_converter {
42
43 /** @var progressive_parser moodle.xml file parser */
44 protected $xmlparser;
45
46 /** @var moodle1_parser_processor */
47 protected $xmlprocessor;
48
49 /** @var array of {@link convert_path} to process */
50 protected $pathelements = array();
51
6cfa5a32
DM
52 /** @var null|string the current module being processed - used to expand the MOD paths */
53 protected $currentmod = null;
1e2c7351 54
6cfa5a32
DM
55 /** @var null|string the current block being processed - used to expand the BLOCK paths */
56 protected $currentblock = null;
1e2c7351
DM
57
58 /** @var string path currently locking processing of children */
59 protected $pathlock;
60
61 /**
62 * Instructs the dispatcher to ignore all children below path processor returning it
63 */
64 const SKIP_ALL_CHILDREN = -991399;
65
66 /**
67 * Detects the Moodle 1.9 format of the backup directory
68 *
69 * @param string $tempdir the name of the backup directory
70 * @return null|string backup::FORMAT_MOODLE1 if the Moodle 1.9 is detected, null otherwise
71 */
72 public static function detect_format($tempdir) {
73 global $CFG;
74
75 $filepath = $CFG->dataroot . '/temp/backup/' . $tempdir . '/moodle.xml';
76 if (file_exists($filepath)) {
77 // looks promising, lets load some information
78 $handle = fopen($filepath, 'r');
79 $first_chars = fread($handle, 200);
80 fclose($handle);
81
82 // check if it has the required strings
83 if (strpos($first_chars,'<?xml version="1.0" encoding="UTF-8"?>') !== false and
84 strpos($first_chars,'<MOODLE_BACKUP>') !== false and
85 strpos($first_chars,'<INFO>') !== false) {
86
87 return backup::FORMAT_MOODLE1;
88 }
89 }
90
91 return null;
92 }
93
94 /**
95 * Initialize the instance if needed, called by the constructor
96 *
97 * Here we create objects we need before the execution.
98 */
99 protected function init() {
100
101 // ask your mother first before going out playing with toys
102 parent::init();
103
104 // good boy, prepare XML parser and processor
105 $this->xmlparser = new progressive_parser();
106 $this->xmlparser->set_file($this->get_tempdir_path() . '/moodle.xml');
107 $this->xmlprocessor = new moodle1_parser_processor($this);
108 $this->xmlparser->set_processor($this->xmlprocessor);
109
110 // make sure that MOD and BLOCK paths are visited
111 $this->xmlprocessor->add_path('/MOODLE_BACKUP/COURSE/MODULES/MOD');
112 $this->xmlprocessor->add_path('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK');
113
114 // register the conversion handlers
115 foreach (moodle1_handlers_factory::get_handlers($this) as $handler) {
1e2c7351
DM
116 $this->register_handler($handler, $handler->get_paths());
117 }
118 }
119
120 /**
121 * Converts the contents of the tempdir into the target format in the workdir
122 */
123 protected function execute() {
9b5f1ad5 124 $this->create_stash_storage();
1e2c7351 125 $this->xmlparser->process();
9b5f1ad5 126 $this->drop_stash_storage();
1e2c7351
DM
127 }
128
129 /**
130 * Register a handler for the given path elements
131 */
132 protected function register_handler(moodle1_handler $handler, array $elements) {
133
134 // first iteration, push them to new array, indexed by name
135 // to detect duplicates in names or paths
136 $names = array();
137 $paths = array();
138 foreach($elements as $element) {
139 if (!$element instanceof convert_path) {
140 throw new convert_exception('path_element_wrong_class', get_class($element));
141 }
142 if (array_key_exists($element->get_name(), $names)) {
143 throw new convert_exception('path_element_name_alreadyexists', $element->get_name());
144 }
145 if (array_key_exists($element->get_path(), $paths)) {
146 throw new convert_exception('path_element_path_alreadyexists', $element->get_path());
147 }
148 $names[$element->get_name()] = true;
149 $paths[$element->get_path()] = $element;
150 }
151
152 // now, for each element not having a processing object yet, assign the handler
153 // if the element is not a memeber of a group
154 foreach($paths as $key => $element) {
155 if (is_null($element->get_processing_object()) and !$this->grouped_parent_exists($element, $paths)) {
156 $paths[$key]->set_processing_object($handler);
157 }
158 // add the element path to the processor
159 $this->xmlprocessor->add_path($element->get_path(), $element->is_grouped());
160 }
161
162 // done, store the paths (duplicates by path are discarded)
163 $this->pathelements = array_merge($this->pathelements, $paths);
164
165 // remove the injected plugin name element from the MOD and BLOCK paths
166 // and register such collapsed path, too
167 foreach ($elements as $element) {
168 $path = $element->get_path();
169 $path = preg_replace('/^\/MOODLE_BACKUP\/COURSE\/MODULES\/MOD\/(\w+)\//', '/MOODLE_BACKUP/COURSE/MODULES/MOD/', $path);
170 $path = preg_replace('/^\/MOODLE_BACKUP\/COURSE\/BLOCKS\/BLOCK\/(\w+)\//', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/', $path);
171 if (!empty($path) and $path != $element->get_path()) {
172 $this->xmlprocessor->add_path($path, false);
173 }
174 }
175 }
176
177 /**
178 * Helper method used by {@link self::register_handler()}
179 *
180 * @param convert_path $pelement path element
181 * @param array of convert_path instances
182 * @return bool true if grouped parent was found, false otherwise
183 */
184 protected function grouped_parent_exists($pelement, $elements) {
185
186 foreach ($elements as $element) {
187 if ($pelement->get_path() == $element->get_path()) {
188 // don't compare against itself
189 continue;
190 }
191 // if the element is grouped and it is a parent of pelement, return true
192 if ($element->is_grouped() and strpos($pelement->get_path() . '/', $element->get_path()) === 0) {
193 return true;
194 }
195 }
196
197 // no grouped parent found
198 return false;
199 }
200
201 /**
202 * Process the data obtained from the XML parser processor
203 *
204 * This methods receives one chunk of information from the XML parser
205 * processor and dispatches it, following the naming rules.
206 * We are expanding the modules and blocks paths here to include the plugin's name.
207 *
208 * @param array $data
209 */
210 public function process_chunk($data) {
211
212 $path = $data['path'];
213
214 // expand the MOD paths so that they contain the module name
215 if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
216 $this->currentmod = strtoupper($data['tags']['MODTYPE']);
217 $path = '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod;
218
219 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
220 $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
221 }
222
223 // expand the BLOCK paths so that they contain the module name
224 if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
225 $this->currentblock = strtoupper($data['tags']['NAME']);
226 $path = '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock;
227
228 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
229 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentmod, $path);
230 }
231
232 if ($path !== $data['path']) {
233 if (!array_key_exists($path, $this->pathelements)) {
234 // no handler registered for the transformed MOD or BLOCK path
235 // todo add this event to the convert log instead of debugging
236 //debugging('No handler registered for the path ' . $path);
237 return;
238
239 } else {
240 // pretend as if the original $data contained the tranformed path
241 $data['path'] = $path;
242 }
243 }
244
245 if (!array_key_exists($data['path'], $this->pathelements)) {
246 // path added to the processor without the handler
247 throw new convert_exception('missing_path_handler', $data['path']);
248 }
249
beb7de37
DM
250 $element = $this->pathelements[$data['path']];
251 $object = $element->get_processing_object();
252 $method = $element->get_processing_method();
253 $returned = null; // data returned by the processing method, if any
1e2c7351
DM
254
255 if (empty($object)) {
256 throw new convert_exception('missing_processing_object', $object);
257 }
258
259 // release the lock if we aren't anymore within children of it
260 if (!is_null($this->pathlock) and strpos($data['path'], $this->pathlock) === false) {
261 $this->pathlock = null;
262 }
263
264 // if the path is not locked, apply the element's recipes and dispatch
265 // the cooked tags to the processing method
266 if (is_null($this->pathlock)) {
beb7de37
DM
267 $rawdatatags = $data['tags'];
268 $data['tags'] = $element->apply_recipes($data['tags']);
46ff8b0e
DM
269
270 // if the processing method exists, give it a chance to modify data
271 if (method_exists($object, $method)) {
272 $returned = $object->$method($data['tags'], $rawdatatags);
273 }
1e2c7351
DM
274 }
275
276 // if the dispatched method returned SKIP_ALL_CHILDREN, remember the current path
277 // and lock it so that its children are not dispatched
beb7de37 278 if ($returned === self::SKIP_ALL_CHILDREN) {
1e2c7351
DM
279 // check we haven't any previous lock
280 if (!is_null($this->pathlock)) {
281 throw new convert_exception('already_locked_path', $data['path']);
282 }
283 // set the lock - nothing below the current path will be dispatched
284 $this->pathlock = $data['path'] . '/';
285
286 // if the method has returned any info, set element data to it
beb7de37
DM
287 } else if (!is_null($returned)) {
288 $element->set_data($returned);
1e2c7351
DM
289
290 // use just the cooked parsed data otherwise
291 } else {
292 $element->set_data($data);
293 }
294 }
295
296 /**
297 * Executes operations required at the start of a watched path
298 *
6cfa5a32
DM
299 * For MOD and BLOCK paths, this is supported only for the sub-paths, not the root
300 * module/block element. For the illustration:
301 *
302 * You CAN'T attach on_xxx_start() listener to a path like
303 * /MOODLE_BACKUP/COURSE/MODULES/MOD/WORKSHOP because the <MOD> must
304 * be processed first in {@link self::process_chunk()} where $this->currentmod
305 * is set.
306 *
307 * You CAN attach some on_xxx_start() listener to a path like
308 * /MOODLE_BACKUP/COURSE/MODULES/MOD/WORKSHOP/SUBMISSIONS because it is
309 * a sub-path under <MOD> and we have $this->currentmod already set when the
310 * <SUBMISSIONS> is reached.
1e2c7351 311 *
1e2c7351
DM
312 * @param string $path in the original file
313 */
314 public function path_start_reached($path) {
a5fe5912 315
6cfa5a32
DM
316 if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
317 $this->currentmod = null;
318 $forbidden = true;
319
320 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
321 // expand the MOD paths so that they contain the module name
322 $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
323 }
324
325 if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
326 $this->currentmod = null;
327 $forbidden = true;
328
329 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
330 // expand the BLOCK paths so that they contain the module name
331 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentmod, $path);
332 }
333
a5fe5912
DM
334 if (empty($this->pathelements[$path])) {
335 return;
336 }
337
338 $element = $this->pathelements[$path];
339 $pobject = $element->get_processing_object();
46ff8b0e 340 $method = $element->get_start_method();
a5fe5912
DM
341
342 if (method_exists($pobject, $method)) {
6cfa5a32
DM
343 if (empty($forbidden)) {
344 $pobject->$method();
345
346 } else {
347 // this path is not supported because we do not know the module/block yet
348 throw new coding_exception('Attaching the on-start event listener to the root MOD or BLOCK element is forbidden.');
349 }
a5fe5912 350 }
1e2c7351
DM
351 }
352
353 /**
354 * Executes operations required at the end of a watched path
355 *
1e2c7351
DM
356 * @param string $path in the original file
357 */
358 public function path_end_reached($path) {
a5fe5912
DM
359
360 // expand the MOD paths so that they contain the current module name
361 if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
362 $path = '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod;
363
364 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
365 $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
366 }
367
368 // expand the BLOCK paths so that they contain the module name
369 if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
370 $path = '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock;
371
372 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
373 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentmod, $path);
374 }
375
376 if (empty($this->pathelements[$path])) {
377 return;
378 }
379
380 $element = $this->pathelements[$path];
381 $pobject = $element->get_processing_object();
46ff8b0e 382 $method = $element->get_end_method();
1cc0e42a 383 $data = $element->get_data();
a5fe5912
DM
384
385 if (method_exists($pobject, $method)) {
1cc0e42a 386 $pobject->$method($data['tags']);
a5fe5912
DM
387 }
388 }
389
390 /**
9b5f1ad5 391 * Creates the temporary storage for stashed data
a5fe5912 392 *
9b5f1ad5 393 * This implementation uses backup_ids_temp table.
a5fe5912 394 */
9b5f1ad5
DM
395 public function create_stash_storage() {
396 backup_controller_dbops::create_backup_ids_temp_table($this->get_id());
a5fe5912
DM
397 }
398
399 /**
9b5f1ad5 400 * Drops the temporary storage of stashed data
a5fe5912 401 *
9b5f1ad5 402 * This implementation uses backup_ids_temp table.
a5fe5912 403 */
9b5f1ad5
DM
404 public function drop_stash_storage() {
405 backup_controller_dbops::drop_backup_ids_temp_table($this->get_id());
1e2c7351 406 }
a5fe5912 407
beb7de37 408 /**
9b5f1ad5 409 * Stores some information for later processing
beb7de37 410 *
9b5f1ad5
DM
411 * This implementation uses backup_ids_temp table to store data. Make
412 * sure that the $stashname + $itemid combo is unique.
beb7de37
DM
413 *
414 * @param string $stashname name of the stash
415 * @param mixed $info information to stash
9b5f1ad5 416 * @param int $itemid optional id for multiple infos within the same stashname
beb7de37 417 */
9b5f1ad5
DM
418 public function set_stash($stashname, $info, $itemid = 0) {
419 try {
420 restore_dbops::set_backup_ids_record($this->get_id(), $stashname, $itemid, 0, null, $info);
421
422 } catch (dml_exception $e) {
423 throw new moodle1_convert_storage_exception('unable_to_restore_stash', null, $e->getMessage());
424 }
beb7de37
DM
425 }
426
427 /**
428 * Restores a given stash stored previously by {@link self::set_stash()}
429 *
430 * @param string $stashname name of the stash
9b5f1ad5
DM
431 * @param int $itemid optional id for multiple infos within the same stashname
432 * @throws moodle1_convert_empty_storage_exception if the info has not been stashed previously
beb7de37
DM
433 * @return mixed stashed data
434 */
9b5f1ad5
DM
435 public function get_stash($stashname, $itemid = 0) {
436
437 $record = restore_dbops::get_backup_ids_record($this->get_id(), $stashname, $itemid);
438
439 if (empty($record)) {
6357693c 440 throw new moodle1_convert_empty_storage_exception('required_not_stashed_data', array($stashname, $itemid));
9b5f1ad5
DM
441 } else {
442 return $record->info;
443 }
beb7de37
DM
444 }
445
6d73f185
DM
446 /**
447 * Returns the list of stashed $itemids in the given stash
448 *
449 * @param string $stashname
450 * @return array
451 */
452 public function get_stash_itemids($stashname) {
453 global $DB;
454
455 $search = array(
456 'backupid' => $this->get_id(),
457 'itemname' => $stashname
458 );
459
460 return array_keys($DB->get_records('backup_ids_temp', $search, '', 'itemid'));
461 }
462
beb7de37
DM
463 /**
464 * Generates an artificial context id
465 *
466 * Moodle 1.9 backups do not contain any context information. But we need them
467 * in Moodle 2.x format so here we generate fictive context id for every given
468 * context level + instance combo.
469 *
26cac34a
DM
470 * CONTEXT_SYSTEM and CONTEXT_COURSE ignore the $instance as they represent a
471 * single system or the course being restored.
472 *
beb7de37
DM
473 * @see get_context_instance()
474 * @param int $level the context level, like CONTEXT_COURSE or CONTEXT_MODULE
475 * @param int $instance the instance id, for example $course->id for courses or $cm->id for activity modules
476 * @return int the context id
477 */
26cac34a 478 public function get_contextid($level, $instance = 0) {
beb7de37 479
9b5f1ad5 480 $stashname = 'context' . $level;
beb7de37 481
26cac34a
DM
482 if ($level == CONTEXT_SYSTEM or $level == CONTEXT_COURSE) {
483 $instance = 0;
484 }
485
d5d02635
DM
486 try {
487 // try the previously stashed id
488 return $this->get_stash($stashname, $instance);
beb7de37 489
d5d02635 490 } catch (moodle1_convert_empty_storage_exception $e) {
beb7de37 491 // this context level + instance is required for the first time
26cac34a
DM
492 $newid = $this->get_nextid();
493 $this->set_stash($stashname, $newid, $instance);
494 return $newid;
9b5f1ad5 495 }
beb7de37 496 }
179982a4 497
6700d288
DM
498 /**
499 * Simple autoincrement generator
500 *
501 * @return int the next number in a row of numbers
502 */
503 public function get_nextid() {
504 static $autoincrement = 0;
505 return ++$autoincrement;
506 }
507
179982a4
DM
508 /**
509 * @see parent::description()
510 */
511 public static function description() {
512
513 return array(
514 'from' => backup::FORMAT_MOODLE1,
515 'to' => backup::FORMAT_MOODLE,
516 'cost' => 10,
517 );
518 }
1e2c7351
DM
519}
520
521
9b5f1ad5
DM
522/**
523 * Exception thrown by this converter
524 */
525class moodle1_convert_exception extends convert_exception {
526}
527
528
529/**
530 * Exception thrown by the temporary storage subsystem of moodle1_converter
531 */
532class moodle1_convert_storage_exception extends moodle1_convert_exception {
533}
534
535
536/**
537 * Exception thrown by the temporary storage subsystem of moodle1_converter
538 */
539class moodle1_convert_empty_storage_exception extends moodle1_convert_exception {
540}
541
542
1e2c7351 543/**
96f7c7ad 544 * XML parser processor used for processing parsed moodle.xml
1e2c7351
DM
545 */
546class moodle1_parser_processor extends grouped_parser_processor {
547
548 /** @var moodle1_converter */
549 protected $converter;
550
551 public function __construct(moodle1_converter $converter) {
552 $this->converter = $converter;
553 parent::__construct();
554 }
555
556 /**
8312ab67
DM
557 * Provides NULL decoding
558 *
559 * Note that we do not decode $@FILEPHP@$ and friends here as we are going to write them
560 * back immediately into another XML file.
1e2c7351
DM
561 */
562 public function process_cdata($cdata) {
1e2c7351 563
8312ab67 564 if ($cdata === '$@NULL@$') {
1e2c7351 565 return null;
1e2c7351 566 }
8312ab67
DM
567
568 return $cdata;
1e2c7351
DM
569 }
570
571 /**
572 * Override this method so we'll be able to skip
573 * dispatching some well-known chunks, like the
574 * ones being 100% part of subplugins stuff. Useful
575 * for allowing development without having all the
576 * possible restore subplugins defined
8312ab67
DM
577 *
578 * @todo review why is this here (it is a relict)
1e2c7351
DM
579 */
580 protected function postprocess_chunk($data) {
581
582 // Iterate over all the data tags, if any of them is
583 // not 'subplugin_XXXX' or has value, then it's a valid chunk,
584 // pass it to standard (parent) processing of chunks.
585 foreach ($data['tags'] as $key => $value) {
586 if (trim($value) !== '' || strpos($key, 'subplugin_') !== 0) {
587 parent::postprocess_chunk($data);
588 return;
589 }
590 }
591 // Arrived here, all the tags correspond to sublplugins and are empty,
592 // skip the chunk, and debug_developer notice
593 $this->chunks--; // not counted
594 debugging('Missing support on restore for ' . clean_param($data['path'], PARAM_PATH) .
595 ' subplugin (' . implode(', ', array_keys($data['tags'])) .')', DEBUG_DEVELOPER);
596 }
597
598 /**
599 * Dispatches the data chunk to the converter class
600 *
601 * @param array $data the chunk of parsed data
602 */
603 protected function dispatch_chunk($data) {
604 $this->converter->process_chunk($data);
605 }
606
607 /**
608 * Informs the converter at the start of a watched path
609 *
610 * @param string $path
611 */
612 protected function notify_path_start($path) {
613 $this->converter->path_start_reached($path);
614 }
615
616 /**
617 * Informs the converter at the end of a watched path
618 *
619 * @param string $path
620 */
621 protected function notify_path_end($path) {
622 $this->converter->path_end_reached($path);
623 }
624}
625
626
96f7c7ad
DM
627/**
628 * XML transformer that modifies the content of the files being written during the conversion
629 *
630 * @see backup_xml_transformer
631 */
632class moodle1_xml_transformer extends xml_contenttransformer {
633
634 /**
635 * Modify the content before it is writter to a file
636 *
637 * @param string|mixed $content
638 */
639 public function process($content) {
640
641 // the content should be a string. If array or object is given, try our best recursively
642 // but inform the developer
643 if (is_array($content)) {
644 debugging('Moodle1 XML transformer should not process arrays but plain content always', DEBUG_DEVELOPER);
645 foreach($content as $key => $plaincontent) {
646 $content[$key] = $this->process($plaincontent);
647 }
648 return $content;
649
650 } else if (is_object($content)) {
651 debugging('Moodle1 XML transformer should not process objects but plain content always', DEBUG_DEVELOPER);
652 foreach((array)$content as $key => $plaincontent) {
653 $content[$key] = $this->process($plaincontent);
654 }
655 return (object)$content;
656 }
657
658 // try to deal with some trivial cases first
659 if (is_null($content)) {
660 return '$@NULL@$';
661
662 } else if ($content === '') {
663 return '';
664
665 } else if (is_numeric($content)) {
666 return $content;
667
668 } else if (strlen($content) < 32) {
669 return $content;
670 }
671
96f7c7ad
DM
672 return $content;
673 }
674}
675
676
1e2c7351
DM
677/**
678 * Class representing a path to be converted from XML file
679 *
680 * This was created as a copy of {@link restore_path_element} and should be refactored
681 * probably.
682 */
683class convert_path {
684
685 /** @var string name of the element */
686 protected $name;
687
688 /** @var string path within the XML file this element will handle */
689 protected $path;
690
691 /** @var bool flag to define if this element will get child ones grouped or no */
692 protected $grouped;
693
694 /** @var object object instance in charge of processing this element. */
695 protected $pobject = null;
696
697 /** @var string the name of the processing method */
698 protected $pmethod = null;
699
46ff8b0e
DM
700 /** @var string the name of the path start event handler */
701 protected $smethod = null;
702
703 /** @var string the name of the path end event handler */
704 protected $emethod = null;
705
1e2c7351
DM
706 /** @var mixed last data read for this element or returned data by processing method */
707 protected $data = null;
708
a5fe5912
DM
709 /** @var array of deprecated fields that are dropped */
710 protected $dropfields = array();
1e2c7351
DM
711
712 /** @var array of fields renaming */
713 protected $renamefields = array();
714
715 /** @var array of new fields to add and their initial values */
716 protected $newfields = array();
717
718 /**
719 * Constructor
720 *
721 * @param string $name name of the element
722 * @param string $path path of the element
723 * @param array $recipe basic description of the structure conversion
724 * @param bool $grouped to gather information in grouped mode or no
725 */
726 public function __construct($name, $path, array $recipe = array(), $grouped = false) {
727
728 $this->validate_name($name);
729
730 $this->name = $name;
731 $this->path = $path;
732 $this->grouped = $grouped;
733
46ff8b0e 734 // set the default method names
1e2c7351 735 $this->set_processing_method('process_' . $name);
46ff8b0e
DM
736 $this->set_start_method('on_'.$name.'_start');
737 $this->set_end_method('on_'.$name.'_end');
1e2c7351 738
a5fe5912
DM
739 if (isset($recipe['dropfields']) and is_array($recipe['dropfields'])) {
740 $this->set_dropped_fields($recipe['dropfields']);
1e2c7351
DM
741 }
742 if (isset($recipe['renamefields']) and is_array($recipe['renamefields'])) {
743 $this->set_renamed_fields($recipe['renamefields']);
744 }
745 if (isset($recipe['newfields']) and is_array($recipe['newfields'])) {
746 $this->set_new_fields($recipe['newfields']);
747 }
748 }
749
750 /**
751 * Validates and sets the given processing object
752 *
753 * @param object $pobject processing object, must provide a method to be called
754 */
755 public function set_processing_object($pobject) {
756 $this->validate_pobject($pobject);
757 $this->pobject = $pobject;
758 }
759
760 /**
761 * Sets the name of the processing method
762 *
763 * @param string $pmethod
764 */
765 public function set_processing_method($pmethod) {
766 $this->pmethod = $pmethod;
767 }
768
46ff8b0e
DM
769 /**
770 * Sets the name of the path start event listener
771 *
772 * @param string $smethod
773 */
774 public function set_start_method($smethod) {
775 $this->smethod = $smethod;
776 }
777
778 /**
779 * Sets the name of the path end event listener
780 *
781 * @param string $emethod
782 */
783 public function set_end_method($emethod) {
784 $this->emethod = $emethod;
785 }
786
1e2c7351
DM
787 /**
788 * Sets the element data
789 *
790 * @param mixed
791 */
792 public function set_data($data) {
793 $this->data = $data;
794 }
795
796 /**
a5fe5912 797 * Sets the list of deprecated fields to drop
1e2c7351
DM
798 *
799 * @param array $fields
800 */
a5fe5912
DM
801 public function set_dropped_fields(array $fields) {
802 $this->dropfields = $fields;
1e2c7351
DM
803 }
804
805 /**
806 * Sets the required new names of the current fields
807 *
808 * @param array $fields (string)$currentname => (string)$newname
809 */
810 public function set_renamed_fields(array $fields) {
811 $this->renamefields = $fields;
812 }
813
814 /**
815 * Sets the new fields and their values
816 *
817 * @param array $fields (string)$field => (mixed)value
818 */
819 public function set_new_fields(array $fields) {
820 $this->newfields = $fields;
821 }
822
823 /**
824 * Cooks the parsed tags data by applying known recipes
825 *
826 * Recipes are used for common trivial operations like adding new fields
827 * or renaming fields. The handler's processing method receives cooked
828 * data.
829 *
830 * @param array $data the contents of the element
831 * @return array
832 */
833 public function apply_recipes(array $data) {
834
835 $cooked = array();
836
837 foreach ($data as $name => $value) {
838 // lower case rocks!
839 $name = strtolower($name);
840
a5fe5912
DM
841 // drop legacy fields
842 if (in_array($name, $this->dropfields)) {
843 continue;
844 }
845
1e2c7351
DM
846 // fields renaming
847 if (array_key_exists($name, $this->renamefields)) {
848 $name = $this->renamefields[$name];
849 }
850
851 $cooked[$name] = $value;
852 }
853
854 // adding new fields
855 foreach ($this->newfields as $name => $value) {
856 $cooked[$name] = $value;
857 }
858
859 return $cooked;
860 }
861
862 /**
863 * @return string the element given name
864 */
865 public function get_name() {
866 return $this->name;
867 }
868
869 /**
870 * @return string the path to the element
871 */
872 public function get_path() {
873 return $this->path;
874 }
875
876 /**
877 * @return bool flag to define if this element will get child ones grouped or no
878 */
879 public function is_grouped() {
880 return $this->grouped;
881 }
882
883 /**
884 * @return object the processing object providing the processing method
885 */
886 public function get_processing_object() {
887 return $this->pobject;
888 }
889
890 /**
891 * @return string the name of the method to call to process the element
892 */
893 public function get_processing_method() {
894 return $this->pmethod;
895 }
896
46ff8b0e
DM
897 /**
898 * @return string the name of the path start event listener
899 */
900 public function get_start_method() {
901 return $this->smethod;
902 }
903
904 /**
905 * @return string the name of the path end event listener
906 */
907 public function get_end_method() {
908 return $this->emethod;
909 }
910
1e2c7351
DM
911 /**
912 * @return mixed the element data
913 */
914 public function get_data() {
915 return $this->data;
916 }
917
918
919 /// end of public API //////////////////////////////////////////////////////
920
921 /**
922 * Makes sure the given name is a valid element name
923 *
924 * Note it may look as if we used exceptions for code flow control here. That's not the case
925 * as we actually validate the code, not the user data. And the code is supposed to be
926 * correct.
927 *
928 * @param string @name the element given name
929 * @throws convert_path_exception
930 * @return void
931 */
932 protected function validate_name($name) {
933 // Validate various name constraints, throwing exception if needed
934 if (empty($name)) {
935 throw new convert_path_exception('convert_path_emptyname', $name);
936 }
937 if (preg_replace('/\s/', '', $name) != $name) {
938 throw new convert_path_exception('convert_path_whitespace', $name);
939 }
940 if (preg_replace('/[^\x30-\x39\x41-\x5a\x5f\x61-\x7a]/', '', $name) != $name) {
941 throw new convert_path_exception('convert_path_notasciiname', $name);
942 }
943 }
944
945 /**
946 * Makes sure that the given object is a valid processing object
947 *
46ff8b0e
DM
948 * The processing object must be an object providing at least element's processing method
949 * or path-reached-end event listener or path-reached-start listener method.
950 *
1e2c7351
DM
951 * Note it may look as if we used exceptions for code flow control here. That's not the case
952 * as we actually validate the code, not the user data. And the code is supposed to be
953 * correct.
954 *
955 * @param object $pobject
956 * @throws convert_path_exception
957 * @return void
958 */
959 protected function validate_pobject($pobject) {
960 if (!is_object($pobject)) {
46ff8b0e 961 throw new convert_path_exception('convert_path_no_object', get_class($pobject));
1e2c7351 962 }
46ff8b0e
DM
963 if (!method_exists($pobject, $this->get_processing_method()) and
964 !method_exists($pobject, $this->get_end_method()) and
965 !method_exists($pobject, $this->get_start_method())) {
966 throw new convert_path_exception('convert_path_missing_method', get_class($pobject));
1e2c7351
DM
967 }
968 }
969}
970
971
972/**
973 * Exception being thrown by {@link convert_path} methods
974 */
975class convert_path_exception extends moodle_exception {
976
977 /**
978 * Constructor
979 *
980 * @param string $errorcode key for the corresponding error string
981 * @param mixed $a extra words and phrases that might be required by the error string
982 * @param string $debuginfo optional debugging information
983 */
984 public function __construct($errorcode, $a = null, $debuginfo = null) {
985 parent::__construct($errorcode, '', '', $a, $debuginfo);
986 }
987}