MDL-22414 Added scales conversion handler
[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
92 $filepath = $CFG->dataroot . '/temp/backup/' . $tempdir . '/moodle.xml';
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) {
257 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentmod, $path);
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)) {
283 throw new convert_exception('missing_processing_object', $object);
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') {
353 $this->currentmod = null;
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
358 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentmod, $path);
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) {
400 $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentmod, $path);
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
cd92d83b
DM
473 /**
474 * Returns the list of existing stashes
475 *
476 * @return array
477 */
478 public function get_stash_names() {
479 global $DB;
480
481 $search = array(
482 'backupid' => $this->get_id(),
483 );
484
485 return array_keys($DB->get_records('backup_ids_temp', $search, '', 'itemname'));
486 }
487
6d73f185
DM
488 /**
489 * Returns the list of stashed $itemids in the given stash
490 *
491 * @param string $stashname
492 * @return array
493 */
494 public function get_stash_itemids($stashname) {
495 global $DB;
496
497 $search = array(
498 'backupid' => $this->get_id(),
499 'itemname' => $stashname
500 );
501
502 return array_keys($DB->get_records('backup_ids_temp', $search, '', 'itemid'));
503 }
504
beb7de37
DM
505 /**
506 * Generates an artificial context id
507 *
508 * Moodle 1.9 backups do not contain any context information. But we need them
509 * in Moodle 2.x format so here we generate fictive context id for every given
510 * context level + instance combo.
511 *
26cac34a
DM
512 * CONTEXT_SYSTEM and CONTEXT_COURSE ignore the $instance as they represent a
513 * single system or the course being restored.
514 *
beb7de37
DM
515 * @see get_context_instance()
516 * @param int $level the context level, like CONTEXT_COURSE or CONTEXT_MODULE
517 * @param int $instance the instance id, for example $course->id for courses or $cm->id for activity modules
518 * @return int the context id
519 */
26cac34a 520 public function get_contextid($level, $instance = 0) {
beb7de37 521
9b5f1ad5 522 $stashname = 'context' . $level;
beb7de37 523
26cac34a
DM
524 if ($level == CONTEXT_SYSTEM or $level == CONTEXT_COURSE) {
525 $instance = 0;
526 }
527
d5d02635
DM
528 try {
529 // try the previously stashed id
530 return $this->get_stash($stashname, $instance);
beb7de37 531
d5d02635 532 } catch (moodle1_convert_empty_storage_exception $e) {
beb7de37 533 // this context level + instance is required for the first time
26cac34a
DM
534 $newid = $this->get_nextid();
535 $this->set_stash($stashname, $newid, $instance);
536 return $newid;
9b5f1ad5 537 }
beb7de37 538 }
179982a4 539
6700d288
DM
540 /**
541 * Simple autoincrement generator
542 *
543 * @return int the next number in a row of numbers
544 */
545 public function get_nextid() {
23007e5d 546 return $this->nextid++;
6700d288
DM
547 }
548
66f79e50
DM
549 /**
550 * Creates and returns new instance of the file manager
551 *
552 * @param int $contextid the default context id of the files being migrated
553 * @param string $component the default component name of the files being migrated
554 * @param string $filearea the default file area of the files being migrated
555 * @param int $itemid the default item id of the files being migrated
556 * @param int $userid initial user id of the files being migrated
557 * @return moodle1_file_manager
558 */
559 public function get_file_manager($contextid = null, $component = null, $filearea = null, $itemid = 0, $userid = null) {
560 return new moodle1_file_manager($this, $contextid, $component, $filearea, $itemid, $userid);
561 }
562
c39226d9
DM
563 /**
564 * Migrates all course files referenced from the hypertext using the given filemanager
565 *
566 * This is typically used to convert images embedded into the intro fields.
567 *
568 * @param string $text hypertext containing $@FILEPHP@$ referenced
569 * @param moodle1_file_manager $fileman file manager to use for the file migration
570 * @return string the original $text with $@FILEPHP@$ references replaced with the new @@PLUGINFILE@@
571 */
572 public static function migrate_referenced_files($text, moodle1_file_manager $fileman) {
573
574 $files = self::find_referenced_files($text);
575 if (!empty($files)) {
576 foreach ($files as $file) {
85d91b6a
DM
577 try {
578 $fileman->migrate_file('course_files'.$file, dirname($file));
579 } catch (moodle1_convert_exception $e) {
580 // file probably does not exist
fe50f530 581 $fileman->log('error migrating file', backup::LOG_WARNING, 'course_files'.$file);
85d91b6a 582 }
c39226d9
DM
583 }
584 $text = self::rewrite_filephp_usage($text, $files);
585 }
586
587 return $text;
588 }
589
c818e2df
DM
590 /**
591 * Detects all links to file.php encoded via $@FILEPHP@$ and returns the files to migrate
592 *
c39226d9 593 * @see self::migrate_referenced_files()
c818e2df
DM
594 * @param string $text
595 * @return array
596 */
597 public static function find_referenced_files($text) {
598
599 $files = array();
600
601 if (empty($text) or is_numeric($text)) {
602 return $files;
603 }
604
605 $matches = array();
606 $pattern = '|(["\'])(\$@FILEPHP@\$.+?)\1|';
607 $result = preg_match_all($pattern, $text, $matches);
608 if ($result === false) {
609 throw new moodle1_convert_exception('error_while_searching_for_referenced_files');
610 }
611 if ($result == 0) {
612 return $files;
613 }
614 foreach ($matches[2] as $match) {
615 $files[] = str_replace(array('$@FILEPHP@$', '$@SLASH@$', '$@FORCEDOWNLOAD@$'), array('', '/', ''), $match);
616 }
617
618 return array_unique($files);
619 }
620
621 /**
622 * Given the list of migrated files, rewrites references to them from $@FILEPHP@$ form to the @@PLUGINFILE@@ one
623 *
c39226d9 624 * @see self::migrate_referenced_files()
c818e2df
DM
625 * @param string $text
626 * @param array $files
627 * @return string
628 */
629 public static function rewrite_filephp_usage($text, array $files) {
630
631 foreach ($files as $file) {
632 $fileref = '$@FILEPHP@$'.str_replace('/', '$@SLASH@$', $file);
633 $text = str_replace($fileref.'$@FORCEDOWNLOAD@$', '@@PLUGINFILE@@'.$file.'?forcedownload=1', $text);
634 $text = str_replace($fileref, '@@PLUGINFILE@@'.$file, $text);
635 }
636
637 return $text;
638 }
639
179982a4
DM
640 /**
641 * @see parent::description()
642 */
643 public static function description() {
644
645 return array(
646 'from' => backup::FORMAT_MOODLE1,
647 'to' => backup::FORMAT_MOODLE,
648 'cost' => 10,
649 );
650 }
1e2c7351
DM
651}
652
653
9b5f1ad5
DM
654/**
655 * Exception thrown by this converter
656 */
657class moodle1_convert_exception extends convert_exception {
658}
659
660
661/**
662 * Exception thrown by the temporary storage subsystem of moodle1_converter
663 */
664class moodle1_convert_storage_exception extends moodle1_convert_exception {
665}
666
667
668/**
669 * Exception thrown by the temporary storage subsystem of moodle1_converter
670 */
671class moodle1_convert_empty_storage_exception extends moodle1_convert_exception {
672}
673
674
1e2c7351 675/**
96f7c7ad 676 * XML parser processor used for processing parsed moodle.xml
1e2c7351
DM
677 */
678class moodle1_parser_processor extends grouped_parser_processor {
679
680 /** @var moodle1_converter */
681 protected $converter;
682
683 public function __construct(moodle1_converter $converter) {
684 $this->converter = $converter;
685 parent::__construct();
686 }
687
688 /**
8312ab67
DM
689 * Provides NULL decoding
690 *
691 * Note that we do not decode $@FILEPHP@$ and friends here as we are going to write them
692 * back immediately into another XML file.
1e2c7351
DM
693 */
694 public function process_cdata($cdata) {
1e2c7351 695
8312ab67 696 if ($cdata === '$@NULL@$') {
1e2c7351 697 return null;
1e2c7351 698 }
8312ab67
DM
699
700 return $cdata;
1e2c7351
DM
701 }
702
1e2c7351
DM
703 /**
704 * Dispatches the data chunk to the converter class
705 *
706 * @param array $data the chunk of parsed data
707 */
708 protected function dispatch_chunk($data) {
709 $this->converter->process_chunk($data);
710 }
711
712 /**
713 * Informs the converter at the start of a watched path
714 *
715 * @param string $path
716 */
717 protected function notify_path_start($path) {
718 $this->converter->path_start_reached($path);
719 }
720
721 /**
722 * Informs the converter at the end of a watched path
723 *
724 * @param string $path
725 */
726 protected function notify_path_end($path) {
727 $this->converter->path_end_reached($path);
728 }
729}
730
731
96f7c7ad
DM
732/**
733 * XML transformer that modifies the content of the files being written during the conversion
734 *
735 * @see backup_xml_transformer
736 */
737class moodle1_xml_transformer extends xml_contenttransformer {
738
739 /**
740 * Modify the content before it is writter to a file
741 *
742 * @param string|mixed $content
743 */
744 public function process($content) {
745
746 // the content should be a string. If array or object is given, try our best recursively
747 // but inform the developer
748 if (is_array($content)) {
749 debugging('Moodle1 XML transformer should not process arrays but plain content always', DEBUG_DEVELOPER);
750 foreach($content as $key => $plaincontent) {
751 $content[$key] = $this->process($plaincontent);
752 }
753 return $content;
754
755 } else if (is_object($content)) {
756 debugging('Moodle1 XML transformer should not process objects but plain content always', DEBUG_DEVELOPER);
757 foreach((array)$content as $key => $plaincontent) {
758 $content[$key] = $this->process($plaincontent);
759 }
760 return (object)$content;
761 }
762
763 // try to deal with some trivial cases first
764 if (is_null($content)) {
765 return '$@NULL@$';
766
767 } else if ($content === '') {
768 return '';
769
770 } else if (is_numeric($content)) {
771 return $content;
772
773 } else if (strlen($content) < 32) {
774 return $content;
775 }
776
96f7c7ad
DM
777 return $content;
778 }
779}
780
781
1e2c7351
DM
782/**
783 * Class representing a path to be converted from XML file
784 *
785 * This was created as a copy of {@link restore_path_element} and should be refactored
786 * probably.
787 */
788class convert_path {
789
790 /** @var string name of the element */
791 protected $name;
792
793 /** @var string path within the XML file this element will handle */
794 protected $path;
795
796 /** @var bool flag to define if this element will get child ones grouped or no */
797 protected $grouped;
798
799 /** @var object object instance in charge of processing this element. */
800 protected $pobject = null;
801
802 /** @var string the name of the processing method */
803 protected $pmethod = null;
804
46ff8b0e
DM
805 /** @var string the name of the path start event handler */
806 protected $smethod = null;
807
808 /** @var string the name of the path end event handler */
809 protected $emethod = null;
810
1e2c7351 811 /** @var mixed last data read for this element or returned data by processing method */
fa30779b 812 protected $tags = null;
1e2c7351 813
a5fe5912
DM
814 /** @var array of deprecated fields that are dropped */
815 protected $dropfields = array();
1e2c7351
DM
816
817 /** @var array of fields renaming */
818 protected $renamefields = array();
819
820 /** @var array of new fields to add and their initial values */
821 protected $newfields = array();
822
823 /**
824 * Constructor
825 *
826 * @param string $name name of the element
827 * @param string $path path of the element
828 * @param array $recipe basic description of the structure conversion
829 * @param bool $grouped to gather information in grouped mode or no
830 */
831 public function __construct($name, $path, array $recipe = array(), $grouped = false) {
832
833 $this->validate_name($name);
834
835 $this->name = $name;
836 $this->path = $path;
837 $this->grouped = $grouped;
838
46ff8b0e 839 // set the default method names
1e2c7351 840 $this->set_processing_method('process_' . $name);
46ff8b0e
DM
841 $this->set_start_method('on_'.$name.'_start');
842 $this->set_end_method('on_'.$name.'_end');
1e2c7351 843
034b0e4a
DM
844 if ($grouped and !empty($recipe)) {
845 throw new convert_path_exception('recipes_not_supported_for_grouped_elements');
846 }
847
a5fe5912
DM
848 if (isset($recipe['dropfields']) and is_array($recipe['dropfields'])) {
849 $this->set_dropped_fields($recipe['dropfields']);
1e2c7351
DM
850 }
851 if (isset($recipe['renamefields']) and is_array($recipe['renamefields'])) {
852 $this->set_renamed_fields($recipe['renamefields']);
853 }
854 if (isset($recipe['newfields']) and is_array($recipe['newfields'])) {
855 $this->set_new_fields($recipe['newfields']);
856 }
857 }
858
859 /**
860 * Validates and sets the given processing object
861 *
862 * @param object $pobject processing object, must provide a method to be called
863 */
864 public function set_processing_object($pobject) {
865 $this->validate_pobject($pobject);
866 $this->pobject = $pobject;
867 }
868
869 /**
870 * Sets the name of the processing method
871 *
872 * @param string $pmethod
873 */
874 public function set_processing_method($pmethod) {
875 $this->pmethod = $pmethod;
876 }
877
46ff8b0e
DM
878 /**
879 * Sets the name of the path start event listener
880 *
881 * @param string $smethod
882 */
883 public function set_start_method($smethod) {
884 $this->smethod = $smethod;
885 }
886
887 /**
888 * Sets the name of the path end event listener
889 *
890 * @param string $emethod
891 */
892 public function set_end_method($emethod) {
893 $this->emethod = $emethod;
894 }
895
1e2c7351 896 /**
fa30779b 897 * Sets the element tags
1e2c7351 898 *
fa30779b 899 * @param array $tags
1e2c7351 900 */
fa30779b
DM
901 public function set_tags($tags) {
902 $this->tags = $tags;
1e2c7351
DM
903 }
904
905 /**
a5fe5912 906 * Sets the list of deprecated fields to drop
1e2c7351
DM
907 *
908 * @param array $fields
909 */
a5fe5912
DM
910 public function set_dropped_fields(array $fields) {
911 $this->dropfields = $fields;
1e2c7351
DM
912 }
913
914 /**
915 * Sets the required new names of the current fields
916 *
917 * @param array $fields (string)$currentname => (string)$newname
918 */
919 public function set_renamed_fields(array $fields) {
920 $this->renamefields = $fields;
921 }
922
923 /**
924 * Sets the new fields and their values
925 *
926 * @param array $fields (string)$field => (mixed)value
927 */
928 public function set_new_fields(array $fields) {
929 $this->newfields = $fields;
930 }
931
932 /**
933 * Cooks the parsed tags data by applying known recipes
934 *
935 * Recipes are used for common trivial operations like adding new fields
936 * or renaming fields. The handler's processing method receives cooked
937 * data.
938 *
939 * @param array $data the contents of the element
940 * @return array
941 */
942 public function apply_recipes(array $data) {
943
944 $cooked = array();
945
946 foreach ($data as $name => $value) {
947 // lower case rocks!
948 $name = strtolower($name);
949
034b0e4a
DM
950 if (is_array($value)) {
951 if ($this->is_grouped()) {
952 $value = $this->apply_recipes($value);
953 } else {
954 throw new convert_path_exception('non_grouped_path_with_array_values');
955 }
956 }
957
a5fe5912
DM
958 // drop legacy fields
959 if (in_array($name, $this->dropfields)) {
960 continue;
961 }
962
1e2c7351
DM
963 // fields renaming
964 if (array_key_exists($name, $this->renamefields)) {
965 $name = $this->renamefields[$name];
966 }
967
968 $cooked[$name] = $value;
969 }
970
971 // adding new fields
972 foreach ($this->newfields as $name => $value) {
973 $cooked[$name] = $value;
974 }
975
976 return $cooked;
977 }
978
979 /**
980 * @return string the element given name
981 */
982 public function get_name() {
983 return $this->name;
984 }
985
986 /**
987 * @return string the path to the element
988 */
989 public function get_path() {
990 return $this->path;
991 }
992
993 /**
994 * @return bool flag to define if this element will get child ones grouped or no
995 */
996 public function is_grouped() {
997 return $this->grouped;
998 }
999
1000 /**
1001 * @return object the processing object providing the processing method
1002 */
1003 public function get_processing_object() {
1004 return $this->pobject;
1005 }
1006
1007 /**
1008 * @return string the name of the method to call to process the element
1009 */
1010 public function get_processing_method() {
1011 return $this->pmethod;
1012 }
1013
46ff8b0e
DM
1014 /**
1015 * @return string the name of the path start event listener
1016 */
1017 public function get_start_method() {
1018 return $this->smethod;
1019 }
1020
1021 /**
1022 * @return string the name of the path end event listener
1023 */
1024 public function get_end_method() {
1025 return $this->emethod;
1026 }
1027
1e2c7351
DM
1028 /**
1029 * @return mixed the element data
1030 */
fa30779b
DM
1031 public function get_tags() {
1032 return $this->tags;
1e2c7351
DM
1033 }
1034
1035
1036 /// end of public API //////////////////////////////////////////////////////
1037
1038 /**
1039 * Makes sure the given name is a valid element name
1040 *
1041 * Note it may look as if we used exceptions for code flow control here. That's not the case
1042 * as we actually validate the code, not the user data. And the code is supposed to be
1043 * correct.
1044 *
1045 * @param string @name the element given name
1046 * @throws convert_path_exception
1047 * @return void
1048 */
1049 protected function validate_name($name) {
1050 // Validate various name constraints, throwing exception if needed
1051 if (empty($name)) {
1052 throw new convert_path_exception('convert_path_emptyname', $name);
1053 }
1054 if (preg_replace('/\s/', '', $name) != $name) {
1055 throw new convert_path_exception('convert_path_whitespace', $name);
1056 }
1057 if (preg_replace('/[^\x30-\x39\x41-\x5a\x5f\x61-\x7a]/', '', $name) != $name) {
1058 throw new convert_path_exception('convert_path_notasciiname', $name);
1059 }
1060 }
1061
1062 /**
1063 * Makes sure that the given object is a valid processing object
1064 *
46ff8b0e
DM
1065 * The processing object must be an object providing at least element's processing method
1066 * or path-reached-end event listener or path-reached-start listener method.
1067 *
1e2c7351
DM
1068 * Note it may look as if we used exceptions for code flow control here. That's not the case
1069 * as we actually validate the code, not the user data. And the code is supposed to be
1070 * correct.
1071 *
1072 * @param object $pobject
1073 * @throws convert_path_exception
1074 * @return void
1075 */
1076 protected function validate_pobject($pobject) {
1077 if (!is_object($pobject)) {
46ff8b0e 1078 throw new convert_path_exception('convert_path_no_object', get_class($pobject));
1e2c7351 1079 }
46ff8b0e
DM
1080 if (!method_exists($pobject, $this->get_processing_method()) and
1081 !method_exists($pobject, $this->get_end_method()) and
1082 !method_exists($pobject, $this->get_start_method())) {
1083 throw new convert_path_exception('convert_path_missing_method', get_class($pobject));
1e2c7351
DM
1084 }
1085 }
1086}
1087
1088
1089/**
1090 * Exception being thrown by {@link convert_path} methods
1091 */
1092class convert_path_exception extends moodle_exception {
1093
1094 /**
1095 * Constructor
1096 *
1097 * @param string $errorcode key for the corresponding error string
1098 * @param mixed $a extra words and phrases that might be required by the error string
1099 * @param string $debuginfo optional debugging information
1100 */
1101 public function __construct($errorcode, $a = null, $debuginfo = null) {
1102 parent::__construct($errorcode, '', '', $a, $debuginfo);
1103 }
1104}
66f79e50
DM
1105
1106
1107/**
1108 * The class responsible for files migration
1109 *
1110 * The files in Moodle 1.9 backup are stored in moddata, user_files, group_files,
1111 * course_files and site_files folders.
1112 */
fe50f530 1113class moodle1_file_manager implements loggable {
66f79e50
DM
1114
1115 /** @var moodle1_converter instance we serve to */
1116 public $converter;
1117
1118 /** @var int context id of the files being migrated */
1119 public $contextid;
1120
1121 /** @var string component name of the files being migrated */
1122 public $component;
1123
1124 /** @var string file area of the files being migrated */
1125 public $filearea;
1126
1127 /** @var int item id of the files being migrated */
1128 public $itemid = 0;
1129
1130 /** @var int user id */
1131 public $userid;
1132
214c4924
DM
1133 /** @var string the root of the converter temp directory */
1134 protected $basepath;
1135
66f79e50
DM
1136 /** @var textlib instance used during the migration */
1137 protected $textlib;
1138
1139 /** @var array of file ids that were migrated by this instance */
1140 protected $fileids = array();
1141
1142 /**
1143 * Constructor optionally accepting some default values for the migrated files
1144 *
1145 * @param moodle1_converter $converter the converter instance we serve to
1146 * @param int $contextid initial context id of the files being migrated
1147 * @param string $component initial component name of the files being migrated
1148 * @param string $filearea initial file area of the files being migrated
1149 * @param int $itemid initial item id of the files being migrated
1150 * @param int $userid initial user id of the files being migrated
1151 */
1152 public function __construct(moodle1_converter $converter, $contextid = null, $component = null, $filearea = null, $itemid = 0, $userid = null) {
214c4924 1153 // set the initial destination of the migrated files
66f79e50
DM
1154 $this->converter = $converter;
1155 $this->contextid = $contextid;
1156 $this->component = $component;
1157 $this->filearea = $filearea;
1158 $this->itemid = $itemid;
1159 $this->userid = $userid;
214c4924
DM
1160 // set other useful bits
1161 $this->basepath = $converter->get_tempdir_path();
66f79e50
DM
1162 $this->textlib = textlib_get_instance();
1163 }
1164
1165 /**
1166 * Migrates one given file stored on disk
1167 *
214c4924 1168 * @param string $sourcepath the path to the source local file within the backup archive {@example 'moddata/foobar/file.ext'}
aa97e0dd 1169 * @param string $filepath the file path of the migrated file, defaults to the root directory '/' {@example '/sub/dir/'}
66f79e50 1170 * @param string $filename the name of the migrated file, defaults to the same as the source file has
aa97e0dd 1171 * @param int $sortorder the sortorder of the file (main files have sortorder set to 1)
66f79e50
DM
1172 * @param int $timecreated override the timestamp of when the migrated file should appear as created
1173 * @param int $timemodified override the timestamp of when the migrated file should appear as modified
1174 * @return int id of the migrated file
1175 */
aa97e0dd 1176 public function migrate_file($sourcepath, $filepath = '/', $filename = null, $sortorder = 0, $timecreated = null, $timemodified = null) {
214c4924
DM
1177
1178 $sourcefullpath = $this->basepath.'/'.$sourcepath;
66f79e50
DM
1179
1180 if (!is_readable($sourcefullpath)) {
214c4924 1181 throw new moodle1_convert_exception('file_not_readable', $sourcefullpath);
66f79e50
DM
1182 }
1183
aa97e0dd
DM
1184 // sanitize filepath
1185 if (empty($filepath)) {
1186 $filepath = '/';
1187 }
1188 if (substr($filepath, -1) !== '/') {
1189 $filepath .= '/';
1190 }
66f79e50
DM
1191 $filepath = clean_param($filepath, PARAM_PATH);
1192
1193 if ($this->textlib->strlen($filepath) > 255) {
1194 throw new moodle1_convert_exception('file_path_longer_than_255_chars');
1195 }
1196
1197 if (is_null($filename)) {
1198 $filename = basename($sourcefullpath);
1199 }
1200
1201 $filename = clean_param($filename, PARAM_FILE);
1202
1203 if ($filename === '') {
1204 throw new moodle1_convert_exception('unsupported_chars_in_filename');
1205 }
1206
1207 if (is_null($timecreated)) {
1208 $timecreated = filectime($sourcefullpath);
1209 }
1210
1211 if (is_null($timemodified)) {
1212 $timemodified = filemtime($sourcefullpath);
1213 }
1214
1215 $filerecord = $this->make_file_record(array(
1216 'filepath' => $filepath,
1217 'filename' => $filename,
aa97e0dd 1218 'sortorder' => $sortorder,
66f79e50
DM
1219 'mimetype' => mimeinfo('type', $sourcefullpath),
1220 'timecreated' => $timecreated,
1221 'timemodified' => $timemodified,
1222 ));
1223
1224 list($filerecord['contenthash'], $filerecord['filesize'], $newfile) = $this->add_file_to_pool($sourcefullpath);
1225 $this->stash_file($filerecord);
1226
1227 return $filerecord['id'];
1228 }
1229
1230 /**
1231 * Migrates all files in the given directory
1232 *
214c4924 1233 * @param string $rootpath path within the backup archive to the root directory containing the files {@example 'course_files'}
66f79e50 1234 * @param string $relpath relative path used during the recursion - do not provide when calling this!
93264625 1235 * @return array ids of the migrated files, empty array if the $rootpath not found
66f79e50
DM
1236 */
1237 public function migrate_directory($rootpath, $relpath='/') {
1238
93264625
DM
1239 if (!file_exists($this->basepath.'/'.$rootpath.$relpath)) {
1240 return array();
1241 }
1242
66f79e50
DM
1243 $fileids = array();
1244
1245 // make the fake file record for the directory itself
1246 $filerecord = $this->make_file_record(array('filepath' => $relpath, 'filename' => '.'));
1247 $this->stash_file($filerecord);
1248 $fileids[] = $filerecord['id'];
1249
214c4924 1250 $items = new DirectoryIterator($this->basepath.'/'.$rootpath.$relpath);
66f79e50
DM
1251
1252 foreach ($items as $item) {
1253
1254 if ($item->isDot()) {
1255 continue;
1256 }
1257
1258 if ($item->isLink()) {
1259 throw new moodle1_convert_exception('unexpected_symlink');
1260 }
1261
1262 if ($item->isFile()) {
214c4924 1263 $fileids[] = $this->migrate_file(substr($item->getPathname(), strlen($this->basepath.'/')),
aa97e0dd 1264 $relpath, $item->getFilename(), 0, $item->getCTime(), $item->getMTime());
66f79e50
DM
1265
1266 } else {
1267 $dirname = clean_param($item->getFilename(), PARAM_PATH);
1268
1269 if ($dirname === '') {
1270 throw new moodle1_convert_exception('unsupported_chars_in_filename');
1271 }
1272
1273 // migrate subdirectories recursively
1274 $fileids = array_merge($fileids, $this->migrate_directory($rootpath, $relpath.$item->getFilename().'/'));
1275 }
1276 }
1277
1278 return $fileids;
1279 }
1280
1281 /**
1282 * Returns the list of all file ids migrated by this instance so far
1283 *
1284 * @return array of int
1285 */
1286 public function get_fileids() {
1287 return $this->fileids;
1288 }
1289
d61ed0af
DM
1290 /**
1291 * Explicitly clear the list of file ids migrated by this instance so far
1292 */
1293 public function reset_fileids() {
1294 $this->fileids = array();
1295 }
1296
fe50f530
DM
1297 /**
1298 * Log a message using the converter's logging mechanism
1299 *
1300 * @param string $message message text
1301 * @param int $level message level {@example backup::LOG_WARNING}
1302 * @param null|mixed $a additional information
1303 * @param null|int $depth the message depth
1304 * @param bool $display whether the message should be sent to the output, too
1305 */
1306 public function log($message, $level, $a = null, $depth = null, $display = false) {
1307 $this->converter->log($message, $level, $a, $depth, $display);
1308 }
1309
66f79e50
DM
1310 /// internal implementation details ////////////////////////////////////////
1311
1312 /**
1313 * Prepares a fake record from the files table
1314 *
1315 * @param array $fileinfo explicit file data
1316 * @return array
1317 */
1318 protected function make_file_record(array $fileinfo) {
1319
1320 $defaultrecord = array(
1321 'contenthash' => 'da39a3ee5e6b4b0d3255bfef95601890afd80709', // sha1 of an empty file
1322 'contextid' => $this->contextid,
1323 'component' => $this->component,
1324 'filearea' => $this->filearea,
1325 'itemid' => $this->itemid,
1326 'filepath' => null,
1327 'filename' => null,
1328 'filesize' => 0,
1329 'userid' => $this->userid,
1330 'mimetype' => null,
1331 'status' => 0,
1332 'timecreated' => $now = time(),
1333 'timemodified' => $now,
1334 'source' => null,
1335 'author' => null,
1336 'license' => null,
1337 'sortorder' => 0,
1338 );
1339
1340 if (!array_key_exists('id', $fileinfo)) {
1341 $defaultrecord['id'] = $this->converter->get_nextid();
1342 }
1343
1344 // override the default values with the explicit data provided and return
1345 return array_merge($defaultrecord, $fileinfo);
1346 }
1347
1348 /**
1349 * Copies the given file to the pool directory
1350 *
1351 * Returns an array containing SHA1 hash of the file contents, the file size
1352 * and a flag indicating whether the file was actually added to the pool or whether
1353 * it was already there.
1354 *
1355 * @param string $pathname the full path to the file
1356 * @return array with keys (string)contenthash, (int)filesize, (bool)newfile
1357 */
1358 protected function add_file_to_pool($pathname) {
1359
1360 if (!is_readable($pathname)) {
1361 throw new moodle1_convert_exception('file_not_readable');
1362 }
1363
1364 $contenthash = sha1_file($pathname);
1365 $filesize = filesize($pathname);
1366 $hashpath = $this->converter->get_workdir_path().'/files/'.substr($contenthash, 0, 2);
1367 $hashfile = "$hashpath/$contenthash";
1368
1369 if (file_exists($hashfile)) {
1370 if (filesize($hashfile) !== $filesize) {
1371 // congratulations! you have found two files with different size and the same
1372 // content hash. or, something were wrong (which is more likely)
1373 throw new moodle1_convert_exception('same_hash_different_size');
1374 }
1375 $newfile = false;
1376
1377 } else {
1378 check_dir_exists($hashpath);
1379 $newfile = true;
1380
1381 if (!copy($pathname, $hashfile)) {
1382 throw new moodle1_convert_exception('unable_to_copy_file');
1383 }
1384
1385 if (filesize($hashfile) !== $filesize) {
1386 throw new moodle1_convert_exception('filesize_different_after_copy');
1387 }
1388 }
1389
1390 return array($contenthash, $filesize, $newfile);
1391 }
1392
1393 /**
1394 * Stashes the file record into 'files' stash and adds the record id to list of migrated files
1395 *
1396 * @param array $filerecord
1397 */
1398 protected function stash_file(array $filerecord) {
1399 $this->converter->set_stash('files', $filerecord, $filerecord['id']);
1400 $this->fileids[] = $filerecord['id'];
1401 }
1402}