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