mirrored from git://git.moodle.org/moodle.git
/
restore_stepslib.php
6393 lines (5476 loc) · 259 KB
/
restore_stepslib.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/>.
/**
* Defines various restore steps that will be used by common tasks in restore
*
* @package core_backup
* @subpackage moodle2
* @category backup
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* delete old directories and conditionally create backup_temp_ids table
*/
class restore_create_and_clean_temp_stuff extends restore_execution_step {
protected function define_execution() {
$exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
// If the table already exists, it's because restore_prechecks have been executed in the same
// request (without problems) and it already contains a bunch of preloaded information (users...)
// that we aren't going to execute again
if ($exists) { // Inform plan about preloaded information
$this->task->set_preloaded_information();
}
// Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
$itemid = $this->task->get_old_contextid();
$newitemid = context_course::instance($this->get_courseid())->id;
restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
// Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
$itemid = $this->task->get_old_system_contextid();
$newitemid = context_system::instance()->id;
restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
// Create the old-course-id to new-course-id mapping, we need that available since the beginning
$itemid = $this->task->get_old_courseid();
$newitemid = $this->get_courseid();
restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
}
}
/**
* Drop temp ids table and delete the temp dir used by backup/restore (conditionally).
*/
class restore_drop_and_clean_temp_stuff extends restore_execution_step {
protected function define_execution() {
global $CFG;
restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
$progress = $this->task->get_progress();
$progress->start_progress('Deleting backup dir');
backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir
$progress->end_progress();
}
}
}
/**
* Restore calculated grade items, grade categories etc
*/
class restore_gradebook_structure_step extends restore_structure_step {
/**
* To conditionally decide if this step must be executed
* Note the "settings" conditions are evaluated in the
* corresponding task. Here we check for other conditions
* not being restore settings (files, site settings...)
*/
protected function execute_condition() {
global $CFG, $DB;
if ($this->get_courseid() == SITEID) {
return false;
}
// No gradebook info found, don't execute
$fullpath = $this->task->get_taskbasepath();
$fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
if (!file_exists($fullpath)) {
return false;
}
// Some module present in backup file isn't available to restore
// in this site, don't execute
if ($this->task->is_missing_modules()) {
return false;
}
// Some activity has been excluded to be restored, don't execute
if ($this->task->is_excluding_activities()) {
return false;
}
// There should only be one grade category (the 1 associated with the course itself)
// If other categories already exist we're restoring into an existing course.
// Restoring categories into a course with an existing category structure is unlikely to go well
$category = new stdclass();
$category->courseid = $this->get_courseid();
$catcount = $DB->count_records('grade_categories', (array)$category);
if ($catcount>1) {
return false;
}
// Identify the backup we're dealing with.
$backuprelease = $this->get_task()->get_info()->backup_release; // The major version: 2.9, 3.0, 3.10...
$backupbuild = 0;
preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
if (!empty($matches[1])) {
$backupbuild = (int) $matches[1]; // The date of Moodle build at the time of the backup.
}
// On older versions the freeze value has to be converted.
// We do this from here as it is happening right before the file is read.
// This only targets the backup files that can contain the legacy freeze.
if ($backupbuild > 20150618 && (version_compare($backuprelease, '3.0', '<') || $backupbuild < 20160527)) {
$this->rewrite_step_backup_file_for_legacy_freeze($fullpath);
}
// Arrived here, execute the step
return true;
}
protected function define_structure() {
$paths = array();
$userinfo = $this->task->get_setting_value('users');
$paths[] = new restore_path_element('attributes', '/gradebook/attributes');
$paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
$gradeitem = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
$paths[] = $gradeitem;
$this->add_plugin_structure('local', $gradeitem);
if ($userinfo) {
$paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
}
$paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
$paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
return $paths;
}
protected function process_attributes($data) {
// For non-merge restore types:
// Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
$target = $this->get_task()->get_target();
if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) {
set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
}
if (!empty($data['calculations_freeze'])) {
if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING ||
$target == backup::TARGET_EXISTING_DELETING) {
set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
}
}
}
protected function process_grade_item($data) {
global $DB;
$data = (object)$data;
$oldid = $data->id;
$data->course = $this->get_courseid();
$data->courseid = $this->get_courseid();
if ($data->itemtype=='manual') {
// manual grade items store category id in categoryid
$data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
// if mapping failed put in course's grade category
if (NULL == $data->categoryid) {
$coursecat = grade_category::fetch_course_category($this->get_courseid());
$data->categoryid = $coursecat->id;
}
} else if ($data->itemtype=='course') {
// course grade item stores their category id in iteminstance
$coursecat = grade_category::fetch_course_category($this->get_courseid());
$data->iteminstance = $coursecat->id;
} else if ($data->itemtype=='category') {
// category grade items store their category id in iteminstance
$data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
} else {
throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
}
$data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL);
$data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
$data->locktime = $this->apply_date_offset($data->locktime);
$coursecategory = $newitemid = null;
//course grade item should already exist so updating instead of inserting
if($data->itemtype=='course') {
//get the ID of the already created grade item
$gi = new stdclass();
$gi->courseid = $this->get_courseid();
$gi->itemtype = $data->itemtype;
//need to get the id of the grade_category that was automatically created for the course
$category = new stdclass();
$category->courseid = $this->get_courseid();
$category->parent = null;
//course category fullname starts out as ? but may be edited
//$category->fullname = '?';
$coursecategory = $DB->get_record('grade_categories', (array)$category);
$gi->iteminstance = $coursecategory->id;
$existinggradeitem = $DB->get_record('grade_items', (array)$gi);
if (!empty($existinggradeitem)) {
$data->id = $newitemid = $existinggradeitem->id;
$DB->update_record('grade_items', $data);
}
} else if ($data->itemtype == 'manual') {
// Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
$gi = array(
'itemtype' => $data->itemtype,
'courseid' => $data->courseid,
'itemname' => $data->itemname,
'categoryid' => $data->categoryid,
);
$newitemid = $DB->get_field('grade_items', 'id', $gi);
}
if (empty($newitemid)) {
//in case we found the course category but still need to insert the course grade item
if ($data->itemtype=='course' && !empty($coursecategory)) {
$data->iteminstance = $coursecategory->id;
}
$newitemid = $DB->insert_record('grade_items', $data);
$data->id = $newitemid;
$gradeitem = new grade_item($data);
core\event\grade_item_created::create_from_grade_item($gradeitem)->trigger();
}
$this->set_mapping('grade_item', $oldid, $newitemid);
}
protected function process_grade_grade($data) {
global $DB;
$data = (object)$data;
$oldid = $data->id;
$olduserid = $data->userid;
$data->itemid = $this->get_new_parentid('grade_item');
$data->userid = $this->get_mappingid('user', $data->userid, null);
if (!empty($data->userid)) {
$data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
$data->locktime = $this->apply_date_offset($data->locktime);
$gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
if ($gradeexists) {
$message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
$this->log($message, backup::LOG_DEBUG);
} else {
$newitemid = $DB->insert_record('grade_grades', $data);
$this->set_mapping('grade_grades', $oldid, $newitemid);
}
} else {
$message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
$this->log($message, backup::LOG_DEBUG);
}
}
protected function process_grade_category($data) {
global $DB;
$data = (object)$data;
$oldid = $data->id;
$data->course = $this->get_courseid();
$data->courseid = $data->course;
$newitemid = null;
//no parent means a course level grade category. That may have been created when the course was created
if(empty($data->parent)) {
//parent was being saved as 0 when it should be null
$data->parent = null;
//get the already created course level grade category
$category = new stdclass();
$category->courseid = $this->get_courseid();
$category->parent = null;
$coursecategory = $DB->get_record('grade_categories', (array)$category);
if (!empty($coursecategory)) {
$data->id = $newitemid = $coursecategory->id;
$DB->update_record('grade_categories', $data);
}
}
// Add a warning about a removed setting.
if (!empty($data->aggregatesubcats)) {
set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
}
//need to insert a course category
if (empty($newitemid)) {
$newitemid = $DB->insert_record('grade_categories', $data);
}
$this->set_mapping('grade_category', $oldid, $newitemid);
}
protected function process_grade_letter($data) {
global $DB;
$data = (object)$data;
$oldid = $data->id;
$data->contextid = context_course::instance($this->get_courseid())->id;
$gradeletter = (array)$data;
unset($gradeletter['id']);
if (!$DB->record_exists('grade_letters', $gradeletter)) {
$newitemid = $DB->insert_record('grade_letters', $data);
} else {
$newitemid = $data->id;
}
$this->set_mapping('grade_letter', $oldid, $newitemid);
}
protected function process_grade_setting($data) {
global $DB;
$data = (object)$data;
$oldid = $data->id;
$data->courseid = $this->get_courseid();
$target = $this->get_task()->get_target();
if ($data->name == 'minmaxtouse' &&
($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) {
// We never restore minmaxtouse during merge.
return;
}
if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
$newitemid = $DB->insert_record('grade_settings', $data);
} else {
$newitemid = $data->id;
}
if (!empty($oldid)) {
// In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
$this->set_mapping('grade_setting', $oldid, $newitemid);
}
}
/**
* put all activity grade items in the correct grade category and mark all for recalculation
*/
protected function after_execute() {
global $DB;
$conditions = array(
'backupid' => $this->get_restoreid(),
'itemname' => 'grade_item'//,
//'itemid' => $itemid
);
$rs = $DB->get_recordset('backup_ids_temp', $conditions);
// We need this for calculation magic later on.
$mappings = array();
if (!empty($rs)) {
foreach($rs as $grade_item_backup) {
// Store the oldid with the new id.
$mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
$updateobj = new stdclass();
$updateobj->id = $grade_item_backup->newitemid;
//if this is an activity grade item that needs to be put back in its correct category
if (!empty($grade_item_backup->parentitemid)) {
$oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
if (!is_null($oldcategoryid)) {
$updateobj->categoryid = $oldcategoryid;
$DB->update_record('grade_items', $updateobj);
}
} else {
//mark course and category items as needing to be recalculated
$updateobj->needsupdate=1;
$DB->update_record('grade_items', $updateobj);
}
}
}
$rs->close();
// We need to update the calculations for calculated grade items that may reference old
// grade item ids using ##gi\d+##.
// $mappings can be empty, use 0 if so (won't match ever)
list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
$sql = "SELECT gi.id, gi.calculation
FROM {grade_items} gi
WHERE gi.id {$sql} AND
calculation IS NOT NULL";
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $gradeitem) {
// Collect all of the used grade item id references
if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
// This calculation doesn't reference any other grade items... EASY!
continue;
}
// For this next bit we are going to do the replacement of id's in two steps:
// 1. We will replace all old id references with a special mapping reference.
// 2. We will replace all mapping references with id's
// Why do we do this?
// Because there potentially there will be an overlap of ids within the query and we
// we substitute the wrong id.. safest way around this is the two step system
$calculationmap = array();
$mapcount = 0;
foreach ($matches[1] as $match) {
// Check that the old id is known to us, if not it was broken to begin with and will
// continue to be broken.
if (!array_key_exists($match, $mappings)) {
continue;
}
// Our special mapping key
$mapping = '##MAPPING'.$mapcount.'##';
// The old id that exists within the calculation now
$oldid = '##gi'.$match.'##';
// The new id that we want to replace the old one with.
$newid = '##gi'.$mappings[$match].'##';
// Replace in the special mapping key
$gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
// And record the mapping
$calculationmap[$mapping] = $newid;
$mapcount++;
}
// Iterate all special mappings for this calculation and replace in the new id's
foreach ($calculationmap as $mapping => $newid) {
$gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
}
// Update the calculation now that its being remapped
$DB->update_record('grade_items', $gradeitem);
}
$rs->close();
// Need to correct the grade category path and parent
$conditions = array(
'courseid' => $this->get_courseid()
);
$rs = $DB->get_recordset('grade_categories', $conditions);
// Get all the parents correct first as grade_category::build_path() loads category parents from the DB
foreach ($rs as $gc) {
if (!empty($gc->parent)) {
$grade_category = new stdClass();
$grade_category->id = $gc->id;
$grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
$DB->update_record('grade_categories', $grade_category);
}
}
$rs->close();
// Now we can rebuild all the paths
$rs = $DB->get_recordset('grade_categories', $conditions);
foreach ($rs as $gc) {
$grade_category = new stdClass();
$grade_category->id = $gc->id;
$grade_category->path = grade_category::build_path($gc);
$grade_category->depth = substr_count($grade_category->path, '/') - 1;
$DB->update_record('grade_categories', $grade_category);
}
$rs->close();
// Check what to do with the minmaxtouse setting.
$this->check_minmaxtouse();
// Freeze gradebook calculations if needed.
$this->gradebook_calculation_freeze();
// Ensure the module cache is current when recalculating grades.
rebuild_course_cache($this->get_courseid(), true);
// Restore marks items as needing update. Update everything now.
grade_regrade_final_grades($this->get_courseid());
}
/**
* Freeze gradebook calculation if needed.
*
* This is similar to various upgrade scripts that check if the freeze is needed.
*/
protected function gradebook_calculation_freeze() {
global $CFG;
$gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
$backupbuild = (int)$matches[1];
$backuprelease = $this->get_task()->get_info()->backup_release; // The major version: 2.9, 3.0, 3.10...
// Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150619) {
require_once($CFG->libdir . '/db/upgradelib.php');
upgrade_extra_credit_weightoverride($this->get_courseid());
}
// Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
if (!$gradebookcalculationsfreeze && $backupbuild >= 20141110 && $backupbuild < 20150627) {
require_once($CFG->libdir . '/db/upgradelib.php');
upgrade_calculated_grade_items($this->get_courseid());
}
// Courses from before 3.1 (20160518) may have a letter boundary problem and should be checked for this issue.
// Backups from before and including 2.9 could have a build number that is greater than 20160518 and should
// be checked for this problem.
if (!$gradebookcalculationsfreeze && ($backupbuild < 20160518 || version_compare($backuprelease, '2.9', '<='))) {
require_once($CFG->libdir . '/db/upgradelib.php');
upgrade_course_letter_boundary($this->get_courseid());
}
}
/**
* Checks what should happen with the course grade setting minmaxtouse.
*
* This is related to the upgrade step at the time the setting was added.
*
* @see MDL-48618
* @return void
*/
protected function check_minmaxtouse() {
global $CFG, $DB;
require_once($CFG->libdir . '/gradelib.php');
$userinfo = $this->task->get_setting_value('users');
$settingname = 'minmaxtouse';
$courseid = $this->get_courseid();
$minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
$version28start = 2014111000.00;
$version28last = 2014111006.05;
$version29start = 2015051100.00;
$version29last = 2015060400.02;
$target = $this->get_task()->get_target();
if ($minmaxtouse === false &&
($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
// The setting was not found because this setting did not exist at the time the backup was made.
// And we are not restoring as merge, in which case we leave the course as it was.
$version = $this->get_task()->get_info()->moodle_version;
if ($version < $version28start) {
// We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
}
} else if (($version >= $version28start && $version < $version28last) ||
($version >= $version29start && $version < $version29last)) {
// They should be using grade_grade when the course has inconsistencies.
$sql = "SELECT gi.id
FROM {grade_items} gi
JOIN {grade_grades} gg
ON gg.itemid = gi.id
WHERE gi.courseid = ?
AND (gi.itemtype != ? AND gi.itemtype != ?)
AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
// The course can only have inconsistencies when we restore the user info,
// we do not need to act on existing grades that were not restored as part of this backup.
if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
// Display the notice as we do during upgrade.
set_config('show_min_max_grades_changed_' . $courseid, 1);
if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
// We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
// If they are using the site-wide grade_grade setting, we only want to notice them.
grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
}
}
} else {
// This should never happen because from now on minmaxtouse is always saved in backups.
}
}
}
/**
* Rewrite step definition to handle the legacy freeze attribute.
*
* In previous backups the calculations_freeze property was stored as an attribute of the
* top level node <gradebook>. The backup API, however, do not process grandparent nodes.
* It only processes definitive children, and their parent attributes.
*
* We had:
*
* <gradebook calculations_freeze="20160511">
* <grade_categories>
* <grade_category id="10">
* <depth>1</depth>
* ...
* </grade_category>
* </grade_categories>
* ...
* </gradebook>
*
* And this method will convert it to:
*
* <gradebook >
* <attributes>
* <calculations_freeze>20160511</calculations_freeze>
* </attributes>
* <grade_categories>
* <grade_category id="10">
* <depth>1</depth>
* ...
* </grade_category>
* </grade_categories>
* ...
* </gradebook>
*
* Note that we cannot just load the XML file in memory as it could potentially be huge.
* We can also completely ignore if the node <attributes> is already in the backup
* file as it never existed before.
*
* @param string $filepath The absolute path to the XML file.
* @return void
*/
protected function rewrite_step_backup_file_for_legacy_freeze($filepath) {
$foundnode = false;
$newfile = make_request_directory(true) . DIRECTORY_SEPARATOR . 'file.xml';
$fr = fopen($filepath, 'r');
$fw = fopen($newfile, 'w');
if ($fr && $fw) {
while (($line = fgets($fr, 4096)) !== false) {
if (!$foundnode && strpos($line, '<gradebook ') === 0) {
$foundnode = true;
$matches = array();
$pattern = '@calculations_freeze=.([0-9]+).@';
if (preg_match($pattern, $line, $matches)) {
$freeze = $matches[1];
$line = preg_replace($pattern, '', $line);
$line .= " <attributes>\n <calculations_freeze>$freeze</calculations_freeze>\n </attributes>\n";
}
}
fputs($fw, $line);
}
if (!feof($fr)) {
throw new restore_step_exception('Error while attempting to rewrite the gradebook step file.');
}
fclose($fr);
fclose($fw);
if (!rename($newfile, $filepath)) {
throw new restore_step_exception('Error while attempting to rename the gradebook step file.');
}
} else {
if ($fr) {
fclose($fr);
}
if ($fw) {
fclose($fw);
}
}
}
}
/**
* Step in charge of restoring the grade history of a course.
*
* The execution conditions are itendical to {@link restore_gradebook_structure_step} because
* we do not want to restore the history if the gradebook and its content has not been
* restored. At least for now.
*/
class restore_grade_history_structure_step extends restore_structure_step {
protected function execute_condition() {
global $CFG, $DB;
if ($this->get_courseid() == SITEID) {
return false;
}
// No gradebook info found, don't execute.
$fullpath = $this->task->get_taskbasepath();
$fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
if (!file_exists($fullpath)) {
return false;
}
// Some module present in backup file isn't available to restore in this site, don't execute.
if ($this->task->is_missing_modules()) {
return false;
}
// Some activity has been excluded to be restored, don't execute.
if ($this->task->is_excluding_activities()) {
return false;
}
// There should only be one grade category (the 1 associated with the course itself).
$category = new stdclass();
$category->courseid = $this->get_courseid();
$catcount = $DB->count_records('grade_categories', (array)$category);
if ($catcount > 1) {
return false;
}
// Arrived here, execute the step.
return true;
}
protected function define_structure() {
$paths = array();
// Settings to use.
$userinfo = $this->get_setting_value('users');
$history = $this->get_setting_value('grade_histories');
if ($userinfo && $history) {
$paths[] = new restore_path_element('grade_grade',
'/grade_history/grade_grades/grade_grade');
}
return $paths;
}
protected function process_grade_grade($data) {
global $DB;
$data = (object)($data);
$olduserid = $data->userid;
unset($data->id);
$data->userid = $this->get_mappingid('user', $data->userid, null);
if (!empty($data->userid)) {
// Do not apply the date offsets as this is history.
$data->itemid = $this->get_mappingid('grade_item', $data->itemid);
$data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
$data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
$data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
$DB->insert_record('grade_grades_history', $data);
} else {
$message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
$this->log($message, backup::LOG_DEBUG);
}
}
}
/**
* decode all the interlinks present in restored content
* relying 100% in the restore_decode_processor that handles
* both the contents to modify and the rules to be applied
*/
class restore_decode_interlinks extends restore_execution_step {
protected function define_execution() {
// Get the decoder (from the plan)
$decoder = $this->task->get_decoder();
restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
// And launch it, everything will be processed
$decoder->execute();
}
}
/**
* first, ensure that we have no gaps in section numbers
* and then, rebuid the course cache
*/
class restore_rebuild_course_cache extends restore_execution_step {
protected function define_execution() {
global $DB;
// Although there is some sort of auto-recovery of missing sections
// present in course/formats... here we check that all the sections
// from 0 to MAX(section->section) exist, creating them if necessary
$maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
// Iterate over all sections
for ($i = 0; $i <= $maxsection; $i++) {
// If the section $i doesn't exist, create it
if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
$sectionrec = array(
'course' => $this->get_courseid(),
'section' => $i,
'timemodified' => time());
$DB->insert_record('course_sections', $sectionrec); // missing section created
}
}
// Rebuild cache now that all sections are in place
rebuild_course_cache($this->get_courseid());
cache_helper::purge_by_event('changesincourse');
cache_helper::purge_by_event('changesincoursecat');
}
}
/**
* Review all the tasks having one after_restore method
* executing it to perform some final adjustments of information
* not available when the task was executed.
*/
class restore_execute_after_restore extends restore_execution_step {
protected function define_execution() {
// Simply call to the execute_after_restore() method of the task
// that always is the restore_final_task
$this->task->launch_execute_after_restore();
}
}
/**
* Review all the (pending) block positions in backup_ids, matching by
* contextid, creating positions as needed. This is executed by the
* final task, once all the contexts have been created
*/
class restore_review_pending_block_positions extends restore_execution_step {
protected function define_execution() {
global $DB;
// Get all the block_position objects pending to match
$params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
$rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
// Process block positions, creating them or accumulating for final step
foreach($rs as $posrec) {
// Get the complete position object out of the info field.
$position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
// If position is for one already mapped (known) contextid
// process it now, creating the position, else nothing to
// do, position finally discarded
if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
$position->contextid = $newctx->newitemid;
// Create the block position
$DB->insert_record('block_positions', $position);
}
}
$rs->close();
}
}
/**
* Updates the availability data for course modules and sections.
*
* Runs after the restore of all course modules, sections, and grade items has
* completed. This is necessary in order to update IDs that have changed during
* restore.
*
* @package core_backup
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_update_availability extends restore_execution_step {
protected function define_execution() {
global $CFG, $DB;
// Note: This code runs even if availability is disabled when restoring.
// That will ensure that if you later turn availability on for the site,
// there will be no incorrect IDs. (It doesn't take long if the restored
// data does not contain any availability information.)
// Get modinfo with all data after resetting cache.
rebuild_course_cache($this->get_courseid(), true);
$modinfo = get_fast_modinfo($this->get_courseid());
// Get the date offset for this restore.
$dateoffset = $this->apply_date_offset(1) - 1;
// Update all sections that were restored.
$params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
$rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
$sectionsbyid = null;
foreach ($rs as $rec) {
if (is_null($sectionsbyid)) {
$sectionsbyid = array();
foreach ($modinfo->get_section_info_all() as $section) {
$sectionsbyid[$section->id] = $section;
}
}
if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
// If the section was not fully restored for some reason
// (e.g. due to an earlier error), skip it.
$this->get_logger()->process('Section not fully restored: id ' .
$rec->newitemid, backup::LOG_WARNING);
continue;
}
$section = $sectionsbyid[$rec->newitemid];
if (!is_null($section->availability)) {
$info = new \core_availability\info_section($section);
$info->update_after_restore($this->get_restoreid(),
$this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
}
}
$rs->close();
// Update all modules that were restored.
$params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
$rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
foreach ($rs as $rec) {
if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
// If the module was not fully restored for some reason
// (e.g. due to an earlier error), skip it.
$this->get_logger()->process('Module not fully restored: id ' .
$rec->newitemid, backup::LOG_WARNING);
continue;
}
$cm = $modinfo->get_cm($rec->newitemid);
if (!is_null($cm->availability)) {
$info = new \core_availability\info_module($cm);
$info->update_after_restore($this->get_restoreid(),
$this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
}
}
$rs->close();
}
}
/**
* Process legacy module availability records in backup_ids.
*
* Matches course modules and grade item id once all them have been already restored.
* Only if all matchings are satisfied the availability condition will be created.
* At the same time, it is required for the site to have that functionality enabled.
*
* This step is included only to handle legacy backups (2.6 and before). It does not
* do anything for newer backups.
*
* @copyright 2014 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
class restore_process_course_modules_availability extends restore_execution_step {
protected function define_execution() {
global $CFG, $DB;
// Site hasn't availability enabled
if (empty($CFG->enableavailability)) {
return;
}
// Do both modules and sections.
foreach (array('module', 'section') as $table) {
// Get all the availability objects to process.
$params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
$rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
// Process availabilities, creating them if everything matches ok.
foreach ($rs as $availrec) {
$allmatchesok = true;
// Get the complete legacy availability object.
$availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
// Note: This code used to update IDs, but that is now handled by the
// current code (after restore) instead of this legacy code.
// Get showavailability option.
$thingid = ($table === 'module') ? $availability->coursemoduleid :
$availability->coursesectionid;
$showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
$table . '_showavailability', $thingid);
if (!$showrec) {
// Should not happen.
throw new coding_exception('No matching showavailability record');
}
$show = $showrec->info->showavailability;
// The $availability object is now in the format used in the old
// system. Interpret this and convert to new system.
$currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
array('id' => $thingid), MUST_EXIST);
$newvalue = \core_availability\info::add_legacy_availability_condition(
$currentvalue, $availability, $show);
$DB->set_field('course_' . $table . 's', 'availability', $newvalue,
array('id' => $thingid));
}
$rs->close();
}
}
}
/*
* Execution step that, *conditionally* (if there isn't preloaded information)
* will load the inforef files for all the included course/section/activity tasks
* to backup_temp_ids. They will be stored with "xxxxref" as itemname