-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAPISyncExternalModule.php
1661 lines (1400 loc) · 50.7 KB
/
APISyncExternalModule.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
namespace Vanderbilt\APISyncExternalModule;
require_once __DIR__ . '/classes/Progress.php';
require_once __DIR__ . '/classes/BatchBuilder.php';
require_once __DIR__ . '/classes/DigestLog.php';
use DateTime;
use Exception;
use REDCap;
use stdClass;
const CHECKBOX_DELIMITER = '___';
class APISyncExternalModule extends \ExternalModules\AbstractExternalModule{
const IMPORT_PROGRESS_SETTING_KEY = 'import-progress';
const UPDATE = 'update';
const DELETE = 'delete';
const TRANSLATION_TABLE_CELL = "<td><textarea></textarea></td>";
const EXPORT_CANCELLED_MESSAGE = 'Export cancelled.';
const DATA_VALUES_MAX_LENGTH = (2^16) - 1;
const MAX_LOG_QUERY_PERIOD = 7;
private $settingPrefix;
private $cachedSettings;
private $allFieldNames = [];
function cron($cronInfo){
/**
* We know 2g is required to prevent exports from crashing on the SAMMC project.
* This was set to 4g somewhat arbitrarily. Hopefully that will cover many potential future use cases.
*/
ini_set('memory_limit', '4g');
$originalPid = $_GET['pid'] ?? null;
$cronName = $cronInfo['cron_name'];
foreach($this->framework->getProjectsWithModuleEnabled() as $localProjectId){
// This automatically associates all log statements with this project.
$_GET['pid'] = $localProjectId;
$this->settingPrefix = substr($cronName, 0, -1); // remove the 's'
if($cronName === 'exports'){
$this->handleExports();
}
else if($cronName === 'imports'){
$this->handleImports();
}
else{
throw new Exception("Unsupported cron name: $cronName");
}
}
// Put the pid back the way it was before this cron job (likely doesn't matter, but wanted to be safe)
$_GET['pid'] = $originalPid;
return "The \"{$cronInfo['cron_description']}\" cron job completed successfully.";
}
private function areAnyEmpty($array){
$filteredArray = array_filter($array);
return count($array) != count($filteredArray);
}
private function handleExports(){
/**
* This amount of time was chosen semi-arbitrarily.
* A time limit less than the cron max run time of 24 hours is important.
* Ideally the cron wouldn't only run for a few minutes max, but VUMC Project 111585 has batches that last a couple of hours.
* We might as well set this high, at least until we can justify including sub-batches in the export progress.
*/
$twentyHours = 60*60*20;
set_time_limit($twentyHours);
// In case the previous export was cancelled, or the button pushed when an export wasn't active.
$this->setExportCancelled(false);
$servers = $this->framework->getSubSettings('export-servers');
$firstServer = $servers[0] ?? null;
$firstProject = $firstServer['export-projects'][0] ?? null;
if($this->areAnyEmpty([
$firstServer['export-redcap-url'] ?? null,
$firstProject['export-api-key'] ?? null,
$firstProject['export-project-name'] ?? null
])){
return;
}
try{
$this->export($servers);
}
catch(\Exception $e){
if($e->getMessage() === self::EXPORT_CANCELLED_MESSAGE){
// No reason to report this exception since this is an expected use case.
}
else{
$this->handleException($e);
}
}
}
function getIdentifiers(){
$fields = REDCap::getDataDictionary($this->getProjectId(), 'array');
$fieldNames = [];
foreach($fields as $fieldName=>$details){
if($details['identifier'] === 'y'){
$fieldNames[] = $fieldName;
}
}
return $fieldNames;
}
// This method can be removed once it makes it into a REDCap version.
private function getLogTable(){
$result = $this->query('select log_event_table from redcap_projects where project_id = ?', $this->getProjectId());
$table = $result->fetch_assoc()['log_event_table'];
$prefix = 'redcap_log_event';
$number = explode($prefix, $table)[1];
$verifiedTable = $prefix;
if(!empty($number)){
$verifiedTable .= (int)$number;
}
if($table !== $verifiedTable){
throw new \Exception('An error occurred while generating the verified log table name.');
}
return $verifiedTable;
}
private function getLogIndexHint($logTable){
$result = $this->query("show variables like 'version'", []);
$versionParts = explode('.', $result->fetch_assoc()['Value']);
$result = $this->query("
show index from $logTable
where Column_name = ? and Seq_in_index = ?
", ['ts', 1]);
$row = $result->fetch_assoc();
$indexName = db_escape($row['Key_name']) ?? null;
if($indexName === null){
return '';
}
/**
* We add the index hint because MySQL is really stupid.
* We've seen it choose not to use the index and hang the cron process on VUMC production.
*/
return " use index ($indexName) ";
}
private function getLastExportedLogId(){
$logTable = $this->getLogTable();
$result = $this->query(
"
select log_event_id
from $logTable " . $this->getLogIndexHint($logTable) . "
where
project_id = ?
and ts >= ?
order by log_event_id asc
limit 1;
",
[
$this->getProjectId(),
(new DateTime)->modify('-' . self::MAX_LOG_QUERY_PERIOD . ' days')->format('YmdHis')
]
);
$weekOldId = $result->fetch_assoc()['log_event_id'];
$lastExportedId = $this->getProjectSetting('last-exported-log-id');
/**
* Even if a last exported ID is set, we never want to look back more than week
* because I don't trust REDCap's current indexing to handle queries looking back than far.
*/
return max($weekOldId, $lastExportedId);
}
private function getLatestLogId(){
$result = $this->query("
select log_event_id
from " . $this->getLogTable() . "
order by log_event_id desc
limit 1;
", []);
$row = $result->fetch_assoc();
return $row['log_event_id'];
}
private function getAllFieldNames(){
$pid = $this->getProjectId();
if(!isset($this->allFieldNames[$pid])){
$dictionary = REDCap::getDataDictionary($pid, 'array');
$this->allFieldNames[$pid] = array_keys($dictionary);
}
return $this->allFieldNames[$pid];
}
private function addBatchesSinceLastExport($specificFieldsBatchBuilder, $allFieldsBatchBuilder, $recordIds){
$recordIds = array_flip($recordIds);
$lastExportedLogId = $this->getLastExportedLogId();
$result = $this->query("
select log_event_id, pk, event, data_values
from " . $this->getLogTable() . "
where
event in ('INSERT', 'UPDATE', 'DELETE')
and object_type = 'redcap_data'
and project_id = ?
and log_event_id > ?
order by log_event_id asc
", [
$this->getProjectId(),
$lastExportedLogId
]);
while($row = $result->fetch_assoc()){
$recordId = $row['pk'];
if(!isset($recordIds[$recordId])){
continue;
}
$fields = $this->getChangedFieldNamesForLogRow($row['data_values'], $this->getAllFieldNames());
if(empty($fields)){
$batchBuilder = $allFieldsBatchBuilder;
}
else{
$batchBuilder = $specificFieldsBatchBuilder;
}
$batchBuilder->addEvent($row['log_event_id'], $recordId, $row['event'], $fields);
}
}
function getChangedFieldNamesForLogRow($dataValues, $allFieldNames){
if(strlen($dataValues) === self::DATA_VALUES_MAX_LENGTH){
// The data_values column was maxed out, so all changes were not included.
// Return an empty array, which will cause all fields to be synced.
return [];
}
preg_match_all('/\n([a-z0-9_]+)/', "\n$dataValues", $matches);
/**
* There are cases where non-field names will be matched (ex: the text after a newline in a textarea).
* Use array_intersect() to weed these invalid field names out.
*/
return array_intersect($allFieldNames, $matches[1]);
}
private function export($servers){
/**
* WHEN MODIFYING EXPORT BEHAVIOR
* If further export permissions tweaks are made, Paul recommended selecting
* an API key to use/mimic during export to make use of existing export options.
* This would replace the $dateShiftDates and getFieldsWithoutIdentifiers() features below.
* The existing solutions may still be better, but we should consider
* this alternative just to make sure.
*/
$recordIdFieldName = $this->getRecordIdField();
$exportProgress = $this->getProjectSetting('export-progress');
if($exportProgress === null){
if(!$this->isTimeToRunExports()){
return;
}
$startingBatchIndex = 0;
/**
* We use separate builders for specific fields & all fields because University of Cincinnati
* ran into a scenario where data_values was maxing out intermittently and a new batch was
* created every time the threshold was crossed back and forth. This created tens of thousands
* of batches for no reason, making an incremental sync much slower than 'export-all-records'.
*/
$specificFieldsBatchBuilder = new BatchBuilder($this->getExportBatchSize());
$allFieldsBatchBuilder = new BatchBuilder($this->getExportBatchSize());
$latestLogId = $this->getLatestLogId();
$allRecordsIds = array_column(json_decode(
REDCap::getData($this->getProjectId(),
'json',
null,
$recordIdFieldName,
null,
null,
false,
false,
false
/**
* If ever try to add filter logic here again in the future,
* remember a simple export filter logic feature is incompatible with incremental change detection.
* During the periods when a record does not match filter logic, incremental changes for that record are ignored permanently
* (regardless of whether the record matches the filter logic again in the future).
* To work around this, we may need to store the last sync time of each individual record and use it to "catch up"
* with past changes if/when unmatched records begin matching again (likely via a full sync of just those records).
*/
), true), $recordIdFieldName);
$exportAllRecords = $this->getProjectSetting('export-all-records') === true;
if($exportAllRecords){
$this->removeProjectSetting('export-all-records');
foreach($allRecordsIds as $recordId){
// An empty fields array will cause all fields to be pulled.
$allFieldsBatchBuilder->addEvent($latestLogId, $recordId, 'UPDATE', []);
}
}
else{
$this->addBatchesSinceLastExport($specificFieldsBatchBuilder, $allFieldsBatchBuilder, $allRecordsIds);
}
$batches = $this->mergeBatches($specificFieldsBatchBuilder, $allFieldsBatchBuilder);
if(empty($batches)){
/**
* No recent changes exist to sync.
* Update the last exported log ID to whatever the latest ID across all projects is
* in order to ensure that we don't check this date range again.
* This can reduce query time significantly on projects thar are updated infrequently,
* especially when the server is under heavy load.
*/
$this->setProjectSetting('last-exported-log-id', $latestLogId);
return;
}
}
else{
// Continue an export in progress
$this->removeProjectSetting('export-progress');
[$startingBatchIndex, $batches] = unserialize($exportProgress);
}
$dateShiftDates = $this->getProjectSetting('export-shift-dates') === true;
$maxSubBatchSize = $this->getExportSubBatchSize();
$excludedFieldNames = [];
if($this->getProjectSetting('export-exclude-identifiers') === true){
$excludedFieldNames = $this->getIdentifiers();
}
for($i=0; $i<count($batches); $i++) {
if($this->isCronRunningTooLong()){
$remainingBatches = array_splice($batches, $i);
$this->setProjectSetting('export-progress', serialize([
$startingBatchIndex+$i,
$remainingBatches
]));
return;
}
$batch = $batches[$i];
$type = $batch->getType();
$lastLogId = $batch->getLastLogId();
$recordIds = $batch->getRecordIds();
$fieldsByRecord = $batch->getFieldsByRecord();
$batchText = "batch " . ($startingBatchIndex+$i+1) . " of " . ($startingBatchIndex+count($batches));
$this->log("Preparing to export {$type}s for $batchText", [
'details' => json_encode([
'Last Log ID' => $lastLogId,
'Record IDs' => $recordIds
], JSON_PRETTY_PRINT)
]);
if($type === self::UPDATE){
$fields = $batch->getFields();
if(!empty($fields)){
$fields[] = $recordIdFieldName;
}
$data = json_decode(REDCap::getData(
$this->getProjectId(),
'json',
$recordIds,
$fields,
[],
[],
false,
false,
false,
false,
false,
false,
false,
$dateShiftDates
), true);
$subBatchData = [];
$subBatchSize = 0;
$subBatchNumber = 1;
for($rowIndex=0; $rowIndex<count($data); $rowIndex++){
$row = $data[$rowIndex];
foreach($batch->getFields() as $field){
if(
$field !== $recordIdFieldName
&&
!isset($fieldsByRecord[$row[$recordIdFieldName]][$field])
){
// This field didn't change for this record, so don't include it in the export.
unset($row[$field]);
}
}
foreach($excludedFieldNames as $excludedFieldName){
unset($row[$excludedFieldName]);
}
$rowSize = strlen(json_encode($row));
$spaceLeftInSubBatch = $maxSubBatchSize - $subBatchSize;
if($rowSize > $spaceLeftInSubBatch){
if($subBatchSize === 0){
$this->log("The export failed because the sub-batch size setting is not large enough to handle the data in the details of this log message.", [
'details' => json_encode($row, JSON_PRETTY_PRINT)
]);
throw new Exception("The export failed because of a sub-batch size error. See the API Sync page for project " . $this->getProjectId() . " for details.");
}
$this->exportSubBatch($servers, $type, $subBatchData, $subBatchNumber, $subBatchSize);
$subBatchData = [];
$subBatchSize = 0;
$subBatchNumber++;
}
$subBatchData[] = $row;
$subBatchSize += $rowSize;
$isLastRow = $rowIndex === count($data)-1;
if($isLastRow){
$this->exportSubBatch($servers, $type, $subBatchData, $subBatchNumber, $subBatchSize);
}
}
}
else if($type === self::DELETE){
$this->exportSubBatch($servers, $type, $recordIds, 1, 0);
}
else{
throw new Exception("Unsupported export type: $type");
}
$this->setProjectSetting('last-exported-log-id', $lastLogId);
$this->log("Finished exporting {$type}s for $batchText");
}
}
function mergeBatches($builder1, $builder2){
$batches = array_merge($builder1->getBatches(), $builder2->getBatches());
usort($batches, function($a, $b){
return $a->getLastLogId() - $b->getLastLogId();
});
return $batches;
}
private function isCronRunningTooLong(){
return time() >= $_SERVER['REQUEST_TIME_FLOAT'] + 55;
}
function logDetails($message, $details){
$parts = str_split($details, 65535);
$params = [
'details' => array_shift($parts)
];
$n = 2;
foreach($parts as $part){
$params["details$n"] = $part;
$n++;
}
return $this->log($message, $params);
}
function getProjects($server){
$fieldListSettingName = $this->getPrefixedSettingName("field-list");
$projects = $server[$this->getPrefixedSettingName("projects")];
$incorrectlyLocatedFieldLists = $projects[$fieldListSettingName] ?? null;
if($incorrectlyLocatedFieldLists !== null){
// Recover from a getSubSettings() bug which was fixed in framework version 9.
foreach ($projects as $i=>&$project) {
$project[$fieldListSettingName] = $incorrectlyLocatedFieldLists[$i] ?? null;
}
unset($projects[$fieldListSettingName]);
}
return $projects;
}
private function exportSubBatch($servers, $type, $data, $subBatchNumber, $subBatchSize){
$subBatchSize = round($subBatchSize/1024/1024, 1) . ' MB';
$recordIdFieldName = $this->getRecordIdField();
foreach ($servers as $server) {
$url = $server['export-redcap-url'];
$logUrl = $this->formatURLForLogs($url);
foreach ($this->getProjects($server) as $project) {
$getProjectExportMessage = function($action) use ($type, $subBatchNumber, $logUrl, $project, $subBatchSize){
return "
<div>$action exporting $type sub-batch $subBatchNumber ($subBatchSize) to the following project at $logUrl:</div>
<div class='remote-project-title'>" . $project['export-project-name'] . "</div>
";
};
$this->log($getProjectExportMessage('Started'));
$apiKey = $project['export-api-key'];
$args = ['content' => 'record'];
if($type === self::UPDATE){
$prepped_data = $this->prepareData($project, $data, $recordIdFieldName);
$args['overwriteBehavior'] = 'overwrite';
$args['data'] = json_encode($prepped_data, JSON_PRETTY_PRINT);
}
else if($type === self::DELETE){
$recordIdPrefix = $project['export-record-id-prefix'];
if ($recordIdPrefix) {
foreach ($data as &$rId) {
$rId = $recordIdPrefix . $rId;
}
}
$args['action'] = 'delete';
$args['records'] = $data;
}
$results = $this->apiRequest($url, $apiKey, $args);
$this->log(
$getProjectExportMessage('Finished'),
['details' => json_encode($results, JSON_PRETTY_PRINT)]
);
if($this->isExportCancelled()){
$this->log(self::EXPORT_CANCELLED_MESSAGE);
throw new \Exception(self::EXPORT_CANCELLED_MESSAGE);
}
}
}
}
function isExportCancelled(){
return $this->getProjectSetting('export-cancelled') === true;
}
function setExportCancelled($value){
return $this->setProjectSetting('export-cancelled', $value);
}
private function getExportBatchSize(){
$size = (int) $this->getProjectSetting('export-batch-size');
if(!$size){
// A size of 100 caused our 4g memory limit to be reached on VUMC project 111585.
$size = 50;
}
return $size;
}
private function getExportSubBatchSize(){
$size = $this->getProjectSetting('export-sub-batch-size');
if($size === null){
/**
* A 7MB limit was added semi-arbitrarily. We know requests greater than 16MB were truncated
* and returning an empty error message when OSHU was attempting to push to Vanderbilt.
* This value might be heavily dependent on the networks/firewalls between each specific source & destination.
*/
$size = 7;
}
// Return the size in bytes
return $size*1024*1024;
}
function clearExportQueue(){
$this->setProjectSetting('last-exported-log-id', $this->getLatestLogId());
}
private function getImportServers(){
$servers = $this->framework->getSubSettings('servers');
$importTimes = $this->getProjectSetting('last-import-time');
for($i=0; $i<count($servers); $i++){
/**
* Hidden settings are excluded from getSubSettings(),
* so manually add this one back in.
*/
$servers[$i]['last-import-time'] = $importTimes[$i] ?? null;
}
return $servers;
}
private function handleImports(){
$progress = new Progress($this);
$servers = $this->getImportServers();
$syncNow = $this->getProjectSetting('sync-now');
$this->removeProjectSetting('sync-now');
foreach($servers as $server){
if(
$syncNow
||
$this->isTimeToRun(
$server['daily-record-import-minute'],
$server['daily-record-import-hour'],
$server['daily-record-import-weekday'],
$server
)
){
// addServer() will have no effect if the server is already in progress.
$progress->addServer($server);
}
}
try{
$this->importNextBatch($progress);
}
catch(Exception $e){
$this->handleException($e);
$progress->finishCurrentProject();
}
$this->setImportProgress($progress->serialize());
}
function getImportProgress(){
return $this->getProjectSetting(self::IMPORT_PROGRESS_SETTING_KEY);
}
function setImportProgress($progress){
$this->setProjectSetting(self::IMPORT_PROGRESS_SETTING_KEY, $progress);
}
function formatURLForLogs($url){
$parts = explode('://', $url);
if(count($parts) === 1){
$domainName = $parts[0];
}
else{
$domainName = $parts[1];
}
return "<b><a href='$url' target='_blank'>$domainName</a></b>";
}
private function handleException($e){
$this->log("An error occurred. Click 'Show Details' for more info.", [
'details' => $e->getMessage() . "\n\n" . $e->getTraceAsString()
]);
$message = "The API Sync module has encountered an error on project " . $this->getProjectId() . ". The sync will be automatically re-tried, but action is likely required before it will succeed.";
if($this->settingPrefix === 'export'){
/**
* In a worst case scenario, the first failed sync would not occur until approximately a day after the first unsynced change,
* and the next successful sync may not occur until a day after the problem is fixed. Because of this, we advertise a window
* two days shorter than MAX_LOG_QUERY_PERIOD for fixing the issue.
*/
$fixDayRange = self::MAX_LOG_QUERY_PERIOD-2 . '-' . self::MAX_LOG_QUERY_PERIOD;
$message .= " If this message persists longer than an approximate $fixDayRange day cutoff, older changes will be skipped to conserve server resources. This cutoff is not possible to predict precisely since it is dependent on actual cron run times for this and other modules. If the cutoff is reached, a full sync (or manual export/import) will be required to ensure all older changes were synced. If this message persists longer than " . self::MAX_LOG_QUERY_PERIOD . " days, please disable this sync to prevent unnecessary server resource consumption.";
}
$this->sendErrorEmail($message);
}
private function sendErrorEmail($message){
$url = $this->getUrl('api-sync.php');
$message .= " See the logs on <a href='$url'>this page</a> for details.";
$usernames = $this->getProjectSetting('error-recipients');
$emails = [];
if(!empty($usernames)){
foreach($usernames as $username){
if(!empty($username)){
$emails[] = $this->getUser($username)->getEmail();
}
}
}
if(empty($emails)){
$users = $this->getProject()->getUsers();
foreach($users as $user){
if($user->hasDesignRights()){
$emails[] = $user->getEmail();
}
}
}
global $homepage_contact_email;
REDCap::email(
implode(', ', $emails),
$homepage_contact_email,
"REDCap API Sync Module Error",
$message
);
}
private function isTimeToRunExports(){
$exportNow = $this->getProjectSetting('export-now');
if($exportNow){
$this->removeProjectSetting('export-now');
return true;
}
$minute = $this->getProjectSetting('export-minute');
$hour = $this->getProjectSetting('export-hour');
$weekday = $this->getProjectSetting('export-weekday');
return $this->isTimeToRun($minute, $hour, $weekday, null);
}
private function isTimeToRun($minute, $hour, $weekday, $server){
if(!is_numeric($minute)){
// Don't sync if this field is not set
return false;
}
else if(!is_numeric($hour)){
// We're syncing hourly, so use the current hour.
$hour = 'H';
}
if (is_numeric($weekday) && (date("w") != $weekday)) {
// Don't sync if weekday is set but doesn't match day of week
return false;
}
if($server === null){
$lastRunTime = $this->getProjectSetting('last-export-time');
}
else{
$lastRunTime = $server['last-import-time'] ?? null;
}
if(empty($lastRunTime)){
/**
* This is the first time this sync has run.
* Don't actually sync, but set a last run time to the current time as if we did.
* This will cause the next scheduled sync to occur normally.
*/
$this->setLastRunTime(time(), $server);
return false;
}
$scheduledTime = strtotime(date("Y-m-d $hour:$minute:00"));
if(
$scheduledTime > time() // Not time to sync yet
||
/**
* Either the current scheduled sync has already run, or this sync has not run for the first time yet
* and we're waiting for the first scheduled time after the last run time was set initially above.
*/
$lastRunTime >= $scheduledTime
){
return false;
}
// Set the scheduled time instead of the actual run time to simplify checking logic.
$this->setLastRunTime($scheduledTime, $server);
return true;
}
private function setLastRunTime($scheduledTime, $server){
/**
* The string cast is required to prevent the setting config dialog from omitting the value,
* and removing it from the database if settings are saved.
* This is really only needed for imports, but we do it for exports too for consistency.
*/
$scheduledTime = (string) $scheduledTime;
if($server === null){
$this->setProjectSetting('last-export-time', $scheduledTime);
}
else{
$servers = $this->getImportServers();
for($i=0; $i<count($servers); $i++){
if($servers[$i]['redcap-url'] === $server['redcap-url']){
$importTimes = $this->getProjectSetting('last-import-time');
$importTimes[$i] = $scheduledTime;
$this->setProjectSetting('last-import-time', $importTimes);
}
}
}
}
function importNextBatch(Progress &$progress){
$project =& $progress->getCurrentProject();
if($project === null){
// No projects are in progress.
return;
}
$url = $progress->getCurrentServerUrl();
$apiKey = $project['api-key'];
if($progress->getBatchIndex() === 0){
$this->log("
<div>Exporting records from the remote project titled:</div>
<div class='remote-project-title'>" . $this->getProjectTitle($url, $apiKey) . "</div>
");
$fieldNames = $this->apiRequest($url, $apiKey, [
'content' => 'exportFieldNames'
]);
$recordIdFieldName = $fieldNames[0]['export_field_name'];
$records = $this->apiRequest($url, $apiKey, [
'content' => 'record',
'fields' => [$recordIdFieldName],
'filterLogic' => implode(
' ' . $project['import-filter-logic-combination-operator'] . ' ',
array_filter([
$this->getCachedProjectSetting('import-filter-logic-all'),
$project['import-filter-logic'],
])
)
]);
$recordIds = [];
foreach($records as $record){
$recordIds[] = $record[$recordIdFieldName];
}
$batchSize = @$project['import-batch-size'];
if(empty($batchSize)){
// This calculation should NOT be changed without testing older PHP versions.
// PHP 7 is much more memory efficient on REDCap imports than PHP 5.
// Use the number of fields times number of records as a metric to determine a reasonable chunk size.
// The following calculation caused about 500MB of maximum memory usage when importing the TIN Database (pid 61715) on the Vanderbilt REDCap test server.
$numberOfDataPoints = count($fieldNames) * count($recordIds);
$numberOfBatches = $numberOfDataPoints / 100000;
$batchSize = round(count($recordIds) / $numberOfBatches);
}
$project['record-ids'] = $recordIds;
$project['record-id-field-name'] = $recordIdFieldName;
$project['import-batch-size'] = $batchSize;
}
else{
$recordIds = $project['record-ids'];
$recordIdFieldName = $project['record-id-field-name'];
$batchSize = $project['import-batch-size'];
}
$batches = array_chunk($recordIds, $batchSize);
$batchIndex = $progress->getBatchIndex();
$batch = $batches[$batchIndex];
$batchText = "batch " . ($batchIndex+1) . " of " . count($batches);
$this->log("Exporting $batchText");
$response = $this->apiRequest($url, $apiKey, [
'content' => 'record',
'format' => 'json',
'records' => $batch
]);
$response = $this->prepareData($project, $response, $recordIdFieldName);
$stopEarly = $this->importBatch($project, $batchText, $batchSize, $response, $progress);
$progress->incrementBatch();
if($progress->getBatchIndex() === count($batches) || $stopEarly){
$progress->finishCurrentProject();
}
}
private function prepareData(&$project, $data, $recordIdFieldName){
// perform translations if configured
$this->buildTranslations($project);
if ($this->translationsAreBuilt($project)) {
$this->translateFormNames($data, $project);
$this->translateEventNames($data, $project);
}
$proj_key_prefix = $this->getProjectTypePrefix($project);
$prefix = $project[$proj_key_prefix . 'record-id-prefix'];
$metadata = $this->getMetadata($this->getProjectId());
$formNamesByField = [];
foreach($metadata as $fieldName=>$field){
$formNamesByField[$fieldName] = $field['form_name'];
}
$newData = [];
foreach($data as &$instance){
if ($prefix) {
$instance[$recordIdFieldName] = $prefix . $instance[$recordIdFieldName];
}
$this->removeInvalidIncompleteStatuses($instance, $formNamesByField);
$this->filterByFieldList($project, $instance);
if(!empty($instance)){
$newData[] = $instance;
}
}
return $newData;
}
private function getPrefixedSettingName($name){
$prefix = $this->settingPrefix;
if(
// At some point it might make sense to refactor other references to use this function
// and add more items to this array.
in_array($name, ['projects'])
&&
$prefix === 'import'
){
// This setting predated the prefixing. Do not prepend the prefix.
}
else{
$name = "$prefix-$name";
}
return $name;
}
function filterByFieldList($project, &$instance){
$type = $project[$this->getPrefixedSettingName('field-list-type')];
$fieldList = $project[$this->getPrefixedSettingName('field-list')];
if(empty($type)){
$type = $this->getCachedProjectSetting($this->getPrefixedSettingName('field-list-type-all'));
$fieldList = $this->getCachedProjectSetting($this->getPrefixedSettingName('field-list-all'));
}
if($fieldList === null){
$fieldList = [];
}
if($type === 'include'){
$fieldList = array_merge($fieldList, $this->getREDCapIdentifierFields());
}
/**
* When nothing is selected, a lone null value appears. Remove it.
*/
$fieldList = array_filter($fieldList);
$fieldList = array_flip($fieldList);
foreach(array_keys($instance) as $field){
$fieldWithoutCheckboxSuffix = explode(CHECKBOX_DELIMITER, $field)[0];
$isset = isset($fieldList[$fieldWithoutCheckboxSuffix]);
if(
($type === 'include' && !$isset)
||
($type === 'exclude' && $isset)
){
unset($instance[$field]);
}
}
}
private function getREDCapIdentifierFields(){
if(!isset($this->redcapIdentifierFields)){
$this->redcapIdentifierFields = [
$this->getRecordIdField(),
'redcap_event_name',
'redcap_repeat_instrument',
'redcap_repeat_instance'
];
}
return $this->redcapIdentifierFields;
}
private function removeInvalidIncompleteStatuses(&$instance, $formNamesByField){
$formValueCounts = [];
foreach($formNamesByField as $fieldName=>$formName){