forked from catalyst/moodle-tool_coursebank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locallib.php
1768 lines (1653 loc) · 69.2 KB
/
locallib.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/>.
/**
*
* @package tool_coursebank
* @author Adam Riddell <[email protected]>
* @author Ghada El-Zoghbi <[email protected]>
* @copyright 2018 Catalyst IT
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
require_once($CFG->dirroot.'/admin/tool/coursebank/classes/coursebank_ws_manager.php');
require_once($CFG->dirroot.'/admin/tool/coursebank/classes/coursebank_http_response.php');
require_once($CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php');
abstract class tool_coursebank {
// Status.
const STATUS_NOTSTARTED = 0;
const STATUS_INPROGRESS = 1;
const STATUS_FINISHED = 2;
const STATUS_ONHOLD = 3;
const STATUS_CANCELLED = 4;
const STATUS_ERROR = 99;
const DEFAULT_TIMEOUT = 10;
const DEFAULT_RETRIES = 4;
const SEND_SUCCESS = 0;
const SEND_ERROR = 1;
const SEND_CRON_TIMEOUT = 2;
const CRON_TIMEOUT = 30;
// The youngest age a lock can reach before it will be removed.
// Allow a longish period of time.
const CRON_LOCK_TIMEOUT = 28800; // seconds (8 hours).
// Maximum number of days a backup can be for fetching.
const MAX_BACKUP_DAYS = 2;
/**
* Returns an array of available statuses
* @return array of availble statuses
*/
public static function get_statuses() {
$notstarted = get_string('statusnotstarted', 'tool_coursebank');
$inprogress = get_string('statusinprogress', 'tool_coursebank');
$statuserror = get_string('statuserror', 'tool_coursebank');
$finished = get_string('statusfinished', 'tool_coursebank');
$onhold = get_string('statusonhold', 'tool_coursebank');
$cancelled = get_string('statuscancelled', 'tool_coursebank');
$statuses = array(
self::STATUS_NOTSTARTED => $notstarted,
self::STATUS_INPROGRESS => $inprogress,
self::STATUS_FINISHED => $finished,
self::STATUS_ONHOLD => $onhold,
self::STATUS_CANCELLED => $cancelled,
self::STATUS_ERROR => $statuserror,
);
return $statuses;
}
/**
* Get the stored session key for use with the external course bank
* REST API if one exists.
*
* @return string or bool false Session key
*/
public static function get_session() {
$sessionkey = get_config('tool_coursebank', 'sessionkey');
if (!empty($sessionkey)) {
return $sessionkey;
}
return '';
}
/**
* Set the session key for use with the external course bank REST API.
*
* @return bool Success/failure
*/
public static function set_session($sessionkey) {
if (set_config('sessionkey', $sessionkey, 'tool_coursebank')) {
return true;
}
return false;
}
/**
* Test that a connection to the configured web service consumer can be
* made successfully.
*
* @param coursebank_ws_manager $wsman Web service manager object.
* @param string $sesskey External course bank session key.
*
* @return bool True for success, false otherwise.
*/
public static function check_connection(coursebank_ws_manager $wsman, $sesskey=false) {
global $USER;
$result = $wsman->get_test($sesskey);
$success = false;
if (isset($result->httpcode)) {
if ($result->httpcode == coursebank_ws_manager::WS_HTTP_OK) {
$success = true;
}
}
// First log the result, then return it.
$info = 'Connection check ';
$info .= $success ? 'passed.' : 'failed.';
$event = $success ? 'connection_checked' : 'connection_check_failed';
$action = 'Connection check';
$otherdata = array(
'conncheckaction' => 'conncheck',
'status' => $success
);
coursebank_logging::log_event(
$info,
$event,
$action,
coursebank_logging::LOG_MODULE_COURSE_BANK,
SITEID,
'',
$USER->id,
$otherdata
);
return $success;
}
/**
* Using get_optimal_chunksize, test the speed of a transfer request.
*
* Log the result of the test before returning an array containing both the
* tested transfer speed in kbps and the optimal chunk size for the site.
*
* @param coursebank_ws_manager $wsman Web service manager object.
* @param int $retry Number of retry attempts.
* @param string $sesskey Session key.
*
* @return array Approximate connection speed in
* kbps, and chunk size in kB:
*
* array('speed' => $speed,
* 'chunksize' => $chunksize)
*/
public static function check_connection_speed(coursebank_ws_manager $wsman,
$retry, $sesskey) {
global $USER;
$chunksizes = array(10, 100, 200, 500, 1000, 1500, 2000);
$result = self::get_optimal_chunksize($wsman, $sesskey, $chunksizes, $retry);
// Log connection speed test.
$otherdata = array(
'conncheckaction' => 'speedtest',
);
if ($result['speed'] > 0) {
$event = 'connection_checked';
$status = ($result['speed'] > 256) ? 'passed' : 'very slow';
$info = "Connection speed test $status. Approximate speed: "
. $result['speed'] . " kbps.";
$otherdata['speed'] = $result['speed'];
} else {
$event = 'connection_check_failed';
$info = "Connection speed test failed.";
$otherdata['speed'] = 0;
}
coursebank_logging::log_event(
$info,
$event,
'Connection check',
coursebank_logging::LOG_MODULE_COURSE_BANK,
SITEID,
'',
$USER->id,
$otherdata
);
return $result;
}
/**
* Send test transfer requests for each of the provided chunk sizes, and
* return the most optimal chunk size value (in kB), along with the
* transfer speed achieved in kbps.
*
* The provided array of chunk size values should be in ascending order.
* Iterate through this array of chunk sizes, calculating a rough transfer
* speed for a single request with dummy data of the corresponding chunk
* size. Continue iterating while increasing the chunk size improves the
* transfer speed by at least 10%. Stop either when this is no longer the
* case, or a transfer takes longer than 5 seconds.
*
* @param coursebank_ws_manager $wsman Web service manager object.
* @param string $sesskey Session key.
* @param array int $sizes Array of chunk sizes, sorted
* in ascending order, in kB.
* @param int $retry Number of retry attempts.
*
* @return array Array containing tested speed in
* kbps and suggested chunksize in kB.
*/
protected static function get_optimal_chunksize(coursebank_ws_manager $wsman,
$sesskey, $sizes=array(10, 100, 1000), $retry=1) {
$timeout = 5;
$threshold = 1.1;
$current = $sizes[0];
$speed = self::test_chunk_speed(
$wsman,
$current,
$retry,
$sesskey
);
foreach (array_slice($sizes, 1) as $size) {
$starttime = time();
$newspeed = self::test_chunk_speed($wsman, $size, $retry, $sesskey);
if ($newspeed < ($threshold * $speed) || (time() - $starttime) >= $timeout) {
break;
}
$speed = $newspeed;
$current = $size;
}
return array('speed' => $speed, 'chunksize' => $current);
}
/**
* Send a number of test transfer requests, then calculate and return a
* rough connection speed (in kbps) based on these transfers. If a request
* fails, return 0.
*
* @param coursebank_ws_manager $wsman ws_manager object.
* @param int $testsize Size of test data to transfer.
* @param int $retry Number of retry attempts.
* @param string $sesskey Session key string.
* @param int $count Number of requests to make.
*
* @return int $speed
*/
public static function test_chunk_speed(coursebank_ws_manager $wsman,
$testsize, $retry, $sesskey, $count=1) {
$starttime = microtime(true);
for ($j = 0; $j <= $retry; $j++) {
$check = str_pad('', $testsize * 1000, '0');
$response = $wsman->get_test(
$sesskey, $check, $count, $testsize, $starttime, $endtime);
if ($response->httpcode == coursebank_ws_manager::WS_HTTP_OK) {
break;
}
}
if ($response->httpcode == coursebank_ws_manager::WS_HTTP_OK) {
// Convert 'total kB transferred'/'total time' into kb/s.
$elapsed = $endtime - $starttime;
$speed = round(($testsize * $count * 8) / $elapsed, 2);
} else {
$speed = 0;
}
return $speed;
}
/**
* Fetch configured chunk size in kB from Moodle config.
*
* @return int $chunksize
*/
public static function get_config_chunk_size() {
return get_config('tool_coursebank', 'chunksize');
}
/**
* Calculate total number of chunks, given individual chunks size in kB and
* overall filesize in bytes.
*
* @param int $chunksize Individual chunk size in kilobytes.
* @param int $filesize Total file size in bytes.
*/
public static function calculate_total_chunks($chunksize, $filesize) {
return ceil($filesize / ($chunksize * 1000));
}
/**
* Function to fetch course bank records for display on the summary
* page. Returns an array of the form:
*
* array('results' => array(...),
* 'count ' => int $count)
*
* @param string $sort Sort field.
* @param string $dir Direction of sort.
* @param string $extraselect Additional select SQL.
* @param array $extraparams Additional parameters.
* @param array $fieldstosort Potential sort fields.
*
* @return array
*/
public static function get_summary_data($sort='status', $dir='ASC', $extraselect='',
array $extraparams=null, $page=0, $recordsperpage=0,
$fieldstosort=array('coursefullname', 'filetimemodified', 'backupfilename', 'filesize', 'status')) {
global $DB;
if (is_array($fieldstosort) and in_array($sort, $fieldstosort)) {
$sort = "$sort $dir";
} else {
$sort = '';
}
$results = $DB->get_records_select('tool_coursebank', $extraselect, $extraparams, $sort, '*', $page, $recordsperpage);
$count = $DB->count_records_select('tool_coursebank', $extraselect, $extraparams);
return array('results' => $results, 'count' => $count);
}
/**
*
* @param coursebank_ws_manager $wsmanager
* @param object $backup Course bank database record object
* @param array $data Data array to post/put.
* @param string $sessionkey Session token
* @param int $retries Number of retries to attempt sending
* when an error occurs.
* @return array of: int result null = needs further investigation.
* -1 = some error, don't continue.
* 1 = all good but don't continue
* -> i.e. External Course Bank already has the backup.
* boolean deletechunks - whether or not chunks should be deleted.
* int highestiterator - highest iterator Cours Bank has received for this backup.
* coursebank_http_response putresponse - the response from the put request.
*
*/
private static function update_backup(coursebank_ws_manager $wsmanager, $data, $backup, $sessionkey, $retries) {
global $DB, $USER;
$result = null;
$deletechunks = false;
$highestiterator = 0;
$putresponse = $wsmanager->put_backup($sessionkey, $data, $backup->uniqueid, $retries);
if ($putresponse !== true) {
if ($putresponse->httpcode == coursebank_ws_manager::WS_HTTP_BAD_REQUEST) {
if (isset($putresponse->body->chunksreceived)) {
// We've sent chunks to External Course Bank already?
if ($putresponse->body->chunksreceived == 0) {
// Possible network error. Should retry again later.
$backup->status = self::STATUS_ERROR;
$DB->update_record('tool_coursebank', $backup);
// Log a transfer interruption event.
$desc = coursebank_logging::get_backup_details(
'event_backup_update_interrupted',
$backup->uniqueid,
$backup->backupfilename
);
coursebank_logging::log_event(
$desc,
'transfer_interrupted',
'Transfer interrupted',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$data['courseid'],
'',
$USER->id,
$data
);
return array('result' => -1,
'deletechunks' => $deletechunks,
'highestiterator' => $highestiterator,
'putresponse' => $putresponse);
}
// Yes, we need to delete the chunks.
$deletechunks = true;
$highestiterator = $putresponse->body->highestchunkiterator;
} else if (isset($putresponse->body->is_completed)) {
// We've sent chunks to External Course Bank already?
if ($putresponse->body->is_completed) {
// Can skip this one as it's already been sent to External Course Bank and is complete.
// Another process (?!?) may have completed this in the meantime.
$backup->status = self::STATUS_FINISHED;
$backup->timecompleted = time();
$DB->update_record('tool_coursebank', $backup);
// Don't let the send_backup() continue.
return array('result' => 1,
'deletechunks' => $deletechunks,
'highestiterator' => $highestiterator,
'putresponse' => $putresponse);
}
// Otherwise, something else is wrong. Try again later.
// Actually, if is_completed is set, it will always be true
// and we shouldn't be here at this point.
}
}
}
// Log a transfer update event.
$desc = coursebank_logging::get_backup_details(
'event_backup_update',
$data['uuid'],
$data['filename']
);
coursebank_logging::log_event(
$desc,
'backup_updated',
'Backup updated',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$data['courseid'],
'',
$USER->id,
$data
);
return array('result' => null,
'deletechunks' => $deletechunks,
'highestiterator' => $highestiterator,
'putresponse' => $putresponse);
}
/**
* Send the initial post_backup.
* @param object $wsmanager Webservice class manager.
* @param object $backup Course bank database record object
*
* @return int 0 = all good, continue.
* -1 = some error, don't continue.
* 1 = all good but don't continue -> i.e. External Course Bank already has the backup.
*/
private static function initialise_backup(coursebank_ws_manager $wsmanager, $backup, $sessionkey, $retries) {
global $DB, $USER, $CFG;
$coursedate = '';
if ($backup->coursestartdate > 0) {
$datetime = new DateTime("@" . $backup->coursestartdate);
$coursedate = $datetime->format('Y-m-d H:i:s');
}
$data = array(
'uuid' => $backup->uniqueid,
'fileid' => $backup->id,
'filehash' => $backup->contenthash,
'filename' => $backup->backupfilename,
'filesize' => $backup->filesize,
'chunksize' => $backup->chunksize,
'totalchunks' => $backup->totalchunks,
'courseid' => $backup->courseid,
'coursename' => $backup->courseshortname,
'startdate' => $coursedate,
'categoryid' => $backup->categoryid,
'categoryname' => $backup->categoryname,
'filetimemodified' => $backup->filetimemodified,
'dbtype' => isset($CFG->dbtype) ? $CFG->dbtype : 'unknown'
);
if (!isset($backup->timetransferstarted) || $backup->timetransferstarted == 0) {
$backup->timetransferstarted = time();
}
$postresponse = $wsmanager->post_backup($data, $sessionkey, $retries);
// Unexpected http response or none received.
if ($postresponse instanceof coursebank_http_response) {
$deletechunks = false;
$highestiterator = 0;
$putresponse = null;
if ($postresponse->httpcode == coursebank_ws_manager::WS_HTTP_CONFLICT) {
// External Course Bank already has some data for this backup.
if ($postresponse->body->is_completed) {
// Can skip this one as it's already been sent to External Course Bank and is complete.
// Data may not match due to chunk size settings changing.
$backup->status = self::STATUS_FINISHED;
$backup->timecompleted = time();
$DB->update_record('tool_coursebank', $backup);
$desc = coursebank_logging::get_backup_details(
'event_backup_init_completed',
$data['uuid'],
$data['filename']
);
coursebank_logging::log_event(
$desc,
'transfer_started',
'Transfer started',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$data['courseid'],
'',
$USER->id,
$data
);
// Don't let the send_backup() continue.
return 1;
} else if ($postresponse->body->chunksreceived == 0) {
/* External Course Bank has some other data for this backup.
* But no chunks have been sent yet.
* Try to update it.
* Don't unset the fileid or the uuid fields.*/
list($result, $deletechunks, $highestiterator, $putresponse) = self::update_backup(
$wsmanager, $data, $backup, $sessionkey, $retries);
$desc = coursebank_logging::get_backup_details(
'event_backup_init_exists_nodata',
$data['uuid'],
$data['filename']
);
coursebank_logging::log_event(
$desc,
'transfer_started',
'Transfer started',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$data['courseid'],
'',
$USER->id,
$data
);
if (!is_null($result)) {
return $result;
}
} else {
/* Post_backup informs us that there's already data for this backup
* in External Course Bank. And, that it's already started receiving
* chunks.
* We need to delete the chunks, then update the backup, then continue.*/
if (isset($postresponse->body->chunksreceived)) {
$desc = coursebank_logging::get_backup_details(
'event_backup_init_exists_data',
$data['uuid'],
$data['filename']
);
coursebank_logging::log_event(
$desc,
'transfer_started',
'Transfer started',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$data['courseid'],
'',
$USER->id,
$data
);
$deletechunks = true;
$highestiterator = $postresponse->body->highestchunkiterator;
}
}
}
if ($deletechunks) {
// Delete chunks up to the highest iterator sent so far.
for ($iterator = 0; $iterator < $highestiterator; $iterator++) {
$deleteresponse = $wsmanager->delete_chunk($sessionkey, $backup->uniqueid, $iterator, $retries);
/* Ignore any errors for this. Perhaps one of the chunks is missing and
* that's why we're getting an error.
* Anyway, the update below should catch any errors.*/
}
list($result, $deletechunks, $highestiterator, $putresponse) = self::update_backup(
$wsmanager, $data, $backup, $sessionkey, $retries);
if (!is_null($result)) {
return $result;
}
if ($deletechunks || $highestiterator > 0) {
// Something is wrong. Try again later.
$backup->status = self::STATUS_ERROR;
$DB->update_record('tool_coursebank', $backup);
$desc = coursebank_logging::get_backup_details(
'event_backup_init_interrupted',
$data['uuid'],
$data['filename']
);
coursebank_logging::log_event(
$desc,
'transfer_start_failed',
'Transfer start failed',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$data['courseid'],
'',
$USER->id,
$data
);
return -1;
}
// Continue.
} else {
$backup->status = self::STATUS_ERROR;
$DB->update_record('tool_coursebank', $backup);
$desc = coursebank_logging::get_backup_details(
'event_backup_init_interrupted',
$data['uuid'],
$data['filename']
);
coursebank_logging::log_event(
$desc,
'transfer_start_failed',
'Transfer start failed',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$data['courseid'],
'',
$USER->id,
$data
);
return -1;
}
}
$backup->status = self::STATUS_INPROGRESS;
$DB->update_record('tool_coursebank', $backup);
return 0;
}
/**
* Convenience function to handle sending a file along with the relevant
* metadata.
*
* @param object $backup Course bank database record object
* @param int $starttime Timestamp corresponding to the the time when
* the transfer task was started. Used to
* determine if a transfer should be halted due
* to cron task time out.
*
* @return int $returncode Return code. One of:
* 0 = Successfully transferred
* 1 = Error
* 2 = Cron timeout
*
*/
public static function send_backup($backup, $starttime) {
global $CFG, $DB, $USER;
// Calculate time limit point as timestamp.
$endtime = $starttime + (self::CRON_TIMEOUT) * 60;
// Copy the backup file into our storage area so there are no changes to the file
// during transfer, unless file already exists.
if ($backup->isbackedup == 0) {
$backup = self::copy_backup($backup);
}
if ($backup === false) {
return self::SEND_ERROR;
}
// Get required config variables.
$urltarget = get_config('tool_coursebank', 'url');
$timeout = self::DEFAULT_TIMEOUT;
$retries = self::DEFAULT_RETRIES;
$token = get_config('tool_coursebank', 'authtoken');
$sessionkey = self::get_session();
// Initialise, check connection.
$wsmanager = new coursebank_ws_manager($urltarget, $timeout);
if (!self::check_connection($wsmanager, $sessionkey)) {
$backup->status = self::STATUS_ERROR;
$DB->update_record('tool_coursebank', $backup);
$wsmanager->close();
return self::SEND_ERROR;
}
// Update again in case a new session key was given.
$sessionkey = self::get_session();
// Chunk size is set in kilobytes.
$chunksize = $backup->chunksize * 1000;
// Open input file.
$coursebankfilepath = self::get_coursebank_filepath($backup);
$file = fopen($coursebankfilepath, 'rb');
// Log transfer_resumed event.
if ($backup->chunknumber > 0) {
// Don't need to log the start. It will be logged in the post_backup call.
coursebank_logging::log_transfer_resumed($backup);
}
// Set offset based on chunk number.
if ($backup->chunknumber != 0) {
fseek($file, $backup->chunknumber * $chunksize);
} else if ($backup->chunknumber == 0) {
// Initialise the backup record.
$result = self::initialise_backup($wsmanager, $backup, $sessionkey, $retries);
switch ($result) {
case 0:
// Continue on.
break;
case 1:
$wsmanager->close();
return self::SEND_SUCCESS;
break;
case -1:
$wsmanager->close();
return self::SEND_ERROR;
break;
}
}
// Log a transfer start event.
$desc = coursebank_logging::get_backup_details(
'event_backup_transfer_started',
$backup->uniqueid,
$backup->backupfilename
);
coursebank_logging::log_event(
$desc,
'transfer_started',
'Transfer started',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$backup->courseid,
'',
$USER->id,
$backup
);
// Read the file in chunks, attempt to send them.
while ($contents = fread($file, $chunksize)) {
$data = array(
'data' => base64_encode($contents),
'chunksize' => $chunksize,
'original_data' => $contents,
);
// Record time this current chunk was started to get sent.
$backup->timechunksent = time();
$DB->update_record('tool_coursebank', $backup);
$response = $wsmanager->put_chunk(
$data,
$backup->uniqueid,
$backup->chunknumber,
$sessionkey,
$retries
);
if ($response === true) {
$backup->timechunkcompleted = time();
$backup->chunknumber++;
if ($backup->status == self::STATUS_ERROR) {
$backup->chunkretries = 0;
$backup->status = self::STATUS_INPROGRESS;
}
$DB->update_record('tool_coursebank', $backup);
} else {
if ($backup->status == self::STATUS_ERROR) {
$backup->chunkretries++;
} else {
$backup->status = self::STATUS_ERROR;
}
$DB->update_record('tool_coursebank', $backup);
// Log a transfer interruption event.
$desc = coursebank_logging::get_backup_details(
'event_backup_chunk_interrupted',
$backup->uniqueid,
$backup->backupfilename
);
coursebank_logging::log_event(
$desc,
'transfer_interrupted',
'Transfer interrupted',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$backup->courseid,
'',
$USER->id,
$backup
);
return self::SEND_ERROR;
}
if (time() >= $endtime) {
// Cron task time limit reached, delay transfer to next run.
return self::SEND_CRON_TIMEOUT;
}
}
if ($backup->chunknumber == $backup->totalchunks) {
// All chunks have been sent. Need to flag this backup is complete.
$data = array(
'fileid' => $backup->id,
'filename' => $backup->backupfilename,
'filehash' => $backup->contenthash,
'filesize' => $backup->filesize,
'chunksize' => $backup->chunksize,
'totalchunks' => $backup->totalchunks
);
// Confirm the backup file as complete.
$completion = $wsmanager->put_backup_complete($sessionkey, $data, $backup);
if ($completion->httpcode != coursebank_ws_manager::WS_HTTP_OK) {
$backup->status = self::STATUS_ERROR;
// Start from the beginning next time.
//
// IMPORTANT: in the event that Coursebank has completed the backup, but
// we timed out or failed for some reason, we rely here on chunknumber
// being reset to 0 so that initialise_backup will be called in the next run.
// This should get a WS_HTTP_CONFLICT from Coursebank and finish the backup.
$backup->chunknumber = 0;
$backup->timechunkcompleted = 0;
$DB->update_record('tool_coursebank', $backup);
// Log a transfer interruption event.
$desc = coursebank_logging::get_backup_details(
'event_backup_update_interrupted',
$backup->uniqueid,
$data['filename']
);
coursebank_logging::log_event(
$desc,
'transfer_interrupted',
'Transfer interrupted',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$backup->courseid,
'',
$USER->id,
$backup
);
return self::SEND_ERROR;
} else {
$backup->status = self::STATUS_FINISHED;
$backup->timecompleted = time();
$DB->update_record('tool_coursebank', $backup);
// Log transfer_completed event.
$desc = coursebank_logging::get_backup_details(
'event_backup_transfer_completed',
$backup->uniqueid,
$backup->backupfilename
);
coursebank_logging::log_event(
$desc,
'transfer_completed',
'Transfer completed',
coursebank_logging::LOG_MODULE_COURSE_BANK,
$backup->courseid,
'',
$USER->id,
$backup
);
}
}
$wsmanager->close();
fclose($file);
return self::SEND_SUCCESS;
}
public static function get_coursebank_data_dir() {
global $CFG;
$dir = $CFG->dataroot . "/coursebank";
if (!file_exists($dir)) {
mkdir($dir);
}
return $dir;
}
public static function get_coursebank_filepath($backup) {
return self::get_coursebank_data_dir() . "/" . $backup->contenthash;
}
/**
* Convenience function to handle copying the backup file to the designated storage area.
*
* @param object $backup Course bank database record object
*
*/
public static function copy_backup($backup) {
global $CFG, $DB;
// Construct the full path of the backup file.
$moodlefilepath = $CFG->dataroot . '/filedir/' .
substr($backup->contenthash, 0, 2) . '/' .
substr($backup->contenthash, 2, 2) . '/' . $backup->contenthash;
if (!is_readable($moodlefilepath)) {
throw new file_serving_exception();
}
if (!is_writable(self::get_coursebank_data_dir())) {
throw new invalid_dataroot_permissions();
}
// Remove any old backups that may have failed and later cancelled.
self::clean_coursebank_data_dir();
$coursebankfilepath = self::get_coursebank_filepath($backup);
copy($moodlefilepath, $coursebankfilepath);
$backup->isbackedup = 1; // We have created a copy.
$DB->update_record('tool_coursebank', $backup);
return $backup;
}
/**
* Convenience function to clear out any old copied backup files.
*
*/
public static function clean_coursebank_data_dir() {
$coursebankdatadir = self::get_coursebank_data_dir();
if (!is_writable($coursebankdatadir)) {
return false;
}
if (is_dir($coursebankdatadir)) {
$maxbackuptime = time() - (self::MAX_BACKUP_DAYS * DAYSECS);
$objects = scandir($coursebankdatadir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
$filename = $coursebankdatadir."/".$object;
if (filetype($filename) == "file") {
$filemtime = filemtime($filename);
if ($filemtime < $maxbackuptime) {
unlink($filename);
}
}
}
}
reset($objects);
}
return true;
}
/**
* Function to handle deleteing the backup file from the designated storage area.
*
* @param object $backup Course bank database record object
* @param boolean $updaterecord Update the database record to relect that the backup is no longer copied.
*
*/
public static function delete_backup($backup, $updaterecord) {
global $DB;
$coursebankfilepath = self::get_coursebank_filepath($backup);
if (!is_readable($coursebankfilepath)) {
return false;
}
if (!is_writable(self::get_coursebank_data_dir())) {
return false;
}
unlink($coursebankfilepath);
if ($updaterecord == true) {
$backup->isbackedup = 0; // We have deleted the copy.
$DB->update_record('tool_coursebank', $backup);
}
return true;
}
/**
* Function to handle deleting the moodle backup file from the storage area.
*
* @param object $backup Course bank database record object
*
*/
public static function delete_moodle_backup($backup) {
$deletelocalbackup = get_config('tool_coursebank', 'deletelocalbackup');
// We don't want to delete moodle backup file.
if (empty($deletelocalbackup)) {
return true;
}
if (self::last_automated_backup_succeed($backup)) {
$config = get_config('backup');
$storage = $config->backup_auto_storage;
$dir = $config->backup_auto_destination;
if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
$dir = null;
}
// Clean up excess backups in the course backup filearea.
if ($storage == 0 || $storage == 2) {
$filestorage = get_file_storage();
$context = context_course::instance($backup->courseid);
$component = 'backup';
$filearea = 'automated';
$itemid = 0;
$files = array();
// Store all the matching files into timemodified => stored_file array.
foreach ($filestorage->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
$files[$file->get_timemodified()] = $file;
}
// Sort by keys descending (newer to older filemodified).
krsort($files);
foreach ($files as $file) {
if ($backup->fileid == $file->get_id()) {
$file->delete();
// Log it.
$delstring = get_string(
'moodledeletesuccess',
'tool_coursebank',
$backup->backupfilename
);
coursebank_logging::log_delete_backup($delstring, true);
}
}
}
// Clean up excess backups in the specified external directory.
if (!empty($dir) && ($storage == 1 || $storage == 2)) {
// Calculate backup filename regex, ignoring the date/time/info parts that can be
// variable, depending of languages, formats and automated backup settings.
$filename = backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $backup->courseid . '-';
$regex = '#' . preg_quote($filename, '#') . '.*\.mbz$#';
// Store all the matching files into filename => timemodified array.
$files = array();
foreach (scandir($dir) as $file) {
// Skip files not matching the naming convention.
if (!preg_match($regex, $file, $matches)) {
continue;
}
// Read the information contained in the backup itself.
try {