Improvements in moodle1_xml_handler external API
[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
52 /** @var string the current module being processed */
53 protected $currentmod = '';
54
55 /** @var string the current block being processed */
56 protected $currentblock = '';
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']);
269 $returned = $object->$method($data['tags'], $rawdatatags);
1e2c7351
DM
270 }
271
272 // if the dispatched method returned SKIP_ALL_CHILDREN, remember the current path
273 // and lock it so that its children are not dispatched
beb7de37 274 if ($returned === self::SKIP_ALL_CHILDREN) {
1e2c7351
DM
275 // check we haven't any previous lock
276 if (!is_null($this->pathlock)) {
277 throw new convert_exception('already_locked_path', $data['path']);
278 }
279 // set the lock - nothing below the current path will be dispatched
280 $this->pathlock = $data['path'] . '/';
281
282 // if the method has returned any info, set element data to it
beb7de37
DM
283 } else if (!is_null($returned)) {
284 $element->set_data($returned);
1e2c7351
DM
285
286 // use just the cooked parsed data otherwise
287 } else {
288 $element->set_data($data);
289 }
290 }
291
292 /**
293 * Executes operations required at the start of a watched path
294 *
295 * Note that this is called before the MOD and BLOCK paths are expanded
a5fe5912
DM
296 * so the current plugin is not known yet. Also note that this is
297 * triggered before the previous path is actually dispatched.
1e2c7351 298 *
1e2c7351
DM
299 * @param string $path in the original file
300 */
301 public function path_start_reached($path) {
a5fe5912
DM
302
303 if (empty($this->pathelements[$path])) {
304 return;
305 }
306
307 $element = $this->pathelements[$path];
308 $pobject = $element->get_processing_object();
309 $method = 'on_' . $element->get_name() . '_start';
310
311 if (method_exists($pobject, $method)) {
312 $pobject->$method();
313 }
1e2c7351
DM
314 }
315
316 /**
317 * Executes operations required at the end of a watched path
318 *
1e2c7351
DM
319 * @param string $path in the original file
320 */
321 public function path_end_reached($path) {
a5fe5912
DM
322
323 // expand the MOD paths so that they contain the current module name
324 if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
325 $path = '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod;
326
327 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
328 $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
329 }
330
331 // expand the BLOCK paths so that they contain the module name
332 if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
333 $path = '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock;
334
335 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
336 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentmod, $path);
337 }
338
339 if (empty($this->pathelements[$path])) {
340 return;
341 }
342
343 $element = $this->pathelements[$path];
344 $pobject = $element->get_processing_object();
1cc0e42a 345 $data = $element->get_data();
a5fe5912
DM
346 $method = 'on_' . $element->get_name() . '_end';
347
348 if (method_exists($pobject, $method)) {
1cc0e42a 349 $pobject->$method($data['tags']);
a5fe5912
DM
350 }
351 }
352
353 /**
9b5f1ad5 354 * Creates the temporary storage for stashed data
a5fe5912 355 *
9b5f1ad5 356 * This implementation uses backup_ids_temp table.
a5fe5912 357 */
9b5f1ad5
DM
358 public function create_stash_storage() {
359 backup_controller_dbops::create_backup_ids_temp_table($this->get_id());
a5fe5912
DM
360 }
361
362 /**
9b5f1ad5 363 * Drops the temporary storage of stashed data
a5fe5912 364 *
9b5f1ad5 365 * This implementation uses backup_ids_temp table.
a5fe5912 366 */
9b5f1ad5
DM
367 public function drop_stash_storage() {
368 backup_controller_dbops::drop_backup_ids_temp_table($this->get_id());
1e2c7351 369 }
a5fe5912 370
beb7de37 371 /**
9b5f1ad5 372 * Stores some information for later processing
beb7de37 373 *
9b5f1ad5
DM
374 * This implementation uses backup_ids_temp table to store data. Make
375 * sure that the $stashname + $itemid combo is unique.
beb7de37
DM
376 *
377 * @param string $stashname name of the stash
378 * @param mixed $info information to stash
9b5f1ad5 379 * @param int $itemid optional id for multiple infos within the same stashname
beb7de37 380 */
9b5f1ad5
DM
381 public function set_stash($stashname, $info, $itemid = 0) {
382 try {
383 restore_dbops::set_backup_ids_record($this->get_id(), $stashname, $itemid, 0, null, $info);
384
385 } catch (dml_exception $e) {
386 throw new moodle1_convert_storage_exception('unable_to_restore_stash', null, $e->getMessage());
387 }
beb7de37
DM
388 }
389
390 /**
391 * Restores a given stash stored previously by {@link self::set_stash()}
392 *
393 * @param string $stashname name of the stash
9b5f1ad5
DM
394 * @param int $itemid optional id for multiple infos within the same stashname
395 * @throws moodle1_convert_empty_storage_exception if the info has not been stashed previously
beb7de37
DM
396 * @return mixed stashed data
397 */
9b5f1ad5
DM
398 public function get_stash($stashname, $itemid = 0) {
399
400 $record = restore_dbops::get_backup_ids_record($this->get_id(), $stashname, $itemid);
401
402 if (empty($record)) {
403 throw new moodle1_convert_empty_storage_exception('required_not_stashed_data');
404 } else {
405 return $record->info;
406 }
beb7de37
DM
407 }
408
409 /**
410 * Generates an artificial context id
411 *
412 * Moodle 1.9 backups do not contain any context information. But we need them
413 * in Moodle 2.x format so here we generate fictive context id for every given
414 * context level + instance combo.
415 *
beb7de37
DM
416 * @see get_context_instance()
417 * @param int $level the context level, like CONTEXT_COURSE or CONTEXT_MODULE
418 * @param int $instance the instance id, for example $course->id for courses or $cm->id for activity modules
419 * @return int the context id
420 */
421 public function get_contextid($level, $instance) {
9b5f1ad5 422 static $autoincrement = 0;
beb7de37 423
9b5f1ad5 424 $stashname = 'context' . $level;
beb7de37 425
d5d02635
DM
426 try {
427 // try the previously stashed id
428 return $this->get_stash($stashname, $instance);
beb7de37 429
d5d02635 430 } catch (moodle1_convert_empty_storage_exception $e) {
beb7de37 431 // this context level + instance is required for the first time
d5d02635 432 $this->set_stash($stashname, ++$autoincrement, $instance);
9b5f1ad5 433 return $autoincrement;
9b5f1ad5 434 }
beb7de37 435 }
179982a4
DM
436
437 /**
438 * @see parent::description()
439 */
440 public static function description() {
441
442 return array(
443 'from' => backup::FORMAT_MOODLE1,
444 'to' => backup::FORMAT_MOODLE,
445 'cost' => 10,
446 );
447 }
1e2c7351
DM
448}
449
450
9b5f1ad5
DM
451/**
452 * Exception thrown by this converter
453 */
454class moodle1_convert_exception extends convert_exception {
455}
456
457
458/**
459 * Exception thrown by the temporary storage subsystem of moodle1_converter
460 */
461class moodle1_convert_storage_exception extends moodle1_convert_exception {
462}
463
464
465/**
466 * Exception thrown by the temporary storage subsystem of moodle1_converter
467 */
468class moodle1_convert_empty_storage_exception extends moodle1_convert_exception {
469}
470
471
1e2c7351 472/**
96f7c7ad 473 * XML parser processor used for processing parsed moodle.xml
1e2c7351
DM
474 */
475class moodle1_parser_processor extends grouped_parser_processor {
476
477 /** @var moodle1_converter */
478 protected $converter;
479
480 public function __construct(moodle1_converter $converter) {
481 $this->converter = $converter;
482 parent::__construct();
483 }
484
485 /**
486 * Provide NULL and legacy file.php uses decoding
487 */
488 public function process_cdata($cdata) {
489 global $CFG;
490
491 if ($cdata === '$@NULL@$') { // Some cases we know we can skip complete processing
492 return null;
493 } else if ($cdata === '') {
494 return '';
495 } else if (is_numeric($cdata)) {
496 return $cdata;
497 } else if (strlen($cdata) < 32) { // Impossible to have one link in 32cc
498 return $cdata; // (http://10.0.0.1/file.php/1/1.jpg, http://10.0.0.1/mod/url/view.php?id=)
499 } else if (strpos($cdata, '$@FILEPHP@$') === false) { // No $@FILEPHP@$, nothing to convert
500 return $cdata;
501 }
502 // Decode file.php calls
503 $search = array ("$@FILEPHP@$");
504 $replace = array(get_file_url($this->courseid));
505 $result = str_replace($search, $replace, $cdata);
506 // Now $@SLASH@$ and $@FORCEDOWNLOAD@$ MDL-18799
507 $search = array('$@SLASH@$', '$@FORCEDOWNLOAD@$');
508 if ($CFG->slasharguments) {
509 $replace = array('/', '?forcedownload=1');
510 } else {
511 $replace = array('%2F', '&amp;forcedownload=1');
512 }
513 return str_replace($search, $replace, $result);
514 }
515
516 /**
517 * Override this method so we'll be able to skip
518 * dispatching some well-known chunks, like the
519 * ones being 100% part of subplugins stuff. Useful
520 * for allowing development without having all the
521 * possible restore subplugins defined
522 */
523 protected function postprocess_chunk($data) {
524
525 // Iterate over all the data tags, if any of them is
526 // not 'subplugin_XXXX' or has value, then it's a valid chunk,
527 // pass it to standard (parent) processing of chunks.
528 foreach ($data['tags'] as $key => $value) {
529 if (trim($value) !== '' || strpos($key, 'subplugin_') !== 0) {
530 parent::postprocess_chunk($data);
531 return;
532 }
533 }
534 // Arrived here, all the tags correspond to sublplugins and are empty,
535 // skip the chunk, and debug_developer notice
536 $this->chunks--; // not counted
537 debugging('Missing support on restore for ' . clean_param($data['path'], PARAM_PATH) .
538 ' subplugin (' . implode(', ', array_keys($data['tags'])) .')', DEBUG_DEVELOPER);
539 }
540
541 /**
542 * Dispatches the data chunk to the converter class
543 *
544 * @param array $data the chunk of parsed data
545 */
546 protected function dispatch_chunk($data) {
547 $this->converter->process_chunk($data);
548 }
549
550 /**
551 * Informs the converter at the start of a watched path
552 *
553 * @param string $path
554 */
555 protected function notify_path_start($path) {
556 $this->converter->path_start_reached($path);
557 }
558
559 /**
560 * Informs the converter at the end of a watched path
561 *
562 * @param string $path
563 */
564 protected function notify_path_end($path) {
565 $this->converter->path_end_reached($path);
566 }
567}
568
569
96f7c7ad
DM
570/**
571 * XML transformer that modifies the content of the files being written during the conversion
572 *
573 * @see backup_xml_transformer
574 */
575class moodle1_xml_transformer extends xml_contenttransformer {
576
577 /**
578 * Modify the content before it is writter to a file
579 *
580 * @param string|mixed $content
581 */
582 public function process($content) {
583
584 // the content should be a string. If array or object is given, try our best recursively
585 // but inform the developer
586 if (is_array($content)) {
587 debugging('Moodle1 XML transformer should not process arrays but plain content always', DEBUG_DEVELOPER);
588 foreach($content as $key => $plaincontent) {
589 $content[$key] = $this->process($plaincontent);
590 }
591 return $content;
592
593 } else if (is_object($content)) {
594 debugging('Moodle1 XML transformer should not process objects but plain content always', DEBUG_DEVELOPER);
595 foreach((array)$content as $key => $plaincontent) {
596 $content[$key] = $this->process($plaincontent);
597 }
598 return (object)$content;
599 }
600
601 // try to deal with some trivial cases first
602 if (is_null($content)) {
603 return '$@NULL@$';
604
605 } else if ($content === '') {
606 return '';
607
608 } else if (is_numeric($content)) {
609 return $content;
610
611 } else if (strlen($content) < 32) {
612 return $content;
613 }
614
615 // todo will we need this?
616 //$content = $this->process_filephp_links($content); // Replace all calls to file.php by $@FILEPHP@$ in a normalised way
617 //$content = $this->encode_absolute_links($content); // Pass the content against all the found encoders
618
619 return $content;
620 }
621}
622
623
1e2c7351
DM
624/**
625 * Class representing a path to be converted from XML file
626 *
627 * This was created as a copy of {@link restore_path_element} and should be refactored
628 * probably.
629 */
630class convert_path {
631
632 /** @var string name of the element */
633 protected $name;
634
635 /** @var string path within the XML file this element will handle */
636 protected $path;
637
638 /** @var bool flag to define if this element will get child ones grouped or no */
639 protected $grouped;
640
641 /** @var object object instance in charge of processing this element. */
642 protected $pobject = null;
643
644 /** @var string the name of the processing method */
645 protected $pmethod = null;
646
647 /** @var mixed last data read for this element or returned data by processing method */
648 protected $data = null;
649
a5fe5912
DM
650 /** @var array of deprecated fields that are dropped */
651 protected $dropfields = array();
1e2c7351
DM
652
653 /** @var array of fields renaming */
654 protected $renamefields = array();
655
656 /** @var array of new fields to add and their initial values */
657 protected $newfields = array();
658
659 /**
660 * Constructor
661 *
662 * @param string $name name of the element
663 * @param string $path path of the element
664 * @param array $recipe basic description of the structure conversion
665 * @param bool $grouped to gather information in grouped mode or no
666 */
667 public function __construct($name, $path, array $recipe = array(), $grouped = false) {
668
669 $this->validate_name($name);
670
671 $this->name = $name;
672 $this->path = $path;
673 $this->grouped = $grouped;
674
675 // set the default processing method name
676 $this->set_processing_method('process_' . $name);
677
a5fe5912
DM
678 if (isset($recipe['dropfields']) and is_array($recipe['dropfields'])) {
679 $this->set_dropped_fields($recipe['dropfields']);
1e2c7351
DM
680 }
681 if (isset($recipe['renamefields']) and is_array($recipe['renamefields'])) {
682 $this->set_renamed_fields($recipe['renamefields']);
683 }
684 if (isset($recipe['newfields']) and is_array($recipe['newfields'])) {
685 $this->set_new_fields($recipe['newfields']);
686 }
687 }
688
689 /**
690 * Validates and sets the given processing object
691 *
692 * @param object $pobject processing object, must provide a method to be called
693 */
694 public function set_processing_object($pobject) {
695 $this->validate_pobject($pobject);
696 $this->pobject = $pobject;
697 }
698
699 /**
700 * Sets the name of the processing method
701 *
702 * @param string $pmethod
703 */
704 public function set_processing_method($pmethod) {
705 $this->pmethod = $pmethod;
706 }
707
708 /**
709 * Sets the element data
710 *
711 * @param mixed
712 */
713 public function set_data($data) {
714 $this->data = $data;
715 }
716
717 /**
a5fe5912 718 * Sets the list of deprecated fields to drop
1e2c7351
DM
719 *
720 * @param array $fields
721 */
a5fe5912
DM
722 public function set_dropped_fields(array $fields) {
723 $this->dropfields = $fields;
1e2c7351
DM
724 }
725
726 /**
727 * Sets the required new names of the current fields
728 *
729 * @param array $fields (string)$currentname => (string)$newname
730 */
731 public function set_renamed_fields(array $fields) {
732 $this->renamefields = $fields;
733 }
734
735 /**
736 * Sets the new fields and their values
737 *
738 * @param array $fields (string)$field => (mixed)value
739 */
740 public function set_new_fields(array $fields) {
741 $this->newfields = $fields;
742 }
743
744 /**
745 * Cooks the parsed tags data by applying known recipes
746 *
747 * Recipes are used for common trivial operations like adding new fields
748 * or renaming fields. The handler's processing method receives cooked
749 * data.
750 *
751 * @param array $data the contents of the element
752 * @return array
753 */
754 public function apply_recipes(array $data) {
755
756 $cooked = array();
757
758 foreach ($data as $name => $value) {
759 // lower case rocks!
760 $name = strtolower($name);
761
a5fe5912
DM
762 // drop legacy fields
763 if (in_array($name, $this->dropfields)) {
764 continue;
765 }
766
1e2c7351
DM
767 // fields renaming
768 if (array_key_exists($name, $this->renamefields)) {
769 $name = $this->renamefields[$name];
770 }
771
772 $cooked[$name] = $value;
773 }
774
775 // adding new fields
776 foreach ($this->newfields as $name => $value) {
777 $cooked[$name] = $value;
778 }
779
780 return $cooked;
781 }
782
783 /**
784 * @return string the element given name
785 */
786 public function get_name() {
787 return $this->name;
788 }
789
790 /**
791 * @return string the path to the element
792 */
793 public function get_path() {
794 return $this->path;
795 }
796
797 /**
798 * @return bool flag to define if this element will get child ones grouped or no
799 */
800 public function is_grouped() {
801 return $this->grouped;
802 }
803
804 /**
805 * @return object the processing object providing the processing method
806 */
807 public function get_processing_object() {
808 return $this->pobject;
809 }
810
811 /**
812 * @return string the name of the method to call to process the element
813 */
814 public function get_processing_method() {
815 return $this->pmethod;
816 }
817
818 /**
819 * @return mixed the element data
820 */
821 public function get_data() {
822 return $this->data;
823 }
824
825
826 /// end of public API //////////////////////////////////////////////////////
827
828 /**
829 * Makes sure the given name is a valid element name
830 *
831 * Note it may look as if we used exceptions for code flow control here. That's not the case
832 * as we actually validate the code, not the user data. And the code is supposed to be
833 * correct.
834 *
835 * @param string @name the element given name
836 * @throws convert_path_exception
837 * @return void
838 */
839 protected function validate_name($name) {
840 // Validate various name constraints, throwing exception if needed
841 if (empty($name)) {
842 throw new convert_path_exception('convert_path_emptyname', $name);
843 }
844 if (preg_replace('/\s/', '', $name) != $name) {
845 throw new convert_path_exception('convert_path_whitespace', $name);
846 }
847 if (preg_replace('/[^\x30-\x39\x41-\x5a\x5f\x61-\x7a]/', '', $name) != $name) {
848 throw new convert_path_exception('convert_path_notasciiname', $name);
849 }
850 }
851
852 /**
853 * Makes sure that the given object is a valid processing object
854 *
855 * The processing object must be an object providing the element's processing method.
856 * Note it may look as if we used exceptions for code flow control here. That's not the case
857 * as we actually validate the code, not the user data. And the code is supposed to be
858 * correct.
859 *
860 * @param object $pobject
861 * @throws convert_path_exception
862 * @return void
863 */
864 protected function validate_pobject($pobject) {
865 if (!is_object($pobject)) {
866 throw new convert_path_exception('convert_path_no_object', $pobject);
867 }
868 if (!method_exists($pobject, $this->get_processing_method())) {
869 throw new convert_path_exception('convert_path_missingmethod', $this->get_processing_method());
870 }
871 }
872}
873
874
875/**
876 * Exception being thrown by {@link convert_path} methods
877 */
878class convert_path_exception extends moodle_exception {
879
880 /**
881 * Constructor
882 *
883 * @param string $errorcode key for the corresponding error string
884 * @param mixed $a extra words and phrases that might be required by the error string
885 * @param string $debuginfo optional debugging information
886 */
887 public function __construct($errorcode, $a = null, $debuginfo = null) {
888 parent::__construct($errorcode, '', '', $a, $debuginfo);
889 }
890}