forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestorelib.php
7502 lines (6771 loc) · 381 KB
/
restorelib.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
//Functions used in restore
require_once($CFG->libdir.'/gradelib.php');
/**
* Group backup/restore constants, 0.
*/
define('RESTORE_GROUPS_NONE', 0);
/**
* Group backup/restore constants, 1.
*/
define('RESTORE_GROUPS_ONLY', 1);
/**
* Group backup/restore constants, 2.
*/
define('RESTORE_GROUPINGS_ONLY', 2);
/**
* Group backup/restore constants, course/all.
*/
define('RESTORE_GROUPS_GROUPINGS', 3);
//This function unzips a zip file in the same directory that it is
//It automatically uses pclzip or command line unzip
function restore_unzip ($file) {
return unzip_file($file, '', false);
}
//This function checks if moodle.xml seems to be a valid xml file
//(exists, has an xml header and a course main tag
function restore_check_moodle_file ($file) {
$status = true;
//Check if it exists
if ($status = is_file($file)) {
//Open it and read the first 200 bytes (chars)
$handle = fopen ($file, "r");
$first_chars = fread($handle,200);
$status = fclose ($handle);
//Chek if it has the requires strings
if ($status) {
$status = strpos($first_chars,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
if ($status !== false) {
$status = strpos($first_chars,"<MOODLE_BACKUP>");
}
}
}
return $status;
}
//This function iterates over all modules in backup file, searching for a
//MODNAME_refresh_events() to execute. Perhaps it should ve moved to central Moodle...
function restore_refresh_events($restore) {
global $CFG;
$status = true;
//Take all modules in backup
$modules = $restore->mods;
//Iterate
foreach($modules as $name => $module) {
//Only if the module is being restored
if (isset($module->restore) && $module->restore == 1) {
//Include module library
include_once("$CFG->dirroot/mod/$name/lib.php");
//If module_refresh_events exists
$function_name = $name."_refresh_events";
if (function_exists($function_name)) {
$status = $function_name($restore->course_id);
}
}
}
return $status;
}
//This function makes all the necessary calls to xxxx_decode_content_links_caller()
//function in each module/block/course format..., passing them the desired contents to be decoded
//from backup format to destination site/course in order to mantain inter-activities
//working in the backup/restore process
function restore_decode_content_links($restore) {
global $CFG, $DB;
$status = true;
if (!defined('RESTORE_SILENTLY')) {
echo "<ul>";
}
// Recode links in the course summary.
if (!defined('RESTORE_SILENTLY')) {
echo '<li>' . get_string('from') . ' ' . get_string('course');
}
$course = $DB->get_record('course', array('id'=>$restore->course_id), 'id,summary');
$coursesummary = backup_todb($course->summary); // Exception: Process FILEPHP (not available when restored) MDL-18222
$coursesummary = restore_decode_content_links_worker($coursesummary, $restore);
if ($coursesummary != $course->summary) {
$course->summary = $coursesummary;
$DB->update_record('course', $course);
}
if (!defined('RESTORE_SILENTLY')) {
echo '</li>';
}
// Recode links in section summaries.
$sections = $DB->get_records('course_sections', array('course'=>$restore->course_id), 'id', 'id,summary');
if ($sections) {
if (!defined('RESTORE_SILENTLY')) {
echo '<li>' . get_string('from') . ' ' . get_string('sections');
}
foreach ($sections as $section) {
$sectionsummary = restore_decode_content_links_worker($section->summary, $restore);
if ($sectionsummary != $section->summary) {
$section->summary = $sectionsummary;
$DB->update_record('course_sections', $section);
}
}
if (!defined('RESTORE_SILENTLY')) {
echo '</li>';
}
}
// Restore links in modules.
foreach ($restore->mods as $name => $info) {
//If the module is being restored
if (isset($info->restore) && $info->restore == 1) {
//Check if the xxxx_decode_content_links_caller exists
include_once("$CFG->dirroot/mod/$name/restorelib.php");
$function_name = $name."_decode_content_links_caller";
if (function_exists($function_name)) {
if (!defined('RESTORE_SILENTLY')) {
echo "<li>".get_string ("from")." ".get_string("modulenameplural",$name);
}
$status = $function_name($restore) && $status;
if (!defined('RESTORE_SILENTLY')) {
echo '</li>';
}
}
}
}
// For the course format call its decode_content_links method (if it exists)
$format = $DB->get_field('course','format', array('id'=>$restore->course_id));
if (file_exists("$CFG->dirroot/course/format/$format/restorelib.php")) {
include_once("$CFG->dirroot/course/format/$format/restorelib.php");
$function_name = $format.'_decode_format_content_links_caller';
if (function_exists($function_name)) {
if (!defined('RESTORE_SILENTLY')) {
echo "<li>".get_string ("from")." ".get_string("format").' '.$format;
}
$status = $function_name($restore);
if (!defined('RESTORE_SILENTLY')) {
echo '</li>';
}
}
}
// Process all html text also in blocks too
if (!defined('RESTORE_SILENTLY')) {
echo '<li>'.get_string ('from').' '.get_string('blocks');
}
if ($blocks = $DB->get_records('block', array('visible'=>1))) {
foreach ($blocks as $block) {
if ($blockobject = block_instance($block->name)) {
$blockobject->decode_content_links_caller($restore);
}
}
}
if (!defined('RESTORE_SILENTLY')) {
echo '</li>';
}
// Restore links in questions.
require_once("$CFG->dirroot/question/restorelib.php");
if (!defined('RESTORE_SILENTLY')) {
echo '<li>' . get_string('from') . ' ' . get_string('questions', 'quiz');
}
$status = question_decode_content_links_caller($restore) && $status;
if (!defined('RESTORE_SILENTLY')) {
echo '</li>';
}
if (!defined('RESTORE_SILENTLY')) {
echo "</ul>";
}
return $status;
}
//This function is called from all xxxx_decode_content_links_caller(),
//its task is to ask all modules (maybe other linkable objects) to restore
//links to them.
function restore_decode_content_links_worker($content,$restore) {
global $CFG, $DB;
foreach($restore->mods as $name => $info) {
$function_name = $name."_decode_content_links";
if (function_exists($function_name)) {
$content = $function_name($content,$restore);
}
}
// For the current format, call decode_format_content_links if it exists
static $format_function_name;
if (!isset($format_function_name)) {
$format_function_name = false;
if ($format = $DB->get_field('course','format', array('id'=>$restore->course_id))) {
if (file_exists("$CFG->dirroot/course/format/$format/restorelib.php")) {
include_once("$CFG->dirroot/course/format/$format/restorelib.php");
$function_name = $format.'_decode_format_content_links';
if (function_exists($function_name)) {
$format_function_name = $function_name;
}
}
}
}
// If the above worked - then we have a function to call
if ($format_function_name) {
$content = $format_function_name($content, $restore);
}
// For each block, call its encode_content_links method
static $blockobjects = null;
if (!isset($blockobjects)) {
$blockobjects = array();
if ($blocks = $DB->get_records('block', array('visible'=>1))) {
foreach ($blocks as $block) {
if ($blockobject = block_instance($block->name)) {
$blockobjects[] = $blockobject;
}
}
}
}
foreach ($blockobjects as $blockobject) {
$content = $blockobject->decode_content_links($content,$restore);
}
return $content;
}
//This function read the xml file and store it data from the info zone in an object
function restore_read_xml_info ($xml_file) {
//We call the main read_xml function, with $todo = INFO
$info = restore_read_xml ($xml_file,"INFO",false);
return $info;
}
//This function read the xml file and store it data from the course header zone in an object
function restore_read_xml_course_header ($xml_file) {
//We call the main read_xml function, with $todo = COURSE_HEADER
$info = restore_read_xml ($xml_file,"COURSE_HEADER",false);
return $info;
}
//This function read the xml file and store its data from the blocks in a object
function restore_read_xml_blocks ($restore, $xml_file) {
//We call the main read_xml function, with $todo = BLOCKS
$info = restore_read_xml ($xml_file,'BLOCKS',$restore);
return $info;
}
//This function read the xml file and store its data from the sections in a object
function restore_read_xml_sections ($xml_file) {
//We call the main read_xml function, with $todo = SECTIONS
$info = restore_read_xml ($xml_file,"SECTIONS",false);
return $info;
}
//This function read the xml file and store its data from the course format in an object
function restore_read_xml_formatdata ($xml_file) {
//We call the main read_xml function, with $todo = FORMATDATA
$info = restore_read_xml ($xml_file,'FORMATDATA',false);
return $info;
}
//This function read the xml file and store its data from the metacourse in a object
function restore_read_xml_metacourse ($xml_file) {
//We call the main read_xml function, with $todo = METACOURSE
$info = restore_read_xml ($xml_file,"METACOURSE",false);
return $info;
}
//This function read the xml file and store its data from the gradebook in a object
function restore_read_xml_gradebook ($restore, $xml_file) {
//We call the main read_xml function, with $todo = GRADEBOOK
$info = restore_read_xml ($xml_file,"GRADEBOOK",$restore);
return $info;
}
//This function read the xml file and store its data from the users in
//backup_ids->info db (and user's id in $info)
function restore_read_xml_users ($restore,$xml_file) {
//We call the main read_xml function, with $todo = USERS
$info = restore_read_xml ($xml_file,"USERS",$restore);
return $info;
}
//This function read the xml file and store its data from the messages in
//backup_ids->message backup_ids->message_read and backup_ids->contact and db (and their counters in info)
function restore_read_xml_messages ($restore,$xml_file) {
//We call the main read_xml function, with $todo = MESSAGES
$info = restore_read_xml ($xml_file,"MESSAGES",$restore);
return $info;
}
//This function read the xml file and store its data from the blogs in
//backup_ids->blog and backup_ids->blog_tag and db (and their counters in info)
function restore_read_xml_blogs ($restore,$xml_file) {
//We call the main read_xml function, with $todo = BLOGS
$info = restore_read_xml ($xml_file,"BLOGS",$restore);
return $info;
}
//This function read the xml file and store its data from the questions in
//backup_ids->info db (and category's id in $info)
function restore_read_xml_questions ($restore,$xml_file) {
//We call the main read_xml function, with $todo = QUESTIONS
$info = restore_read_xml ($xml_file,"QUESTIONS",$restore);
return $info;
}
//This function read the xml file and store its data from the scales in
//backup_ids->info db (and scale's id in $info)
function restore_read_xml_scales ($restore,$xml_file) {
//We call the main read_xml function, with $todo = SCALES
$info = restore_read_xml ($xml_file,"SCALES",$restore);
return $info;
}
//This function read the xml file and store its data from the groups in
//backup_ids->info db (and group's id in $info)
function restore_read_xml_groups ($restore,$xml_file) {
//We call the main read_xml function, with $todo = GROUPS
$info = restore_read_xml ($xml_file,"GROUPS",$restore);
return $info;
}
//This function read the xml file and store its data from the groupings in
//backup_ids->info db (and grouping's id in $info)
function restore_read_xml_groupings ($restore,$xml_file) {
//We call the main read_xml function, with $todo = GROUPINGS
$info = restore_read_xml ($xml_file,"GROUPINGS",$restore);
return $info;
}
//This function read the xml file and store its data from the groupings in
//backup_ids->info db (and grouping's id in $info)
function restore_read_xml_groupings_groups ($restore,$xml_file) {
//We call the main read_xml function, with $todo = GROUPINGS
$info = restore_read_xml ($xml_file,"GROUPINGSGROUPS",$restore);
return $info;
}
//This function read the xml file and store its data from the events (course) in
//backup_ids->info db (and event's id in $info)
function restore_read_xml_events ($restore,$xml_file) {
//We call the main read_xml function, with $todo = EVENTS
$info = restore_read_xml ($xml_file,"EVENTS",$restore);
return $info;
}
//This function read the xml file and store its data from the modules in
//backup_ids->info
function restore_read_xml_modules ($restore,$xml_file) {
//We call the main read_xml function, with $todo = MODULES
$info = restore_read_xml ($xml_file,"MODULES",$restore);
return $info;
}
//This function read the xml file and store its data from the logs in
//backup_ids->info
function restore_read_xml_logs ($restore,$xml_file) {
//We call the main read_xml function, with $todo = LOGS
$info = restore_read_xml ($xml_file,"LOGS",$restore);
return $info;
}
function restore_read_xml_roles ($xml_file) {
//We call the main read_xml function, with $todo = ROLES
$info = restore_read_xml ($xml_file,"ROLES",false);
return $info;
}
//This function prints the contents from the info parammeter passed
function restore_print_info ($info) {
global $CFG, $OUTPUT;
$status = true;
if ($info) {
$table = new html_table();
//This is tha align to every ingo table
$table->align = array ("right","left");
//This is the nowrap clause
$table->wrap = array ("","nowrap");
//The width
$table->width = "70%";
//Put interesting info in table
//The backup original name
$tab[0][0] = "<b>".get_string("backuporiginalname").":</b>";
$tab[0][1] = $info->backup_name;
//The moodle version
$tab[1][0] = "<b>".get_string("moodleversion").":</b>";
$tab[1][1] = $info->backup_moodle_release." (".$info->backup_moodle_version.")";
//The backup version
$tab[2][0] = "<b>".get_string("backupversion").":</b>";
$tab[2][1] = $info->backup_backup_release." (".$info->backup_backup_version.")";
//The backup date
$tab[3][0] = "<b>".get_string("backupdate").":</b>";
$tab[3][1] = userdate($info->backup_date);
//Is this the same Moodle install?
if (!empty($info->original_siteidentifier)) {
$tab[4][0] = "<b>".get_string("backupfromthissite").":</b>";
if (backup_is_same_site($info)) {
$tab[4][1] = get_string('yes');
} else {
$tab[4][1] = get_string('no');
}
}
//Print title
echo $OUTPUT->heading(get_string("backup").":");
$table->data = $tab;
//Print backup general info
echo html_writer::table($table);
if ($info->backup_backup_version <= 2005070500) {
echo $OUTPUT->notification(get_string('backupnonisowarning')); // Message informing that this backup may not work!
}
//Now backup contents in another table
$tab = array();
//First mods info
$mods = $info->mods;
$elem = 0;
foreach ($mods as $key => $mod) {
$tab[$elem][0] = "<b>".get_string("modulenameplural",$key).":</b>";
if ($mod->backup == "false") {
$tab[$elem][1] = get_string("notincluded");
} else {
if ($mod->userinfo == "true") {
$tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
} else {
$tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
}
if (isset($mod->instances) && is_array($mod->instances) && count($mod->instances)) {
foreach ($mod->instances as $instance) {
if ($instance->backup) {
$elem++;
$tab[$elem][0] = $instance->name;
if ($instance->userinfo == 'true') {
$tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
} else {
$tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
}
}
}
}
}
$elem++;
}
//Metacourse info
$tab[$elem][0] = "<b>".get_string("metacourse").":</b>";
if ($info->backup_metacourse == "true") {
$tab[$elem][1] = get_string("yes");
} else {
$tab[$elem][1] = get_string("no");
}
$elem++;
//Users info
$tab[$elem][0] = "<b>".get_string("users").":</b>";
$tab[$elem][1] = get_string($info->backup_users);
$elem++;
//Logs info
$tab[$elem][0] = "<b>".get_string("logs").":</b>";
if ($info->backup_logs == "true") {
$tab[$elem][1] = get_string("yes");
} else {
$tab[$elem][1] = get_string("no");
}
$elem++;
//User Files info
$tab[$elem][0] = "<b>".get_string("userfiles").":</b>";
if ($info->backup_user_files == "true") {
$tab[$elem][1] = get_string("yes");
} else {
$tab[$elem][1] = get_string("no");
}
$elem++;
//Course Files info
$tab[$elem][0] = "<b>".get_string("coursefiles").":</b>";
if ($info->backup_course_files == "true") {
$tab[$elem][1] = get_string("yes");
} else {
$tab[$elem][1] = get_string("no");
}
$elem++;
//site Files info
$tab[$elem][0] = "<b>".get_string("sitefiles").":</b>";
if (isset($info->backup_site_files) && $info->backup_site_files == "true") {
$tab[$elem][1] = get_string("yes");
} else {
$tab[$elem][1] = get_string("no");
}
$elem++;
//gradebook history info
$tab[$elem][0] = "<b>".get_string('gradebookhistories', 'grades').":</b>";
if (isset($info->gradebook_histories) && $info->gradebook_histories == "true") {
$tab[$elem][1] = get_string("yes");
} else {
$tab[$elem][1] = get_string("no");
}
$elem++;
//Messages info (only showed if present)
if ($info->backup_messages == 'true') {
$tab[$elem][0] = "<b>".get_string('messages','message').":</b>";
$tab[$elem][1] = get_string('yes');
$elem++;
} else {
//Do nothing
}
$elem++;
//Blogs info (only showed if present)
if (isset($info->backup_blogs) && $info->backup_blogs == 'true') {
$tab[$elem][0] = "<b>".get_string('blogs','blog').":</b>";
$tab[$elem][1] = get_string('yes');
$elem++;
} else {
//Do nothing
}
$table->data = $tab;
//Print title
echo $OUTPUT->heading(get_string("backupdetails").":");
//Print backup general info
echo html_writer::table($table);
} else {
$status = false;
}
return $status;
}
//This function prints the contents from the course_header parammeter passed
function restore_print_course_header ($course_header) {
global $OUTPUT;
$status = true;
if ($course_header) {
$table = new html_table();
//This is tha align to every ingo table
$table->align = array ("right","left");
//The width
$table->width = "70%";
//Put interesting course header in table
//The course name
$tab[0][0] = "<b>".get_string("name").":</b>";
$tab[0][1] = $course_header->course_fullname." (".$course_header->course_shortname.")";
//The course summary
$tab[1][0] = "<b>".get_string("summary").":</b>";
$tab[1][1] = $course_header->course_summary;
$table->data = $tab;
//Print title
echo $OUTPUT->heading(get_string("course").":");
//Print backup course header info
echo html_writer::table($table);
} else {
$status = false;
}
return $status;
}
/**
* Given one user object (from backup file), perform all the neccesary
* checks is order to decide how that user will be handled on restore.
*
* Note the function requires $user->mnethostid to be already calculated
* so it's caller responsibility to set it
*
* This function is used both by @restore_precheck_users() and
* @restore_create_users() to get consistent results in both places
*
* It returns:
* - one user object (from DB), if match has been found and user will be remapped
* - boolean true if the user needs to be created
* - boolean false if some conflict happened and the user cannot be handled
*
* Each test is responsible for returning its results and interrupt
* execution. At the end, boolean true (user needs to be created) will be
* returned if no test has interrupted that.
*
* Here it's the logic applied, keep it updated:
*
* If restoring users from same site backup:
* 1A - Normal check: If match by id and username and mnethost => ok, return target user
* 1B - Handle users deleted in DB and "alive" in backup file:
* If match by id and mnethost and user is deleted in DB and
* (match by username LIKE 'backup_email.%' or by non empty email = md5(username)) => ok, return target user
* 1C - Handle users deleted in backup file and "alive" in DB:
* If match by id and mnethost and user is deleted in backup file
* and match by email = email_without_time(backup_email) => ok, return target user
* 1D - Conflict: If match by username and mnethost and doesn't match by id => conflict, return false
* 1E - None of the above, return true => User needs to be created
*
* if restoring from another site backup (cannot match by id here, replace it by email/firstaccess combination):
* 2A - Normal check: If match by username and mnethost and (email or non-zero firstaccess) => ok, return target user
* 2B - Handle users deleted in DB and "alive" in backup file:
* 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
* (username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
* 2B2 - If match by mnethost and user is deleted in DB and
* username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
* (to cover situations were md5(username) wasn't implemented on delete we requiere both)
* 2C - Handle users deleted in backup file and "alive" in DB:
* If match mnethost and user is deleted in backup file
* and by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
* 2D - Conflict: If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
* 2E - None of the above, return true => User needs to be created
*
* Note: for DB deleted users email is stored in username field, hence we
* are looking there for emails. See delete_user()
* Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
* hence we are looking there for usernames if not empty. See delete_user()
*/
function restore_check_user($restore, $user) {
global $CFG, $DB;
// Verify mnethostid is set, return error if not
// it's parent responsibility to define that before
// arriving here
if (empty($user->mnethostid)) {
debugging("restore_check_user() wrong use, mnethostid not set for user $user->username", DEBUG_DEVELOPER);
return false;
}
// Handle checks from same site backups
if (backup_is_same_site($restore) && empty($CFG->forcedifferentsitecheckingusersonrestore)) {
// 1A - If match by id and username and mnethost => ok, return target user
if ($rec = $DB->get_record('user', array('id'=>$user->id, 'username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
return $rec; // Matching user found, return it
}
// 1B - Handle users deleted in DB and "alive" in backup file
// Note: for DB deleted users email is stored in username field, hence we
// are looking there for emails. See delete_user()
// Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
// hence we are looking there for usernames if not empty. See delete_user()
// If match by id and mnethost and user is deleted in DB and
// match by username LIKE 'backup_email.%' or by non empty email = md5(username) => ok, return target user
if ($rec = $DB->get_record_sql("SELECT *
FROM {user} u
WHERE id = ?
AND mnethostid = ?
AND deleted = 1
AND (
username LIKE ?
OR (
".$DB->sql_isnotempty('user', 'email', false, false)."
AND email = ?
)
)",
array($user->id, $user->mnethostid, $user->email.'.%', md5($user->username)))) {
return $rec; // Matching user, deleted in DB found, return it
}
// 1C - Handle users deleted in backup file and "alive" in DB
// If match by id and mnethost and user is deleted in backup file
// and match by email = email_without_time(backup_email) => ok, return target user
if ($user->deleted) {
// Note: for DB deleted users email is stored in username field, hence we
// are looking there for emails. See delete_user()
// Trim time() from email
$trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
if ($rec = $DB->get_record_sql("SELECT *
FROM {user} u
WHERE id = ?
AND mnethostid = ?
AND email = ?",
array($user->id, $user->mnethostid, $trimemail))) {
return $rec; // Matching user, deleted in backup file found, return it
}
}
// 1D - If match by username and mnethost and doesn't match by id => conflict, return false
if ($rec = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
if ($user->id != $rec->id) {
return false; // Conflict, username already exists and belongs to another id
}
}
// Handle checks from different site backups
} else {
// 2A - If match by username and mnethost and
// (email or non-zero firstaccess) => ok, return target user
if ($rec = $DB->get_record_sql("SELECT *
FROM {user} u
WHERE username = ?
AND mnethostid = ?
AND (
email = ?
OR (
firstaccess != 0
AND firstaccess = ?
)
)",
array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
return $rec; // Matching user found, return it
}
// 2B - Handle users deleted in DB and "alive" in backup file
// Note: for DB deleted users email is stored in username field, hence we
// are looking there for emails. See delete_user()
// Note: for DB deleted users md5(username) is stored *sometimes* in the email field,
// hence we are looking there for usernames if not empty. See delete_user()
// 2B1 - If match by mnethost and user is deleted in DB and not empty email = md5(username) and
// (by username LIKE 'backup_email.%' or non-zero firstaccess) => ok, return target user
if ($rec = $DB->get_record_sql("SELECT *
FROM {user} u
WHERE mnethostid = ?
AND deleted = 1
AND ".$DB->sql_isnotempty('user', 'email', false, false)."
AND email = ?
AND (
username LIKE ?
OR (
firstaccess != 0
AND firstaccess = ?
)
)",
array($user->mnethostid, md5($user->username), $user->email.'.%', $user->firstaccess))) {
return $rec; // Matching user found, return it
}
// 2B2 - If match by mnethost and user is deleted in DB and
// username LIKE 'backup_email.%' and non-zero firstaccess) => ok, return target user
// (this covers situations where md5(username) wasn't being stored so we require both
// the email & non-zero firstaccess to match)
if ($rec = $DB->get_record_sql("SELECT *
FROM {user} u
WHERE mnethostid = ?
AND deleted = 1
AND username LIKE ?
AND firstaccess != 0
AND firstaccess = ?",
array($user->mnethostid, $user->email.'.%', $user->firstaccess))) {
return $rec; // Matching user found, return it
}
// 2C - Handle users deleted in backup file and "alive" in DB
// If match mnethost and user is deleted in backup file
// and match by email = email_without_time(backup_email) and non-zero firstaccess=> ok, return target user
if ($user->deleted) {
// Note: for DB deleted users email is stored in username field, hence we
// are looking there for emails. See delete_user()
// Trim time() from email
$trimemail = preg_replace('/(.*?)\.[0-9]+.?$/', '\\1', $user->username);
if ($rec = $DB->get_record_sql("SELECT *
FROM {user} u
WHERE mnethostid = ?
AND email = ?
AND firstaccess != 0
AND firstaccess = ?",
array($user->mnethostid, $trimemail, $user->firstaccess))) {
return $rec; // Matching user, deleted in backup file found, return it
}
}
// 2D - If match by username and mnethost and not by (email or non-zero firstaccess) => conflict, return false
if ($rec = $DB->get_record_sql("SELECT *
FROM {user} u
WHERE username = ?
AND mnethostid = ?
AND NOT (
email = ?
OR (
firstaccess != 0
AND firstaccess = ?
)
)",
array($user->username, $user->mnethostid, $user->email, $user->firstaccess))) {
return false; // Conflict, username/mnethostid already exist and belong to another user (by email/firstaccess)
}
}
// Arrived here, return true as the user will need to be created and no
// conflicts have been found in the logic above. This covers:
// 1E - else => user needs to be created, return true
// 2E - else => user needs to be created, return true
return true;
}
/**
* For all the users being restored, check if they are going to cause problems
* before executing the restore process itself, detecting situations like:
* - conflicts preventing restore to continue - provided by @restore_check_user()
* - prevent creation of users if not allowed - check some global settings/caps
*/
function restore_precheck_users($xml_file, $restore, &$problems) {
global $CFG, $DB;
$status = true; // Init $status
// We aren't restoring users, nothing to check, allow continue
if ($restore->users == 2) {
return true;
}
// Get array of users from xml file and load them in backup_ids table
if (!$info = restore_read_xml_users($restore,$xml_file)) {
return true; // No users, nothing to check, allow continue
}
// We are going to map mnethostid, so load all the available ones
$mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id');
// Calculate the context we are going to use for capability checking
if (!empty($restore->course_id)) { // Know the target (existing) course, check capabilities there
$context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
} else if (!empty($restore->restore_restorecatto)) { // Know the category, check capabilities there
$context = get_context_instance(CONTEXT_COURSECAT, $restore->restore_restorecatto);
} else { // Last resort, check capabilities at system level
$context = get_context_instance(CONTEXT_SYSTEM);
}
// Calculate if we have perms to create users, by checking:
// to 'moodle/restore:createuser' and 'moodle/restore:userinfo'
// and also observe $CFG->disableusercreationonrestore
$cancreateuser = false;
if (has_capability('moodle/restore:createuser', $context) and
has_capability('moodle/restore:userinfo', $context) and
empty($CFG->disableusercreationonrestore)) { // Can create users
$cancreateuser = true;
}
// Iterate over all users, checking if they are likely to cause problems on restore
$counter = 0;
foreach ($info->users as $userid) {
$rec = backup_getid($restore->backup_unique_code, 'user', $userid);
$user = $rec->info;
// Find the correct mnethostid for user before performing any further check
if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
$user->mnethostid = $CFG->mnet_localhost_id;
} else {
// fast url-to-id lookups
if (isset($mnethosts[$user->mnethosturl])) {
$user->mnethostid = $mnethosts[$user->mnethosturl]->id;
} else {
$user->mnethostid = $CFG->mnet_localhost_id;
}
}
// Calculate the best way to handle this user from backup file
$usercheck = restore_check_user($restore, $user);
if (is_object($usercheck)) { // No problem, we have found one user in DB to be mapped to
// Annotate it, for later process by restore_create_users(). Set new_id to mapping user->id
backup_putid($restore->backup_unique_code, 'user', $userid, $usercheck->id, $user);
} else if ($usercheck === false) { // Found conflict, report it as problem
$problems[] = get_string('restoreuserconflict', '', $user->username);
$status = false;
} else if ($usercheck === true) { // User needs to be created, check if we are able
if ($cancreateuser) { // Can create user, annotate it, for later process by restore_create_users(). Set new_id to 0
backup_putid($restore->backup_unique_code, 'user', $userid, 0, $user);
} else { // Cannot create user, report it as problem
$problems[] = get_string('restorecannotcreateuser', '', $user->username);
$status = false;
}
} else { // Shouldn't arrive here ever, something is for sure wrong in restore_check_user()
if (!defined('RESTORE_SILENTLY')) {
notify('Unexpected error pre-checking user ' . s($user->username) . ' from backup file');
return false;
}
}
// Do some output
$counter++;
if ($counter % 10 == 0) {
if (!defined('RESTORE_SILENTLY')) {
echo ".";
if ($counter % 200 == 0) {
echo "<br />";
}
}
backup_flush(300);
}
}
return $status;
}
//This function create a new course record.
//When finished, course_header contains the id of the new course
function restore_create_new_course($restore,&$course_header) {
global $CFG, $DB;
//Create the course_object
if ($status) {
$course = new object();
$course->category = $course_header->category->id;
$course->password = $course_header->course_password;
$course->fullname = $course_header->course_fullname;
$course->shortname = $course_header->course_shortname;
$course->idnumber = $course_header->course_idnumber;
$course->idnumber = ''; //$course_header->course_idnumber; // we don't want this at all.
$course->summary = $course_header->course_summary;
$course->format = $course_header->course_format;
$course->showgrades = $course_header->course_showgrades;
$course->newsitems = $course_header->course_newsitems;
$course->guest = $course_header->course_guest;
$course->startdate = $course_header->course_startdate;
$course->startdate += $restore->course_startdateoffset;
$course->numsections = $course_header->course_numsections;
//$course->showrecent = $course_header->course_showrecent; INFO: This is out in 1.3
$course->maxbytes = $course_header->course_maxbytes;
$course->showreports = $course_header->course_showreports;
if (isset($course_header->course_groupmode)) {
$course->groupmode = $course_header->course_groupmode;
}
if (isset($course_header->course_groupmodeforce)) {
$course->groupmodeforce = $course_header->course_groupmodeforce;
}
if (isset($course_header->course_defaultgroupingid)) {
//keep the original now - convert after groupings restored
$course->defaultgroupingid = $course_header->course_defaultgroupingid;
}
$course->lang = $course_header->course_lang;
$course->theme = $course_header->course_theme;
$course->cost = $course_header->course_cost;
$course->currency = isset($course_header->course_currency)?$course_header->course_currency:'';
$course->marker = $course_header->course_marker;
$course->visible = $course_header->course_visible;
$course->hiddensections = $course_header->course_hiddensections;
$course->timecreated = $course_header->course_timecreated;
$course->timemodified = $course_header->course_timemodified;
$course->metacourse = $course_header->course_metacourse;
$course->expirynotify = isset($course_header->course_expirynotify) ? $course_header->course_expirynotify:0;
$course->notifystudents = isset($course_header->course_notifystudents) ? $course_header->course_notifystudents : 0;
$course->expirythreshold = isset($course_header->course_expirythreshold) ? $course_header->course_expirythreshold : 0;
$course->enrollable = isset($course_header->course_enrollable) ? $course_header->course_enrollable : 1;
$course->enrolstartdate = isset($course_header->course_enrolstartdate) ? $course_header->course_enrolstartdate : 0;
if ($course->enrolstartdate) { //Roll course dates
$course->enrolstartdate += $restore->course_startdateoffset;
}
$course->enrolenddate = isset($course_header->course_enrolenddate) ? $course_header->course_enrolenddate : 0;
if ($course->enrolenddate) { //Roll course dates