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