Merge branch 'MDL-37039-23' of git://github.com/damyon/moodle into MOODLE_23_STABLE
[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
23007e5d
DM
61 /** @var int used by the serial number {@link get_nextid()} */
62 private $nextid = 1;
63
1e2c7351
DM
64 /**
65 * Instructs the dispatcher to ignore all children below path processor returning it
66 */
67 const SKIP_ALL_CHILDREN = -991399;
68
fe50f530
DM
69 /**
70 * Log a message
71 *
72 * @see parent::log()
73 * @param string $message message text
74 * @param int $level message level {@example backup::LOG_WARNING}
75 * @param null|mixed $a additional information
76 * @param null|int $depth the message depth
77 * @param bool $display whether the message should be sent to the output, too
78 */
79 public function log($message, $level, $a = null, $depth = null, $display = false) {
80 parent::log('(moodle1) '.$message, $level, $a, $depth, $display);
81 }
82
1e2c7351
DM
83 /**
84 * Detects the Moodle 1.9 format of the backup directory
85 *
86 * @param string $tempdir the name of the backup directory
87 * @return null|string backup::FORMAT_MOODLE1 if the Moodle 1.9 is detected, null otherwise
88 */
89 public static function detect_format($tempdir) {
90 global $CFG;
91
7aa06e6d 92 $filepath = $CFG->tempdir . '/backup/' . $tempdir . '/moodle.xml';
1e2c7351
DM
93 if (file_exists($filepath)) {
94 // looks promising, lets load some information
95 $handle = fopen($filepath, 'r');
96 $first_chars = fread($handle, 200);
97 fclose($handle);
98
99 // check if it has the required strings
100 if (strpos($first_chars,'<?xml version="1.0" encoding="UTF-8"?>') !== false and
101 strpos($first_chars,'<MOODLE_BACKUP>') !== false and
102 strpos($first_chars,'<INFO>') !== false) {
103
104 return backup::FORMAT_MOODLE1;
105 }
106 }
107
108 return null;
109 }
110
111 /**
112 * Initialize the instance if needed, called by the constructor
113 *
114 * Here we create objects we need before the execution.
115 */
116 protected function init() {
117
118 // ask your mother first before going out playing with toys
119 parent::init();
120
fe50f530
DM
121 $this->log('initializing '.$this->get_name().' converter', backup::LOG_INFO);
122
1e2c7351 123 // good boy, prepare XML parser and processor
fe50f530 124 $this->log('setting xml parser', backup::LOG_DEBUG, null, 1);
1e2c7351
DM
125 $this->xmlparser = new progressive_parser();
126 $this->xmlparser->set_file($this->get_tempdir_path() . '/moodle.xml');
fe50f530 127 $this->log('setting xml processor', backup::LOG_DEBUG, null, 1);
1e2c7351
DM
128 $this->xmlprocessor = new moodle1_parser_processor($this);
129 $this->xmlparser->set_processor($this->xmlprocessor);
130
131 // make sure that MOD and BLOCK paths are visited
132 $this->xmlprocessor->add_path('/MOODLE_BACKUP/COURSE/MODULES/MOD');
133 $this->xmlprocessor->add_path('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK');
134
135 // register the conversion handlers
136 foreach (moodle1_handlers_factory::get_handlers($this) as $handler) {
fe50f530 137 $this->log('registering handler', backup::LOG_DEBUG, get_class($handler), 1);
1e2c7351
DM
138 $this->register_handler($handler, $handler->get_paths());
139 }
140 }
141
142 /**
143 * Converts the contents of the tempdir into the target format in the workdir
144 */
145 protected function execute() {
fe50f530 146 $this->log('creating the stash storage', backup::LOG_DEBUG);
9b5f1ad5 147 $this->create_stash_storage();
fe50f530
DM
148
149 $this->log('parsing moodle.xml starts', backup::LOG_DEBUG);
1e2c7351 150 $this->xmlparser->process();
fe50f530
DM
151 $this->log('parsing moodle.xml done', backup::LOG_DEBUG);
152
153 $this->log('dropping the stash storage', backup::LOG_DEBUG);
9b5f1ad5 154 $this->drop_stash_storage();
1e2c7351
DM
155 }
156
157 /**
158 * Register a handler for the given path elements
159 */
160 protected function register_handler(moodle1_handler $handler, array $elements) {
161
162 // first iteration, push them to new array, indexed by name
163 // to detect duplicates in names or paths
164 $names = array();
165 $paths = array();
166 foreach($elements as $element) {
167 if (!$element instanceof convert_path) {
168 throw new convert_exception('path_element_wrong_class', get_class($element));
169 }
170 if (array_key_exists($element->get_name(), $names)) {
171 throw new convert_exception('path_element_name_alreadyexists', $element->get_name());
172 }
173 if (array_key_exists($element->get_path(), $paths)) {
174 throw new convert_exception('path_element_path_alreadyexists', $element->get_path());
175 }
176 $names[$element->get_name()] = true;
177 $paths[$element->get_path()] = $element;
178 }
179
180 // now, for each element not having a processing object yet, assign the handler
181 // if the element is not a memeber of a group
182 foreach($paths as $key => $element) {
183 if (is_null($element->get_processing_object()) and !$this->grouped_parent_exists($element, $paths)) {
184 $paths[$key]->set_processing_object($handler);
185 }
186 // add the element path to the processor
187 $this->xmlprocessor->add_path($element->get_path(), $element->is_grouped());
188 }
189
190 // done, store the paths (duplicates by path are discarded)
191 $this->pathelements = array_merge($this->pathelements, $paths);
192
193 // remove the injected plugin name element from the MOD and BLOCK paths
194 // and register such collapsed path, too
195 foreach ($elements as $element) {
196 $path = $element->get_path();
197 $path = preg_replace('/^\/MOODLE_BACKUP\/COURSE\/MODULES\/MOD\/(\w+)\//', '/MOODLE_BACKUP/COURSE/MODULES/MOD/', $path);
198 $path = preg_replace('/^\/MOODLE_BACKUP\/COURSE\/BLOCKS\/BLOCK\/(\w+)\//', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/', $path);
199 if (!empty($path) and $path != $element->get_path()) {
200 $this->xmlprocessor->add_path($path, false);
201 }
202 }
203 }
204
205 /**
206 * Helper method used by {@link self::register_handler()}
207 *
208 * @param convert_path $pelement path element
209 * @param array of convert_path instances
210 * @return bool true if grouped parent was found, false otherwise
211 */
212 protected function grouped_parent_exists($pelement, $elements) {
213
214 foreach ($elements as $element) {
215 if ($pelement->get_path() == $element->get_path()) {
216 // don't compare against itself
217 continue;
218 }
219 // if the element is grouped and it is a parent of pelement, return true
220 if ($element->is_grouped() and strpos($pelement->get_path() . '/', $element->get_path()) === 0) {
221 return true;
222 }
223 }
224
225 // no grouped parent found
226 return false;
227 }
228
229 /**
230 * Process the data obtained from the XML parser processor
231 *
232 * This methods receives one chunk of information from the XML parser
233 * processor and dispatches it, following the naming rules.
234 * We are expanding the modules and blocks paths here to include the plugin's name.
235 *
236 * @param array $data
237 */
238 public function process_chunk($data) {
239
240 $path = $data['path'];
241
242 // expand the MOD paths so that they contain the module name
243 if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
244 $this->currentmod = strtoupper($data['tags']['MODTYPE']);
245 $path = '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod;
246
247 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
248 $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
249 }
250
251 // expand the BLOCK paths so that they contain the module name
252 if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
253 $this->currentblock = strtoupper($data['tags']['NAME']);
254 $path = '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock;
255
256 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
afaabdaf 257 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock, $path);
1e2c7351
DM
258 }
259
260 if ($path !== $data['path']) {
261 if (!array_key_exists($path, $this->pathelements)) {
262 // no handler registered for the transformed MOD or BLOCK path
fe50f530 263 $this->log('no handler attached', backup::LOG_WARNING, $path);
1e2c7351
DM
264 return;
265
266 } else {
267 // pretend as if the original $data contained the tranformed path
268 $data['path'] = $path;
269 }
270 }
271
272 if (!array_key_exists($data['path'], $this->pathelements)) {
273 // path added to the processor without the handler
274 throw new convert_exception('missing_path_handler', $data['path']);
275 }
276
beb7de37
DM
277 $element = $this->pathelements[$data['path']];
278 $object = $element->get_processing_object();
279 $method = $element->get_processing_method();
280 $returned = null; // data returned by the processing method, if any
1e2c7351
DM
281
282 if (empty($object)) {
a5f2b97b 283 throw new convert_exception('missing_processing_object', null, $data['path']);
1e2c7351
DM
284 }
285
286 // release the lock if we aren't anymore within children of it
287 if (!is_null($this->pathlock) and strpos($data['path'], $this->pathlock) === false) {
288 $this->pathlock = null;
289 }
290
291 // if the path is not locked, apply the element's recipes and dispatch
292 // the cooked tags to the processing method
293 if (is_null($this->pathlock)) {
beb7de37
DM
294 $rawdatatags = $data['tags'];
295 $data['tags'] = $element->apply_recipes($data['tags']);
46ff8b0e
DM
296
297 // if the processing method exists, give it a chance to modify data
298 if (method_exists($object, $method)) {
299 $returned = $object->$method($data['tags'], $rawdatatags);
300 }
1e2c7351
DM
301 }
302
303 // if the dispatched method returned SKIP_ALL_CHILDREN, remember the current path
304 // and lock it so that its children are not dispatched
beb7de37 305 if ($returned === self::SKIP_ALL_CHILDREN) {
1e2c7351
DM
306 // check we haven't any previous lock
307 if (!is_null($this->pathlock)) {
308 throw new convert_exception('already_locked_path', $data['path']);
309 }
310 // set the lock - nothing below the current path will be dispatched
311 $this->pathlock = $data['path'] . '/';
312
313 // if the method has returned any info, set element data to it
beb7de37 314 } else if (!is_null($returned)) {
fa30779b 315 $element->set_tags($returned);
1e2c7351
DM
316
317 // use just the cooked parsed data otherwise
318 } else {
fa30779b 319 $element->set_tags($data['tags']);
1e2c7351
DM
320 }
321 }
322
323 /**
324 * Executes operations required at the start of a watched path
325 *
6cfa5a32
DM
326 * For MOD and BLOCK paths, this is supported only for the sub-paths, not the root
327 * module/block element. For the illustration:
328 *
329 * You CAN'T attach on_xxx_start() listener to a path like
330 * /MOODLE_BACKUP/COURSE/MODULES/MOD/WORKSHOP because the <MOD> must
331 * be processed first in {@link self::process_chunk()} where $this->currentmod
332 * is set.
333 *
334 * You CAN attach some on_xxx_start() listener to a path like
335 * /MOODLE_BACKUP/COURSE/MODULES/MOD/WORKSHOP/SUBMISSIONS because it is
336 * a sub-path under <MOD> and we have $this->currentmod already set when the
337 * <SUBMISSIONS> is reached.
1e2c7351 338 *
1e2c7351
DM
339 * @param string $path in the original file
340 */
341 public function path_start_reached($path) {
a5fe5912 342
6cfa5a32
DM
343 if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
344 $this->currentmod = null;
345 $forbidden = true;
346
347 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
348 // expand the MOD paths so that they contain the module name
349 $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
350 }
351
352 if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
afaabdaf 353 $this->currentblock = null;
6cfa5a32
DM
354 $forbidden = true;
355
356 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
357 // expand the BLOCK paths so that they contain the module name
afaabdaf 358 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock, $path);
6cfa5a32
DM
359 }
360
a5fe5912
DM
361 if (empty($this->pathelements[$path])) {
362 return;
363 }
364
365 $element = $this->pathelements[$path];
366 $pobject = $element->get_processing_object();
46ff8b0e 367 $method = $element->get_start_method();
a5fe5912
DM
368
369 if (method_exists($pobject, $method)) {
6cfa5a32
DM
370 if (empty($forbidden)) {
371 $pobject->$method();
372
373 } else {
374 // this path is not supported because we do not know the module/block yet
375 throw new coding_exception('Attaching the on-start event listener to the root MOD or BLOCK element is forbidden.');
376 }
a5fe5912 377 }
1e2c7351
DM
378 }
379
380 /**
381 * Executes operations required at the end of a watched path
382 *
1e2c7351
DM
383 * @param string $path in the original file
384 */
385 public function path_end_reached($path) {
a5fe5912
DM
386
387 // expand the MOD paths so that they contain the current module name
388 if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
389 $path = '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod;
390
391 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
392 $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
393 }
394
395 // expand the BLOCK paths so that they contain the module name
396 if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
397 $path = '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock;
398
399 } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
afaabdaf 400 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock, $path);
a5fe5912
DM
401 }
402
403 if (empty($this->pathelements[$path])) {
404 return;
405 }
406
407 $element = $this->pathelements[$path];
408 $pobject = $element->get_processing_object();
46ff8b0e 409 $method = $element->get_end_method();
fa30779b 410 $tags = $element->get_tags();
a5fe5912
DM
411
412 if (method_exists($pobject, $method)) {
fa30779b 413 $pobject->$method($tags);
a5fe5912
DM
414 }
415 }
416
417 /**
9b5f1ad5 418 * Creates the temporary storage for stashed data
a5fe5912 419 *
9b5f1ad5 420 * This implementation uses backup_ids_temp table.
a5fe5912 421 */
9b5f1ad5
DM
422 public function create_stash_storage() {
423 backup_controller_dbops::create_backup_ids_temp_table($this->get_id());
a5fe5912
DM
424 }
425
426 /**
9b5f1ad5 427 * Drops the temporary storage of stashed data
a5fe5912 428 *
9b5f1ad5 429 * This implementation uses backup_ids_temp table.
a5fe5912 430 */
9b5f1ad5
DM
431 public function drop_stash_storage() {
432 backup_controller_dbops::drop_backup_ids_temp_table($this->get_id());
1e2c7351 433 }
a5fe5912 434
beb7de37 435 /**
9b5f1ad5 436 * Stores some information for later processing
beb7de37 437 *
9b5f1ad5
DM
438 * This implementation uses backup_ids_temp table to store data. Make
439 * sure that the $stashname + $itemid combo is unique.
beb7de37
DM
440 *
441 * @param string $stashname name of the stash
442 * @param mixed $info information to stash
9b5f1ad5 443 * @param int $itemid optional id for multiple infos within the same stashname
beb7de37 444 */
9b5f1ad5
DM
445 public function set_stash($stashname, $info, $itemid = 0) {
446 try {
447 restore_dbops::set_backup_ids_record($this->get_id(), $stashname, $itemid, 0, null, $info);
448
449 } catch (dml_exception $e) {
450 throw new moodle1_convert_storage_exception('unable_to_restore_stash', null, $e->getMessage());
451 }
beb7de37
DM
452 }
453
454 /**
455 * Restores a given stash stored previously by {@link self::set_stash()}
456 *
457 * @param string $stashname name of the stash
9b5f1ad5
DM
458 * @param int $itemid optional id for multiple infos within the same stashname
459 * @throws moodle1_convert_empty_storage_exception if the info has not been stashed previously
beb7de37
DM
460 * @return mixed stashed data
461 */
9b5f1ad5
DM
462 public function get_stash($stashname, $itemid = 0) {
463
464 $record = restore_dbops::get_backup_ids_record($this->get_id(), $stashname, $itemid);
465
466 if (empty($record)) {
6357693c 467 throw new moodle1_convert_empty_storage_exception('required_not_stashed_data', array($stashname, $itemid));
9b5f1ad5
DM
468 } else {
469 return $record->info;
470 }
beb7de37
DM
471 }
472
acc9a7b9
DM
473 /**
474 * Restores a given stash or returns the given default if there is no such stash
475 *
476 * @param string $stashname name of the stash
477 * @param int $itemid optional id for multiple infos within the same stashname
478 * @param mixed $default information to return if the info has not been stashed previously
479 * @return mixed stashed data or the default value
480 */
481 public function get_stash_or_default($stashname, $itemid = 0, $default = null) {
482 try {
483 return $this->get_stash($stashname, $itemid);
484 } catch (moodle1_convert_empty_storage_exception $e) {
485 return $default;
486 }
487 }
488
cd92d83b
DM
489 /**
490 * Returns the list of existing stashes
491 *
492 * @return array
493 */
494 public function get_stash_names() {
495 global $DB;
496
497 $search = array(
498 'backupid' => $this->get_id(),
499 );
500
501 return array_keys($DB->get_records('backup_ids_temp', $search, '', 'itemname'));
502 }
503
6d73f185
DM
504 /**
505 * Returns the list of stashed $itemids in the given stash
506 *
507 * @param string $stashname
508 * @return array
509 */
510 public function get_stash_itemids($stashname) {
511 global $DB;
512
513 $search = array(
514 'backupid' => $this->get_id(),
515 'itemname' => $stashname
516 );
517
518 return array_keys($DB->get_records('backup_ids_temp', $search, '', 'itemid'));
519 }
520
beb7de37
DM
521 /**
522 * Generates an artificial context id
523 *
524 * Moodle 1.9 backups do not contain any context information. But we need them
525 * in Moodle 2.x format so here we generate fictive context id for every given
526 * context level + instance combo.
527 *
26cac34a
DM
528 * CONTEXT_SYSTEM and CONTEXT_COURSE ignore the $instance as they represent a
529 * single system or the course being restored.
530 *
beb7de37
DM
531 * @see get_context_instance()
532 * @param int $level the context level, like CONTEXT_COURSE or CONTEXT_MODULE
533 * @param int $instance the instance id, for example $course->id for courses or $cm->id for activity modules
534 * @return int the context id
535 */
26cac34a 536 public function get_contextid($level, $instance = 0) {
beb7de37 537
9b5f1ad5 538 $stashname = 'context' . $level;
beb7de37 539
26cac34a
DM
540 if ($level == CONTEXT_SYSTEM or $level == CONTEXT_COURSE) {
541 $instance = 0;
542 }
543
d5d02635
DM
544 try {
545 // try the previously stashed id
546 return $this->get_stash($stashname, $instance);
beb7de37 547
d5d02635 548 } catch (moodle1_convert_empty_storage_exception $e) {
beb7de37 549 // this context level + instance is required for the first time
26cac34a
DM
550 $newid = $this->get_nextid();
551 $this->set_stash($stashname, $newid, $instance);
552 return $newid;
9b5f1ad5 553 }
beb7de37 554 }
179982a4 555
6700d288
DM
556 /**
557 * Simple autoincrement generator
558 *
559 * @return int the next number in a row of numbers
560 */
561 public function get_nextid() {
23007e5d 562 return $this->nextid++;
6700d288
DM
563 }
564
66f79e50
DM
565 /**
566 * Creates and returns new instance of the file manager
567 *
568 * @param int $contextid the default context id of the files being migrated
569 * @param string $component the default component name of the files being migrated
570 * @param string $filearea the default file area of the files being migrated
571 * @param int $itemid the default item id of the files being migrated
572 * @param int $userid initial user id of the files being migrated
573 * @return moodle1_file_manager
574 */
575 public function get_file_manager($contextid = null, $component = null, $filearea = null, $itemid = 0, $userid = null) {
576 return new moodle1_file_manager($this, $contextid, $component, $filearea, $itemid, $userid);
577 }
578
33560f50
DM
579 /**
580 * Creates and returns new instance of the inforef manager
581 *
582 * @param string $name the name of the annotator (like course, section, activity, block)
583 * @param int $id the id of the annotator if required
584 * @return moodle1_inforef_manager
585 */
586 public function get_inforef_manager($name, $id = 0) {
587 return new moodle1_inforef_manager($this, $name, $id);
588 }
589
590
c39226d9
DM
591 /**
592 * Migrates all course files referenced from the hypertext using the given filemanager
593 *
594 * This is typically used to convert images embedded into the intro fields.
595 *
596 * @param string $text hypertext containing $@FILEPHP@$ referenced
597 * @param moodle1_file_manager $fileman file manager to use for the file migration
598 * @return string the original $text with $@FILEPHP@$ references replaced with the new @@PLUGINFILE@@
599 */
600 public static function migrate_referenced_files($text, moodle1_file_manager $fileman) {
601
602 $files = self::find_referenced_files($text);
603 if (!empty($files)) {
604 foreach ($files as $file) {
85d91b6a
DM
605 try {
606 $fileman->migrate_file('course_files'.$file, dirname($file));
607 } catch (moodle1_convert_exception $e) {
608 // file probably does not exist
fe50f530 609 $fileman->log('error migrating file', backup::LOG_WARNING, 'course_files'.$file);
85d91b6a 610 }
c39226d9
DM
611 }
612 $text = self::rewrite_filephp_usage($text, $files);
613 }
614
615 return $text;
616 }
617
c818e2df
DM
618 /**
619 * Detects all links to file.php encoded via $@FILEPHP@$ and returns the files to migrate
620 *
c39226d9 621 * @see self::migrate_referenced_files()
c818e2df
DM
622 * @param string $text
623 * @return array
624 */
625 public static function find_referenced_files($text) {
626
627 $files = array();
628
629 if (empty($text) or is_numeric($text)) {
630 return $files;
631 }
632
633 $matches = array();
634 $pattern = '|(["\'])(\$@FILEPHP@\$.+?)\1|';
635 $result = preg_match_all($pattern, $text, $matches);
636 if ($result === false) {
637 throw new moodle1_convert_exception('error_while_searching_for_referenced_files');
638 }
639 if ($result == 0) {
640 return $files;
641 }
642 foreach ($matches[2] as $match) {
0dfc9101 643 $file = str_replace(array('$@FILEPHP@$', '$@SLASH@$', '$@FORCEDOWNLOAD@$'), array('', '/', ''), $match);
53499f8d
DM
644 if ($file === clean_param($file, PARAM_PATH)) {
645 $files[] = rawurldecode($file);
646 }
c818e2df
DM
647 }
648
649 return array_unique($files);
650 }
651
652 /**
653 * Given the list of migrated files, rewrites references to them from $@FILEPHP@$ form to the @@PLUGINFILE@@ one
654 *
c39226d9 655 * @see self::migrate_referenced_files()
c818e2df
DM
656 * @param string $text
657 * @param array $files
658 * @return string
659 */
660 public static function rewrite_filephp_usage($text, array $files) {
661
662 foreach ($files as $file) {
045053f6
DM
663 // Expect URLs properly encoded by default.
664 $parts = explode('/', $file);
665 $encoded = implode('/', array_map('rawurlencode', $parts));
666 $fileref = '$@FILEPHP@$'.str_replace('/', '$@SLASH@$', $encoded);
667 $text = str_replace($fileref.'$@FORCEDOWNLOAD@$', '@@PLUGINFILE@@'.$encoded.'?forcedownload=1', $text);
668 $text = str_replace($fileref, '@@PLUGINFILE@@'.$encoded, $text);
669 // Add support for URLs without any encoding.
c818e2df 670 $fileref = '$@FILEPHP@$'.str_replace('/', '$@SLASH@$', $file);
045053f6
DM
671 $text = str_replace($fileref.'$@FORCEDOWNLOAD@$', '@@PLUGINFILE@@'.$encoded.'?forcedownload=1', $text);
672 $text = str_replace($fileref, '@@PLUGINFILE@@'.$encoded, $text);
c818e2df
DM
673 }
674
675 return $text;
676 }
677
179982a4
DM
678 /**
679 * @see parent::description()
680 */
681 public static function description() {
682
683 return array(
684 'from' => backup::FORMAT_MOODLE1,
685 'to' => backup::FORMAT_MOODLE,
686 'cost' => 10,
687 );
688 }
1e2c7351
DM
689}
690
691
9b5f1ad5
DM
692/**
693 * Exception thrown by this converter
694 */
695class moodle1_convert_exception extends convert_exception {
696}
697
698
699/**
700 * Exception thrown by the temporary storage subsystem of moodle1_converter
701 */
702class moodle1_convert_storage_exception extends moodle1_convert_exception {
703}
704
705
706/**
707 * Exception thrown by the temporary storage subsystem of moodle1_converter
708 */
709class moodle1_convert_empty_storage_exception extends moodle1_convert_exception {
710}
711
712
1e2c7351 713/**
96f7c7ad 714 * XML parser processor used for processing parsed moodle.xml
1e2c7351
DM
715 */
716class moodle1_parser_processor extends grouped_parser_processor {
717
718 /** @var moodle1_converter */
719 protected $converter;
720
721 public function __construct(moodle1_converter $converter) {
722 $this->converter = $converter;
723 parent::__construct();
724 }
725
726 /**
8312ab67
DM
727 * Provides NULL decoding
728 *
729 * Note that we do not decode $@FILEPHP@$ and friends here as we are going to write them
730 * back immediately into another XML file.
1e2c7351
DM
731 */
732 public function process_cdata($cdata) {
1e2c7351 733
8312ab67 734 if ($cdata === '$@NULL@$') {
1e2c7351 735 return null;
1e2c7351 736 }
8312ab67
DM
737
738 return $cdata;
1e2c7351
DM
739 }
740
1e2c7351
DM
741 /**
742 * Dispatches the data chunk to the converter class
743 *
744 * @param array $data the chunk of parsed data
745 */
746 protected function dispatch_chunk($data) {
747 $this->converter->process_chunk($data);
748 }
749
750 /**
751 * Informs the converter at the start of a watched path
752 *
753 * @param string $path
754 */
755 protected function notify_path_start($path) {
756 $this->converter->path_start_reached($path);
757 }
758
759 /**
760 * Informs the converter at the end of a watched path
761 *
762 * @param string $path
763 */
764 protected function notify_path_end($path) {
765 $this->converter->path_end_reached($path);
766 }
767}
768
769
96f7c7ad
DM
770/**
771 * XML transformer that modifies the content of the files being written during the conversion
772 *
773 * @see backup_xml_transformer
774 */
775class moodle1_xml_transformer extends xml_contenttransformer {
776
777 /**
778 * Modify the content before it is writter to a file
779 *
780 * @param string|mixed $content
781 */
782 public function process($content) {
783
784 // the content should be a string. If array or object is given, try our best recursively
785 // but inform the developer
786 if (is_array($content)) {
787 debugging('Moodle1 XML transformer should not process arrays but plain content always', DEBUG_DEVELOPER);
788 foreach($content as $key => $plaincontent) {
789 $content[$key] = $this->process($plaincontent);
790 }
791 return $content;
792
793 } else if (is_object($content)) {
794 debugging('Moodle1 XML transformer should not process objects but plain content always', DEBUG_DEVELOPER);
795 foreach((array)$content as $key => $plaincontent) {
796 $content[$key] = $this->process($plaincontent);
797 }
798 return (object)$content;
799 }
800
801 // try to deal with some trivial cases first
802 if (is_null($content)) {
803 return '$@NULL@$';
804
805 } else if ($content === '') {
806 return '';
807
808 } else if (is_numeric($content)) {
809 return $content;
810
811 } else if (strlen($content) < 32) {
812 return $content;
813 }
814
96f7c7ad
DM
815 return $content;
816 }
817}
818
819
1e2c7351
DM
820/**
821 * Class representing a path to be converted from XML file
822 *
823 * This was created as a copy of {@link restore_path_element} and should be refactored
824 * probably.
825 */
826class convert_path {
827
828 /** @var string name of the element */
829 protected $name;
830
831 /** @var string path within the XML file this element will handle */
832 protected $path;
833
834 /** @var bool flag to define if this element will get child ones grouped or no */
835 protected $grouped;
836
837 /** @var object object instance in charge of processing this element. */
838 protected $pobject = null;
839
840 /** @var string the name of the processing method */
841 protected $pmethod = null;
842
46ff8b0e
DM
843 /** @var string the name of the path start event handler */
844 protected $smethod = null;
845
846 /** @var string the name of the path end event handler */
847 protected $emethod = null;
848
1e2c7351 849 /** @var mixed last data read for this element or returned data by processing method */
fa30779b 850 protected $tags = null;
1e2c7351 851
a5fe5912
DM
852 /** @var array of deprecated fields that are dropped */
853 protected $dropfields = array();
1e2c7351
DM
854
855 /** @var array of fields renaming */
856 protected $renamefields = array();
857
858 /** @var array of new fields to add and their initial values */
859 protected $newfields = array();
860
861 /**
862 * Constructor
863 *
864 * @param string $name name of the element
865 * @param string $path path of the element
866 * @param array $recipe basic description of the structure conversion
867 * @param bool $grouped to gather information in grouped mode or no
868 */
869 public function __construct($name, $path, array $recipe = array(), $grouped = false) {
870
871 $this->validate_name($name);
872
873 $this->name = $name;
874 $this->path = $path;
875 $this->grouped = $grouped;
876
46ff8b0e 877 // set the default method names
1e2c7351 878 $this->set_processing_method('process_' . $name);
46ff8b0e
DM
879 $this->set_start_method('on_'.$name.'_start');
880 $this->set_end_method('on_'.$name.'_end');
1e2c7351 881
034b0e4a
DM
882 if ($grouped and !empty($recipe)) {
883 throw new convert_path_exception('recipes_not_supported_for_grouped_elements');
884 }
885
a5fe5912
DM
886 if (isset($recipe['dropfields']) and is_array($recipe['dropfields'])) {
887 $this->set_dropped_fields($recipe['dropfields']);
1e2c7351
DM
888 }
889 if (isset($recipe['renamefields']) and is_array($recipe['renamefields'])) {
890 $this->set_renamed_fields($recipe['renamefields']);
891 }
892 if (isset($recipe['newfields']) and is_array($recipe['newfields'])) {
893 $this->set_new_fields($recipe['newfields']);
894 }
895 }
896
897 /**
898 * Validates and sets the given processing object
899 *
900 * @param object $pobject processing object, must provide a method to be called
901 */
902 public function set_processing_object($pobject) {
903 $this->validate_pobject($pobject);
904 $this->pobject = $pobject;
905 }
906
907 /**
908 * Sets the name of the processing method
909 *
910 * @param string $pmethod
911 */
912 public function set_processing_method($pmethod) {
913 $this->pmethod = $pmethod;
914 }
915
46ff8b0e
DM
916 /**
917 * Sets the name of the path start event listener
918 *
919 * @param string $smethod
920 */
921 public function set_start_method($smethod) {
922 $this->smethod = $smethod;
923 }
924
925 /**
926 * Sets the name of the path end event listener
927 *
928 * @param string $emethod
929 */
930 public function set_end_method($emethod) {
931 $this->emethod = $emethod;
932 }
933
1e2c7351 934 /**
fa30779b 935 * Sets the element tags
1e2c7351 936 *
fa30779b 937 * @param array $tags
1e2c7351 938 */
fa30779b
DM
939 public function set_tags($tags) {
940 $this->tags = $tags;
1e2c7351
DM
941 }
942
943 /**
a5fe5912 944 * Sets the list of deprecated fields to drop
1e2c7351
DM
945 *
946 * @param array $fields
947 */
a5fe5912
DM
948 public function set_dropped_fields(array $fields) {
949 $this->dropfields = $fields;
1e2c7351
DM
950 }
951
952 /**
953 * Sets the required new names of the current fields
954 *
955 * @param array $fields (string)$currentname => (string)$newname
956 */
957 public function set_renamed_fields(array $fields) {
958 $this->renamefields = $fields;
959 }
960
961 /**
962 * Sets the new fields and their values
963 *
964 * @param array $fields (string)$field => (mixed)value
965 */
966 public function set_new_fields(array $fields) {
967 $this->newfields = $fields;
968 }
969
970 /**
971 * Cooks the parsed tags data by applying known recipes
972 *
973 * Recipes are used for common trivial operations like adding new fields
974 * or renaming fields. The handler's processing method receives cooked
975 * data.
976 *
977 * @param array $data the contents of the element
978 * @return array
979 */
980 public function apply_recipes(array $data) {
981
982 $cooked = array();
983
984 foreach ($data as $name => $value) {
985 // lower case rocks!
986 $name = strtolower($name);
987
034b0e4a
DM
988 if (is_array($value)) {
989 if ($this->is_grouped()) {
990 $value = $this->apply_recipes($value);
991 } else {
992 throw new convert_path_exception('non_grouped_path_with_array_values');
993 }
994 }
995
a5fe5912
DM
996 // drop legacy fields
997 if (in_array($name, $this->dropfields)) {
998 continue;
999 }
1000
1e2c7351
DM
1001 // fields renaming
1002 if (array_key_exists($name, $this->renamefields)) {
1003 $name = $this->renamefields[$name];
1004 }
1005
1006 $cooked[$name] = $value;
1007 }
1008
1009 // adding new fields
1010 foreach ($this->newfields as $name => $value) {
1011 $cooked[$name] = $value;
1012 }
1013
1014 return $cooked;
1015 }
1016
1017 /**
1018 * @return string the element given name
1019 */
1020 public function get_name() {
1021 return $this->name;
1022 }
1023
1024 /**
1025 * @return string the path to the element
1026 */
1027 public function get_path() {
1028 return $this->path;
1029 }
1030
1031 /**
1032 * @return bool flag to define if this element will get child ones grouped or no
1033 */
1034 public function is_grouped() {
1035 return $this->grouped;
1036 }
1037
1038 /**
1039 * @return object the processing object providing the processing method
1040 */
1041 public function get_processing_object() {
1042 return $this->pobject;
1043 }
1044
1045 /**
1046 * @return string the name of the method to call to process the element
1047 */
1048 public function get_processing_method() {
1049 return $this->pmethod;
1050 }
1051
46ff8b0e
DM
1052 /**
1053 * @return string the name of the path start event listener
1054 */
1055 public function get_start_method() {
1056 return $this->smethod;
1057 }
1058
1059 /**
1060 * @return string the name of the path end event listener
1061 */
1062 public function get_end_method() {
1063 return $this->emethod;
1064 }
1065
1e2c7351
DM
1066 /**
1067 * @return mixed the element data
1068 */
fa30779b
DM
1069 public function get_tags() {
1070 return $this->tags;
1e2c7351
DM
1071 }
1072
1073
1074 /// end of public API //////////////////////////////////////////////////////
1075
1076 /**
1077 * Makes sure the given name is a valid element name
1078 *
1079 * Note it may look as if we used exceptions for code flow control here. That's not the case
1080 * as we actually validate the code, not the user data. And the code is supposed to be
1081 * correct.
1082 *
1083 * @param string @name the element given name
1084 * @throws convert_path_exception
1085 * @return void
1086 */
1087 protected function validate_name($name) {
1088 // Validate various name constraints, throwing exception if needed
1089 if (empty($name)) {
1090 throw new convert_path_exception('convert_path_emptyname', $name);
1091 }
1092 if (preg_replace('/\s/', '', $name) != $name) {
1093 throw new convert_path_exception('convert_path_whitespace', $name);
1094 }
1095 if (preg_replace('/[^\x30-\x39\x41-\x5a\x5f\x61-\x7a]/', '', $name) != $name) {
1096 throw new convert_path_exception('convert_path_notasciiname', $name);
1097 }
1098 }
1099
1100 /**
1101 * Makes sure that the given object is a valid processing object
1102 *
46ff8b0e
DM
1103 * The processing object must be an object providing at least element's processing method
1104 * or path-reached-end event listener or path-reached-start listener method.
1105 *
1e2c7351
DM
1106 * Note it may look as if we used exceptions for code flow control here. That's not the case
1107 * as we actually validate the code, not the user data. And the code is supposed to be
1108 * correct.
1109 *
1110 * @param object $pobject
1111 * @throws convert_path_exception
1112 * @return void
1113 */
1114 protected function validate_pobject($pobject) {
1115 if (!is_object($pobject)) {
46ff8b0e 1116 throw new convert_path_exception('convert_path_no_object', get_class($pobject));
1e2c7351 1117 }
46ff8b0e
DM
1118 if (!method_exists($pobject, $this->get_processing_method()) and
1119 !method_exists($pobject, $this->get_end_method()) and
1120 !method_exists($pobject, $this->get_start_method())) {
1121 throw new convert_path_exception('convert_path_missing_method', get_class($pobject));
1e2c7351
DM
1122 }
1123 }
1124}
1125
1126
1127/**
1128 * Exception being thrown by {@link convert_path} methods
1129 */
1130class convert_path_exception extends moodle_exception {
1131
1132 /**
1133 * Constructor
1134 *
1135 * @param string $errorcode key for the corresponding error string
1136 * @param mixed $a extra words and phrases that might be required by the error string
1137 * @param string $debuginfo optional debugging information
1138 */
1139 public function __construct($errorcode, $a = null, $debuginfo = null) {
1140 parent::__construct($errorcode, '', '', $a, $debuginfo);
1141 }
1142}
66f79e50
DM
1143
1144
1145/**
1146 * The class responsible for files migration
1147 *
1148 * The files in Moodle 1.9 backup are stored in moddata, user_files, group_files,
1149 * course_files and site_files folders.
1150 */
fe50f530 1151class moodle1_file_manager implements loggable {
66f79e50
DM
1152
1153 /** @var moodle1_converter instance we serve to */
1154 public $converter;
1155
1156 /** @var int context id of the files being migrated */
1157 public $contextid;
1158
1159 /** @var string component name of the files being migrated */
1160 public $component;
1161
1162 /** @var string file area of the files being migrated */
1163 public $filearea;
1164
1165 /** @var int item id of the files being migrated */
1166 public $itemid = 0;
1167
1168 /** @var int user id */
1169 public $userid;
1170
214c4924
DM
1171 /** @var string the root of the converter temp directory */
1172 protected $basepath;
1173
66f79e50
DM
1174 /** @var array of file ids that were migrated by this instance */
1175 protected $fileids = array();
1176
1177 /**
1178 * Constructor optionally accepting some default values for the migrated files
1179 *
1180 * @param moodle1_converter $converter the converter instance we serve to
1181 * @param int $contextid initial context id of the files being migrated
1182 * @param string $component initial component name of the files being migrated
1183 * @param string $filearea initial file area of the files being migrated
1184 * @param int $itemid initial item id of the files being migrated
1185 * @param int $userid initial user id of the files being migrated
1186 */
1187 public function __construct(moodle1_converter $converter, $contextid = null, $component = null, $filearea = null, $itemid = 0, $userid = null) {
214c4924 1188 // set the initial destination of the migrated files
66f79e50
DM
1189 $this->converter = $converter;
1190 $this->contextid = $contextid;
1191 $this->component = $component;
1192 $this->filearea = $filearea;
1193 $this->itemid = $itemid;
1194 $this->userid = $userid;
214c4924
DM
1195 // set other useful bits
1196 $this->basepath = $converter->get_tempdir_path();
66f79e50
DM
1197 }
1198
1199 /**
1200 * Migrates one given file stored on disk
1201 *
214c4924 1202 * @param string $sourcepath the path to the source local file within the backup archive {@example 'moddata/foobar/file.ext'}
aa97e0dd 1203 * @param string $filepath the file path of the migrated file, defaults to the root directory '/' {@example '/sub/dir/'}
66f79e50 1204 * @param string $filename the name of the migrated file, defaults to the same as the source file has
aa97e0dd 1205 * @param int $sortorder the sortorder of the file (main files have sortorder set to 1)
66f79e50
DM
1206 * @param int $timecreated override the timestamp of when the migrated file should appear as created
1207 * @param int $timemodified override the timestamp of when the migrated file should appear as modified
1208 * @return int id of the migrated file
1209 */
aa97e0dd 1210 public function migrate_file($sourcepath, $filepath = '/', $filename = null, $sortorder = 0, $timecreated = null, $timemodified = null) {
214c4924
DM
1211
1212 $sourcefullpath = $this->basepath.'/'.$sourcepath;
66f79e50 1213
53499f8d
DM
1214 if ($sourcefullpath !== clean_param($sourcefullpath, PARAM_PATH)) {
1215 throw new moodle1_convert_exception('file_invalid_path', $sourcefullpath);
1216 }
1217
66f79e50 1218 if (!is_readable($sourcefullpath)) {
214c4924 1219 throw new moodle1_convert_exception('file_not_readable', $sourcefullpath);
66f79e50
DM
1220 }
1221
aa97e0dd
DM
1222 // sanitize filepath
1223 if (empty($filepath)) {
1224 $filepath = '/';
1225 }
1226 if (substr($filepath, -1) !== '/') {
1227 $filepath .= '/';
1228 }
66f79e50
DM
1229 $filepath = clean_param($filepath, PARAM_PATH);
1230
f8311def 1231 if (textlib::strlen($filepath) > 255) {
66f79e50
DM
1232 throw new moodle1_convert_exception('file_path_longer_than_255_chars');
1233 }
1234
1235 if (is_null($filename)) {
1236 $filename = basename($sourcefullpath);
1237 }
1238
1239 $filename = clean_param($filename, PARAM_FILE);
1240
1241 if ($filename === '') {
1242 throw new moodle1_convert_exception('unsupported_chars_in_filename');
1243 }
1244
1245 if (is_null($timecreated)) {
1246 $timecreated = filectime($sourcefullpath);
1247 }
1248
1249 if (is_null($timemodified)) {
1250 $timemodified = filemtime($sourcefullpath);
1251 }
1252
1253 $filerecord = $this->make_file_record(array(
1254 'filepath' => $filepath,
1255 'filename' => $filename,
aa97e0dd 1256 'sortorder' => $sortorder,
66f79e50
DM
1257 'mimetype' => mimeinfo('type', $sourcefullpath),
1258 'timecreated' => $timecreated,
1259 'timemodified' => $timemodified,
1260 ));
1261
1262 list($filerecord['contenthash'], $filerecord['filesize'], $newfile) = $this->add_file_to_pool($sourcefullpath);
1263 $this->stash_file($filerecord);
1264
1265 return $filerecord['id'];
1266 }
1267
1268 /**
1269 * Migrates all files in the given directory
1270 *
214c4924 1271 * @param string $rootpath path within the backup archive to the root directory containing the files {@example 'course_files'}
66f79e50 1272 * @param string $relpath relative path used during the recursion - do not provide when calling this!
93264625 1273 * @return array ids of the migrated files, empty array if the $rootpath not found
66f79e50
DM
1274 */
1275 public function migrate_directory($rootpath, $relpath='/') {
1276
e2f455b8
DM
1277 // Check the trailing slash in the $rootpath
1278 if (substr($rootpath, -1) === '/') {
1279 $rootpath = substr($rootpath, 0, strlen($rootpath) - 1);
1280 }
1281
93264625
DM
1282 if (!file_exists($this->basepath.'/'.$rootpath.$relpath)) {
1283 return array();
1284 }
1285
66f79e50
DM
1286 $fileids = array();
1287
1288 // make the fake file record for the directory itself
1289 $filerecord = $this->make_file_record(array('filepath' => $relpath, 'filename' => '.'));
1290 $this->stash_file($filerecord);
1291 $fileids[] = $filerecord['id'];
1292
214c4924 1293 $items = new DirectoryIterator($this->basepath.'/'.$rootpath.$relpath);
66f79e50
DM
1294
1295 foreach ($items as $item) {
1296
1297 if ($item->isDot()) {
1298 continue;
1299 }
1300
1301 if ($item->isLink()) {
1302 throw new moodle1_convert_exception('unexpected_symlink');
1303 }
1304
1305 if ($item->isFile()) {
214c4924 1306 $fileids[] = $this->migrate_file(substr($item->getPathname(), strlen($this->basepath.'/')),
aa97e0dd 1307 $relpath, $item->getFilename(), 0, $item->getCTime(), $item->getMTime());
66f79e50
DM
1308
1309 } else {
1310 $dirname = clean_param($item->getFilename(), PARAM_PATH);
1311
1312 if ($dirname === '') {
1313 throw new moodle1_convert_exception('unsupported_chars_in_filename');
1314 }
1315
1316 // migrate subdirectories recursively
1317 $fileids = array_merge($fileids, $this->migrate_directory($rootpath, $relpath.$item->getFilename().'/'));
1318 }
1319 }
1320
1321 return $fileids;
1322 }
1323
1324 /**
1325 * Returns the list of all file ids migrated by this instance so far
1326 *
1327 * @return array of int
1328 */
1329 public function get_fileids() {
1330 return $this->fileids;
1331 }
1332
d61ed0af
DM
1333 /**
1334 * Explicitly clear the list of file ids migrated by this instance so far
1335 */
1336 public function reset_fileids() {
1337 $this->fileids = array();
1338 }
1339
fe50f530
DM
1340 /**
1341 * Log a message using the converter's logging mechanism
1342 *
1343 * @param string $message message text
1344 * @param int $level message level {@example backup::LOG_WARNING}
1345 * @param null|mixed $a additional information
1346 * @param null|int $depth the message depth
1347 * @param bool $display whether the message should be sent to the output, too
1348 */
1349 public function log($message, $level, $a = null, $depth = null, $display = false) {
1350 $this->converter->log($message, $level, $a, $depth, $display);
1351 }
1352
66f79e50
DM
1353 /// internal implementation details ////////////////////////////////////////
1354
1355 /**
1356 * Prepares a fake record from the files table
1357 *
1358 * @param array $fileinfo explicit file data
1359 * @return array
1360 */
1361 protected function make_file_record(array $fileinfo) {
1362
1363 $defaultrecord = array(
1364 'contenthash' => 'da39a3ee5e6b4b0d3255bfef95601890afd80709', // sha1 of an empty file
1365 'contextid' => $this->contextid,
1366 'component' => $this->component,
1367 'filearea' => $this->filearea,
1368 'itemid' => $this->itemid,
1369 'filepath' => null,
1370 'filename' => null,
1371 'filesize' => 0,
1372 'userid' => $this->userid,
1373 'mimetype' => null,
1374 'status' => 0,
1375 'timecreated' => $now = time(),
1376 'timemodified' => $now,
1377 'source' => null,
1378 'author' => null,
1379 'license' => null,
1380 'sortorder' => 0,
1381 );
1382
1383 if (!array_key_exists('id', $fileinfo)) {
1384 $defaultrecord['id'] = $this->converter->get_nextid();
1385 }
1386
1387 // override the default values with the explicit data provided and return
1388 return array_merge($defaultrecord, $fileinfo);
1389 }
1390
1391 /**
1392 * Copies the given file to the pool directory
1393 *
1394 * Returns an array containing SHA1 hash of the file contents, the file size
1395 * and a flag indicating whether the file was actually added to the pool or whether
1396 * it was already there.
1397 *
1398 * @param string $pathname the full path to the file
1399 * @return array with keys (string)contenthash, (int)filesize, (bool)newfile
1400 */
1401 protected function add_file_to_pool($pathname) {
1402
1403 if (!is_readable($pathname)) {
1404 throw new moodle1_convert_exception('file_not_readable');
1405 }
1406
1407 $contenthash = sha1_file($pathname);
1408 $filesize = filesize($pathname);
1409 $hashpath = $this->converter->get_workdir_path().'/files/'.substr($contenthash, 0, 2);
1410 $hashfile = "$hashpath/$contenthash";
1411
1412 if (file_exists($hashfile)) {
1413 if (filesize($hashfile) !== $filesize) {
1414 // congratulations! you have found two files with different size and the same
1415 // content hash. or, something were wrong (which is more likely)
1416 throw new moodle1_convert_exception('same_hash_different_size');
1417 }
1418 $newfile = false;
1419
1420 } else {
1421 check_dir_exists($hashpath);
1422 $newfile = true;
1423
1424 if (!copy($pathname, $hashfile)) {
1425 throw new moodle1_convert_exception('unable_to_copy_file');
1426 }
1427
1428 if (filesize($hashfile) !== $filesize) {
1429 throw new moodle1_convert_exception('filesize_different_after_copy');
1430 }
1431 }
1432
1433 return array($contenthash, $filesize, $newfile);
1434 }
1435
1436 /**
1437 * Stashes the file record into 'files' stash and adds the record id to list of migrated files
1438 *
1439 * @param array $filerecord
1440 */
1441 protected function stash_file(array $filerecord) {
1442 $this->converter->set_stash('files', $filerecord, $filerecord['id']);
1443 $this->fileids[] = $filerecord['id'];
1444 }
1445}
33560f50
DM
1446
1447
1448/**
1449 * Helper class that handles ids annotations for inforef.xml files
1450 */
1451class moodle1_inforef_manager {
1452
1453 /** @var string the name of the annotator we serve to (like course, section, activity, block) */
1454 protected $annotator = null;
1455
1456 /** @var int the id of the annotator if it can have multiple instances */
1457 protected $annotatorid = null;
1458
1459 /** @var array the actual storage of references, currently implemented as a in-memory structure */
1460 private $refs = array();
1461
1462 /**
1463 * Creates new instance of the manager for the given annotator
1464 *
1465 * The identification of the annotator we serve to may be important in the future
1466 * when we move the actual storage of the references from memory to a persistent storage.
1467 *
1468 * @param moodle1_converter $converter
1469 * @param string $name the name of the annotator (like course, section, activity, block)
1470 * @param int $id the id of the annotator if required
1471 */
1472 public function __construct(moodle1_converter $converter, $name, $id = 0) {
1473 $this->annotator = $name;
1474 $this->annotatorid = $id;
1475 }
1476
1477 /**
1478 * Adds a reference
1479 *
1480 * @param string $item the name of referenced item (like user, file, scale, outcome or grade_item)
1481 * @param int $id the value of the reference
1482 */
1483 public function add_ref($item, $id) {
1484 $this->validate_item($item);
1485 $this->refs[$item][$id] = true;
1486 }
1487
1488 /**
1489 * Adds a bulk of references
1490 *
1491 * @param string $item the name of referenced item (like user, file, scale, outcome or grade_item)
1492 * @param array $ids the list of referenced ids
1493 */
1494 public function add_refs($item, array $ids) {
1495 $this->validate_item($item);
1496 foreach ($ids as $id) {
1497 $this->refs[$item][$id] = true;
1498 }
1499 }
1500
1501 /**
1502 * Writes the current references using a given opened xml writer
1503 *
1504 * @param xml_writer $xmlwriter
1505 */
1506 public function write_refs(xml_writer $xmlwriter) {
1507 $xmlwriter->begin_tag('inforef');
1508 foreach ($this->refs as $item => $ids) {
1509 $xmlwriter->begin_tag($item.'ref');
1510 foreach (array_keys($ids) as $id) {
1511 $xmlwriter->full_tag($item, $id);
1512 }
1513 $xmlwriter->end_tag($item.'ref');
1514 }
1515 $xmlwriter->end_tag('inforef');
1516 }
1517
1518 /**
1519 * Makes sure that the given name is a valid citizen of inforef.xml file
1520 *
1521 * @see backup_helper::get_inforef_itemnames()
1522 * @param string $item the name of reference (like user, file, scale, outcome or grade_item)
1523 * @throws coding_exception
1524 */
1525 protected function validate_item($item) {
1526
1527 $allowed = array(
1528 'user' => true,
1529 'grouping' => true,
1530 'group' => true,
1531 'role' => true,
1532 'file' => true,
1533 'scale' => true,
1534 'outcome' => true,
1535 'grade_item' => true,
1536 'question_category' => true
1537 );
1538
1539 if (!isset($allowed[$item])) {
1540 throw new coding_exception('Invalid inforef item type');
1541 }
1542 }
1543}