-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathFlightTrackerExternalModule.php
More file actions
executable file
·2002 lines (1878 loc) · 80.5 KB
/
Copy pathFlightTrackerExternalModule.php
File metadata and controls
executable file
·2002 lines (1878 loc) · 80.5 KB
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\FlightTrackerExternalModule;
use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;
use Vanderbilt\CareerDevLibrary\ajax\ajaxRouter;
use Vanderbilt\CareerDevLibrary\Application;
use Vanderbilt\CareerDevLibrary\CronManager;
use Vanderbilt\CareerDevLibrary\DataDictionaryManagement;
use Vanderbilt\CareerDevLibrary\EmailManager;
use Vanderbilt\CareerDevLibrary\FeatureSwitches;
use Vanderbilt\CareerDevLibrary\ORCID;
use Vanderbilt\CareerDevLibrary\REDCapManagement;
use Vanderbilt\CareerDevLibrary\Download;
use Vanderbilt\CareerDevLibrary\NameMatcher;
use Vanderbilt\CareerDevLibrary\Upload;
use Vanderbilt\CareerDevLibrary\MMAHelper;
use Vanderbilt\CareerDevLibrary\Sanitizer;
use Vanderbilt\CareerDevLibrary\Portal;
use Vanderbilt\CareerDevLibrary\Links;
use Vanderbilt\CareerDevLibrary\CelebrationsEmail;
use Vanderbilt\CareerDevLibrary\MSTP;
use Vanderbilt\CareerDevLibrary\Grant;
use Vanderbilt\CareerDevLibrary\REDCapLookupByUserid;
use function Vanderbilt\CareerDevLibrary\flattenORCIDArray;
use function Vanderbilt\CareerDevLibrary\updateORCIDProfileData;
require_once(__DIR__."/classes/Autoload.php");
require_once(__DIR__."/cronLoad.php");
require_once(APP_PATH_DOCROOT."Classes/System.php");
class FlightTrackerExternalModule extends AbstractExternalModule
{
public const RECENT_YEARS = CelebrationsEmail::RECENT_YEARS;
public const SHARING_SETTING = "matches";
public const COMPLETE_INDICES = [2];
public const MATCHES_BATCH_SIZE = 200;
public const LONG_RUNNING_BATCH_SUFFIX = "long";
public const LOCAL_BATCH_SUFFIX = "local";
public const INTENSE_BATCH_SUFFIX = "intense";
public const TEST_CRON = "test";
public const WEEKDAYS = [1, 2, 3, 4, 5];
public const OLD_FIRST_NAMES = "old_first_names";
public const OLD_LAST_NAMES = "old_last_names";
public const FIRST_NAMES = "first_names";
public const LAST_NAMES = "last_names";
public const VANDERBILT_TEST_SERVER = "redcaptest.vumc.org";
public function getPrefix() {
return Application::getPrefix();
}
public function getName() {
return $this->name;
}
public function enqueueTonight() {
$this->setProjectSetting("run_tonight", true);
}
# Vanderbilt's REDCap traffic tends to speed up around 8am and decrease after 6pm
# give one hour for crons to complete before traffic speedup
# these should already be partitioned to run more quickly
public function intense_batch() {
$currTs = time();
# purposefully switch windows - start of restricted time = end of window
$endWindow = strtotime(CronManager::getRestrictedTime("intense", "start"));
$startWindow = strtotime(CronManager::getRestrictedTime("intense", "end"));
if (
!in_array(date("N"), self::WEEKDAYS)
|| ($currTs < $endWindow)
|| ($currTs > $startWindow)
|| Application::isLocalhost()
) {
$this->runBatch(self::INTENSE_BATCH_SUFFIX);
}
}
# local-resource cron; runs 24/7
public function local() {
$this->runBatch(self::LOCAL_BATCH_SUFFIX);
}
# Vanderbilt's REDCap traffic tends to speed up around 8am and decrease after 6pm
# give two hours for long-running crons to complete before traffic speedup
public function long_batch() {
$currTs = time();
# purposefully switch windows - start of restricted time = end of window
$endWindow = strtotime(CronManager::getRestrictedTime("long", "start"));
$startWindow = strtotime(CronManager::getRestrictedTime("long", "end"));
if (
!in_array(date("N"), self::WEEKDAYS)
|| ($currTs < $endWindow)
|| ($currTs > $startWindow)
|| Application::isLocalhost()
) {
$this->runBatch(self::LONG_RUNNING_BATCH_SUFFIX);
}
}
public function main_batch() {
$this->runBatch("");
}
private function runBatch($suffix) {
Application::increaseProcessingMax(8);
$this->setupApplication();
$activePids = $this->getPids();
foreach ($activePids as $pid) {
# note return at end of successful run because only need to run once
$token = $this->getProjectSetting("token", $pid);
$server = $this->getProjectSetting("server", $pid);
$adminEmail = $this->getProjectSetting("admin_email", $pid);
if ($token && $server) {
try {
$this->cronManager = new CronManager($token, $server, $pid, $this, $suffix);
$this->cronManager->sendEmails($activePids, $this);
$this->cronManager->runBatchJobs();
} catch (\Exception $e) {
# should only happen in rarest of circumstances
if (preg_match("/'batchCronJobs' because the value is larger than the \d+ byte limit/", $e->getMessage())) {
Application::saveSetting("batchCronJobs", [], $pid);
}
$mssg = $e->getMessage()."<br><br>".$e->getTraceAsString();
if (Application::isVanderbilt()) {
\REDCap::email($adminEmail, "noreply.flighttracker@vumc.org", CronManager::EXCEPTION_EMAIL_SUBJECT, $mssg);
} else {
CronManager::enqueueExceptionsMessageInDigest($adminEmail, $mssg);
}
}
return;
} else {
Application::log("No token or server", $pid);
}
}
}
public function getPids() {
return $this->framework->getProjectsWithModuleEnabled();
}
public function emails() {
$this->setupApplication();
$activePids = $this->getPids();
$oneHour = 3600;
// CareerDev::log($this->getName()." sending emails for pids ".json_encode($pids));
foreach ($activePids as $pid) {
if (REDCapManagement::isActiveProject($pid)) {
$token = $this->getProjectSetting("token", $pid);
$server = $this->getProjectSetting("server", $pid);
if ($token && $server) {
try {
$tokenName = $this->getProjectSetting("tokenName", $pid);
$adminEmail = $this->getProjectSetting("admin_email", $pid);
$cronStatus = $this->getProjectSetting("send_cron_status", $pid);
if ($cronStatus && (time() <= $cronStatus + $oneHour)) {
// module must be NULL to run once immediately
$this->cronManager = new CronManager($token, $server, $pid, null, self::TEST_CRON);
loadTestingCrons($this->cronManager);
$this->cronManager->run($adminEmail, $tokenName);
}
$mgr = new EmailManager($token, $server, $pid, $this);
$mgr->sendRelevantEmails();
if (
Application::isMSTP($pid)
&& MSTP::isTimeToSend($pid)
) {
MSTP::sendReminders($pid);
}
} catch (\Exception $e) {
# should only happen in rarest of circumstances
if (preg_match("/'batchCronJobs' because the value is larger than the \d+ byte limit/", $e->getMessage())) {
Application::saveSetting("batchCronJobs", [], $pid);
}
$mssg = $e->getMessage()."<br/><br/>".$e->getTraceAsString();
\REDCap::email($adminEmail, "noreply.flighttracker@vumc.org", "Flight Tracker Email Exception", $mssg);
}
}
}
}
}
# returns a boolean; modifies $normativeRow
private static function copyDataFromRowToNormative($sourceRow, $completeValue, $prefix, $metadataFields, $sourceChoices, $destChoices, &$normativeRow, $instrument) {
$hasChanged = self::copyDataFromRowToRow($sourceRow, $prefix, $metadataFields, $sourceChoices, $destChoices, "", $normativeRow);
if ($hasChanged) {
$normativeRow[$instrument."_complete"] = $completeValue;
}
return $hasChanged;
}
# returns a boolean; modifies $destRow
private static function copyDataFromRowToRow($sourceRow, $prefix, $metadataFields, $sourceChoices, $destChoices, $instrument, &$destRow) {
$hasChanged = false;
if ($sourceRow["redcap_repeat_instrument"] == $instrument) {
foreach ($sourceRow as $sourceField => $sourceValue) {
if (
preg_match("/^$prefix/", $sourceField)
&& in_array($sourceField, $metadataFields)
&& !preg_match("/honor_imported$/", $sourceField)
) {
if (
isset($sourceChoices[$sourceField])
&& isset($sourceChoices[$sourceField][$sourceValue])
&& isset($destChoices[$sourceField])
) {
$destValue = "";
foreach ($destChoices[$sourceField] as $destIdx => $destLabel) {
if (strtolower($destLabel) == strtolower($sourceChoices[$sourceField][$sourceValue])) {
$destValue = $destIdx;
}
}
if ($destValue !== "") {
$destRow[$sourceField] = $destValue;
$hasChanged = true;
}
} else {
$destRow[$sourceField] = $sourceValue;
$hasChanged = true;
}
}
}
}
return $hasChanged;
}
# returns a row if data can be copied; otherwise returns FALSE
private static function copyDataFromRowToNewRow($sourceRow, $completeValue, $prefix, $metadataFields, $sourceChoices, $destChoices, $recordId, $instrument, $newInstance) {
$newRow = [
"record_id" => $recordId,
"redcap_repeat_instrument" => $instrument,
"redcap_repeat_instance" => $newInstance,
$instrument."_complete" => $completeValue,
];
$hasChanged = self::copyDataFromRowToRow($sourceRow, $prefix, $metadataFields, $sourceChoices, $destChoices, $instrument, $newRow);
if ($hasChanged) {
return $newRow;
}
return $hasChanged;
}
private static function allFieldsMatch($fields, $row1, $row2, $choices1, $choices2) {
foreach ($fields as $testField) {
if ($choices1[$testField] && $choices2[$testField]) {
if ((array_key_exists($testField, $row1) && array_key_exists($testField, $row2)) &&
$row1[$testField] !== "" && $row2[$testField] !== "") {
$value1 = $choices1[$testField][$row1[$testField]];
$value2 = $choices2[$testField][$row2[$testField]];
} else {
return false;
}
} else {
$value1 = $row1[$testField];
$value2 = $row2[$testField];
}
if ($value1 != $value2) {
return false;
}
}
return true;
}
private static function fieldBlank($field, $row) {
if (!isset($row[$field])) {
return true;
}
if ($row[$field] === "") {
return true;
}
return false;
}
public function cleanupLogs($pid) {
$daysPrior = 10;
$this->cleanupExtModLogs($pid, $daysPrior);
}
public function cleanupExtModLogs($pid, $daysPrior) {
Application::log("Cleaning up logs...", $pid);
$ts = time() - $daysPrior * 24 * 3600;
$thresholdDate = date("Y-m-d", $ts);
$externalModuleId = CareerDev::getModuleId();
Application::log("Removing logs prior to $thresholdDate", $pid);
$numIterations = 0;
$maxRowsToDelete = 50000000;
$numRowsToDelete = 1000;
$maxIterations = $maxRowsToDelete / $numRowsToDelete;
do {
$moreToDelete = $this->deleteLogs($externalModuleId, $thresholdDate, $pid, $numRowsToDelete);
$numIterations++;
usleep(100000);
} while ($moreToDelete && ($numIterations < $maxIterations));
Application::log("Done removing logs in $numIterations iterations", $pid);
}
public function deleteLogs($externalModuleId, $thresholdDate, $pid, $numToDelete) {
$params = [$externalModuleId, $thresholdDate, $pid];
$fromAndWhereClause = "FROM redcap_external_modules_log WHERE external_module_id = ? AND timestamp <= ? AND project_id = ?";
$deleteSql = "DELETE $fromAndWhereClause LIMIT $numToDelete";
$selectSql = "SELECT log_id $fromAndWhereClause LIMIT 1";
$this->query($deleteSql, $params);
$result = $this->query($selectSql, $params);
return $result->fetch_assoc();
}
private static function isValidToCopy($fields, $sourceRow, $destRow, $sourceChoices, $destChoices) {
if ((count($fields) == 1) && self::fieldBlank($fields[0], $sourceRow)) {
# one blank field => not valid enough to copy
// Application::log("isValidToCopy Rejecting because one field blank: ".json_encode($fields));
return false;
} elseif (self::allFieldsMatch($fields, $sourceRow, $destRow, $sourceChoices, $destChoices)) {
# already copied => skip
// Application::log("isValidToCopy Rejecting because all fields match");
return false;
}
// Application::log("isValidToCopy returning TRUE");
return true;
}
private static function repeatingAlreadyUploadedToPid($fields, $sourceRow, $priorDestUploads, $sourceChoices, $destChoices) {
if (empty($priorDestUploads)) {
# no data previously uploaded => not already uploaded
return false;
}
$uploadedDestData = [];
foreach ($priorDestUploads as $sourceLicensePlate => $rows) {
# it doesn't matter if a normative row is duplicated because we're looking for a repeating instrument
$uploadedDestData = array_merge($uploadedDestData, $rows);
}
# if valid to copy repeating => not already uploaded (same logic)
return !self::isValidToCopyRepeating($fields, $sourceRow, $priorDestUploads, $sourceChoices, $destChoices);
}
private static function isValidToCopyRepeating(array $fields, array $sourceRow, array $destData, array $sourceChoices, array $destChoices) {
if ((count($fields) == 1) && self::fieldBlank($fields[0], $sourceRow)) {
# one blank field => not valid enough to copy
// Application::log("isValidToCopyRepeating Rejecting because one field blank: ".json_encode($fields));
return false;
} else {
if (REDCapManagement::isAssoc($destData)) {
throw new \Exception("Destination data should be a traditional array!");
}
foreach ($destData as $destRow) {
if (
($destRow['redcap_repeat_instrument'] == $sourceRow['redcap_repeat_instrument'])
&& self::allFieldsMatch($fields, $sourceRow, $destRow, $sourceChoices, $destChoices)
) {
# already copied => skip
// Application::log("isValidToCopyRepeating Rejecting because all fields match");
return false;
}
}
}
// Application::log("isValidToCopyRepeating returning TRUE with ".json_encode($fields)." and destData rows: ".count($destData)." ".json_encode(array_keys($destData)));
return true;
}
private static function getSharingInformation() {
$ary = [
"initial_survey" => ["prefix" => "check", "formType" => "single", "test_fields" => ["check_date"], "always_copy" => true, ],
"followup" => ["prefix" => "followup", "formType" => "repeating", "test_fields" => ["followup_date"], "debug_field" => "followup_name_last", "always_copy" => true, ],
"position_change" => [ "prefix" => "promotion", "formType" => "repeating", "test_fields" => ["promotion_job_title", "promotion_date"], "always_copy" => false, ],
// "resources" => [ "prefix" => "resources", "formType" => "repeating", "test_fields" => ["resources_date", "resources_resource"], "debug_field" => "resources_resource", "always_copy" => false, ],
"old_honors_and_awards" => [ "prefix" => "honor", "formType" => "repeating", "test_fields" => ["honor_name", "honor_date"], "debug_field" => "honor_name", "always_copy" => false, ],
"honors_awards_and_activities" => [ "prefix" => "activityhonor", "formType" => "repeating", "test_fields" => ["activityhonor_name", "activityhonor_datetime"], "debug_field" => "activityhonor_name", "always_copy" => true, ],
"honors_awards_and_activities_survey" => [ "prefix" => "surveyactivityhonor", "formType" => "repeating", "test_fields" => ["surveyactivityhonor_datetime"], "debug_field" => "surveyactivityhonor_datetime", "always_copy" => true, ],
];
if (Application::isVanderbilt()) {
// $ary['resources']['always_copy'] = true;
$ary['old_honors_and_awards']['always_copy'] = true;
$ary['position_change']['always_copy'] = true;
}
return $ary;
}
public static function getConfigurableForms() {
$forms = self::getSharingInformation();
$formsForCopy = [];
foreach ($forms as $instrument => $config) {
if (!isset($config["always_copy"]) || !$config["always_copy"]) {
$formsForCopy[] = $instrument;
}
}
$instrumentsWithLabels = [];
foreach ($formsForCopy as $instrument) {
$label = preg_replace("/_/", " ", $instrument);
$label = ucwords($label);
$instrumentsWithLabels[$instrument] = $label;
}
return $instrumentsWithLabels;
}
private function getTokensAndServersAndPids($requestedPids) {
$tokens = [];
$servers = [];
$pids = [];
foreach ($requestedPids as $pid) {
if (REDCapManagement::isActiveProject($pid)) {
$token = $this->getProjectSetting("token", $pid);
$server = $this->getProjectSetting("server", $pid);
if ($token && $server) {
$tokens[$pid] = $token;
$servers[$pid] = $server;
$pids[] = $pid;
}
}
}
return [$tokens, $servers, $pids];
}
# will be run weekly, in which case $pidsSource = $pidsDest = all active pids
# can be run on a one-time basis for a set of projects, in which case $pidsDest is a handful of pids
public function findMatches($pidsSource, $pidsDest) {
# all test_fields must be equal and, if by self (i.e., list of one), non-blank
$firstNames = [];
$lastNames = [];
$updatedRecords = [];
$allPids = array_unique(array_merge($pidsSource, $pidsDest));
list($tokens, $servers, $pids) = $this->getTokensAndServersAndPids($allPids);
# checks a list of names in an ExtMod setting to see what records have been updated.
# add to $updatedRecords when a record is new or a name has changed.
$originalPid = CareerDev::getPid();
foreach ($pids as $pid) {
if ($tokens[$pid] && $servers[$pid]) {
CareerDev::setPid($pid);
$token = $tokens[$pid];
$server = $servers[$pid];
$firstNames[$pid] = Download::firstnames($token, $server);
$lastNames[$pid] = Download::lastnames($token, $server);
if (in_array($pid, $pidsDest)) {
$updatedRecords[$pid] = array_keys($firstNames[$pid]);
if (empty($updatedRecords[$pid])) {
unset($updatedRecords[$pid]);
}
}
}
}
CareerDev::setPid($originalPid);
# push
if (!empty($updatedRecords)) {
$this->updateMatches($pidsSource, $firstNames, $lastNames, $updatedRecords);
}
foreach ($pidsDest as $currPid) {
if (isset($updatedRecords[$currPid])) {
Application::log("Found matches", $currPid);
} else {
Application::log("No updated records found", $currPid);
}
}
}
public function searchForMissingEmails($allPids) {
list($tokens, $servers, $pids) = $this->getTokensAndServersAndPids($allPids);
$usedMatches = Application::getSystemSetting(self::SHARING_SETTING) ?: [];
$emailsToUpdate = [];
foreach ($usedMatches as $matchAry) {
$infoArray = self::makeInfoArray($matchAry, $tokens, $servers);
$emailMatches = $this->alertForBlankEmails($infoArray);
foreach ($emailMatches as $emailData) {
$emailPid = $emailData["dest"]["pid"];
if (!isset($emailsToUpdate[$emailPid])) {
$emailsToUpdate[$emailPid] = [];
}
$emailsToUpdate[$emailPid][] = $emailData;
}
}
foreach ($emailsToUpdate as $emailPid => $items) {
$adminEmail = Application::getSetting("admin_email", $emailPid);
$defaultFrom = Application::getSetting("default_from", $emailPid) ?: "noreply@flightTracker.vumc.org";
if ($adminEmail && REDCapManagement::isEmailOrEmails($adminEmail)) {
$htmlRows = [];
$htmlRows[] = self::makeEmailCopyHTML($items);
$projectTitle = Download::projectTitle($emailPid);
$projectTitleHTML = Links::makeProjectHomeLink($emailPid, $projectTitle);
$introHTML = "<p>For $projectTitleHTML, the following Flight Tracker scholars have been matched. An email exists from the below source projects, but it is blank in yours. Do you want to change them? If so, please click the link to copy. <span style='text-decoration: underline; font-weight: bold;'>Note: A scholar might be matched to more than one possible email.</span></p>";
$html = $introHTML . implode("", $htmlRows);
\REDCap::email($adminEmail, $defaultFrom, "Flight Tracker New Email Matches - " . $projectTitle, $html);
}
}
}
public function addMatchProcessingToCron($destPids) {
if (!isset($this->cronManager)) {
return;
}
$matchQueueSize = count(Application::getSystemSetting(FlightTrackerExternalModule::SHARING_SETTING) ?: []);
foreach ($destPids as $pid) {
Application::log("Adding $matchQueueSize sharing matches to cron", $pid);
}
for ($index = 0; $index < ceil($matchQueueSize / FlightTrackerExternalModule::MATCHES_BATCH_SIZE); $index++) {
$this->cronManager->addMultiCron("drivers/preprocess.php", "preprocessSharingMatches", date("Y-m-d"), $destPids, $index);
}
}
private static function cleanSharingItems() {
$matches = Application::getSystemSetting(self::SHARING_SETTING) ?: [];
$newMatches = [];
$changed = false;
$recordsByPid = [];
foreach ($matches as $matchAry) {
$newMatchAry = [];
foreach ($matchAry as $licensePlate) {
list($currPid, $currRecordId) = explode(":", $licensePlate);
if (!isset($recordsByPid[$currPid])) {
$recordsByPid[$currPid] = Download::recordIdsByPid($currPid);
}
if (in_array($currRecordId, $recordsByPid[$currPid])) {
$newMatchAry[] = $licensePlate;
} else {
$changed = true;
}
}
if (count($newMatchAry) >= 2) {
$newMatches[] = $newMatchAry;
}
}
if ($changed) {
Application::saveSystemSetting(self::SHARING_SETTING, $newMatches);
}
}
# will be run weekly, in which case $pidsSource = $pidsDest = all active pids
# can be run on a one-time basis for a set of projects, in which case $pidsDest is a handful of pids
public function processFoundMatches($allPids, $destPids, $idx) {
self::cleanSharingItems();
$usedMatches = Application::getSystemSetting(self::SHARING_SETTING) ?: [];
$matchChunks = array_chunk($usedMatches, self::MATCHES_BATCH_SIZE);
if ($idx >= count($matchChunks)) {
return [];
}
$currChunk = $matchChunks[$idx];
list($tokens, $servers, $pids) = $this->getTokensAndServersAndPids($allPids);
$forms = self::getSharingInformation();
$choices = [];
$metadataFields = [];
foreach ($pids as $pid) {
$currMetadataFields = Download::metadataFieldsByPid($pid);
if (DataDictionaryManagement::isMetadataFieldsFilled($currMetadataFields)) {
$relevantFields = [];
foreach ($forms as $instrument => $array) {
$relevantFields = array_merge($relevantFields, $array["test_fields"] ?: []);
}
$relevantFields = array_unique($relevantFields);
$choices[$pid] = DataDictionaryManagement::getChoicesForFields($pid, $relevantFields);
$metadataFields[$pid] = $currMetadataFields;
Application::log("Processing ".count($currChunk)." matches in batch ".($idx + 1)." of ".count($matchChunks), $pid);
}
}
$pidsUpdated = $this->processMatchesForList($currChunk, $tokens, $servers, $forms, $metadataFields, $choices, $destPids);
foreach ($pidsUpdated as $currPid) {
Application::log("Updated match information", $currPid);
}
return $pidsUpdated;
}
private static function makeInfoArray($matchAry, $tokens, $servers) {
$pidsAffected = [];
$infoArray = [];
foreach ($matchAry as $licensePlate) {
list($currPid, $recordId) = explode(":", $licensePlate);
if (($tokens[$currPid] ?? false) && ($servers[$currPid] ?? false)) {
$infoArray[] = [
"token" => $tokens[$currPid],
"server" => $servers[$currPid],
"pid" => $currPid,
"record" => $recordId,
];
$pidsAffected[] = $currPid;
}
}
return [$infoArray, $pidsAffected];
}
private function processMatchesForList($matches, $tokens, $servers, $forms, $metadataFields, $choices, $destPids) {
$pidsUpdated = [];
$usedPids = [];
foreach ($matches as $matchAry) {
if (count($matchAry) > 1) {
foreach ($matchAry as $licensePlate) {
$currPid = explode(":", $licensePlate)[0];
if (!in_array($currPid, $usedPids)) {
$usedPids[] = $currPid;
}
}
}
}
if (empty($usedPids)) {
return [];
}
$completes = [];
foreach (array_keys($forms) as $instrument) {
$completes[$instrument] = [];
}
foreach ($usedPids as $currPid) {
$repeatingForms = DataDictionaryManagement::getRepeatingForms($currPid);
$validForms = Download::metadataFormsByPid($currPid);
foreach (array_keys($forms) as $instrument) {
if (in_array($instrument, $validForms)) {
$field = $instrument . "_complete";
if (in_array($instrument, $repeatingForms)) {
$completes[$instrument][$currPid] = Download::oneFieldWithInstancesByPid($currPid, $field);
} else {
$completes[$instrument][$currPid] = Download::oneFieldByPid($currPid, $field);
}
}
}
}
foreach ($matches as $matchAry) {
list($infoArray, $pidsAffected) = self::makeInfoArray($matchAry, $tokens, $servers);
if (!empty(array_intersect($pidsAffected, $destPids))) {
$this->copyFormData($completes, $pidsUpdated, $forms, $infoArray, $metadataFields, $choices);
$this->copyWranglerData($pidsUpdated, $infoArray);
$positionFields = ['promotion_date','promotion_job_title','promotion_in_effect','promotion_institution'];
$this->dedupRecordInstances($infoArray, $positionFields, 'position_change');
$this->dedupRecordInstances($infoArray, ['followup_date'], 'followup');
foreach ($pidsAffected as $currPid) {
Application::log("Shared data among ".implode(", ", $matchAry), $currPid);
}
$pidsUpdated = array_unique(array_merge($pidsUpdated, $pidsAffected));
}
}
return $pidsUpdated;
}
private static function makeEmailCopyHTML($items) {
$infoByLicensePlate = [];
foreach ($items as $copyInfo) {
$destPid = $copyInfo['dest']['pid'];
$destRecord = $copyInfo['dest']['record'];
$licensePlate = "$destPid:$destRecord";
if (!isset($infoByLicensePlate[$licensePlate])) {
$infoByLicensePlate[$licensePlate] = [];
}
$infoByLicensePlate[$licensePlate][] = $copyInfo;
}
$html = "";
$style = "padding: 6px; border: 1px solid #444; background-color: #AAA; color: black; text-decoration: none;";
foreach ($infoByLicensePlate as $destLicensePlate => $copyInfos) {
$numEmails = self::getNumberOfEmailAddresses($copyInfos);
if ($numEmails > 0) {
$baselineInfo = $copyInfos[0];
$destInfo = $baselineInfo['dest'];
$destRecord = $destInfo['record'];
$destName = Download::fullName($destInfo['token'], $destInfo['server'], $destRecord);
$matchWord = ($numEmails == 1) ? "Match" : "Matches";
$header = "<h2>$destName: Record $destRecord ($numEmails $matchWord)</h2>";
$htmlByEmail = [];
foreach ($copyInfos as $copyInfo) {
$sourceInfo = $copyInfo['source'];
$email = $copyInfo['email'];
$sourceName = Download::fullName($sourceInfo['token'], $sourceInfo['server'], $sourceInfo['record']);
$sourceProject = Download::projectTitle($sourceInfo['pid']);
$adoptLink = Application::link("copyEmail.php", $destInfo['pid'])."&sourcePid=".$sourceInfo['pid']."&sourceRecord=".$sourceInfo['record']."&destRecord=$destRecord";
$notAdoptLink = Application::link("copyEmail.php", $destInfo['pid'])."&skip=".urlencode($email)."&destRecord=$destRecord";
$itemHTML = "<div style='margin-top: 1em;'>Matched to $sourceName from $sourceProject. The proposed email is <strong>$email</strong>.</div>";
$itemHTML .= "<div style='margin-bottom: 1.5em; margin-top: 6px;'><a href='$adoptLink' style='$style'>Yes, please adopt this one</a> -or- <a href='$notAdoptLink' style='$style'>do not adopt this one</a></div>";
$htmlByEmail[$email] = $itemHTML;
}
$html .= $header.implode("", array_values($htmlByEmail));
}
}
return $html;
}
private static function getNumberOfEmailAddresses($infoAry) {
$emails = [];
foreach ($infoAry as $info) {
if ($info['email'] && !in_array($info['email'], $emails) && REDCapManagement::isEmailOrEmails($info['email'])) {
$emails[] = $info['email'];
}
}
return count($emails);
}
private function alertForBlankEmails(array $infoArray): array {
$hasEmails = [];
$missingEmails = [];
foreach ($infoArray as $info) {
$currPid = $info['pid'];
$recordId = $info['record'];
$omitted = Application::getSetting("omittedEmails", $currPid) ?: [];
$email = Download::oneFieldForRecordByPid($currPid, "identifier_email", $recordId);
$proceed = true;
foreach ($omitted[$recordId] ?? [] as $omittedEmail) {
if (strtolower($omittedEmail) == strtolower($email)) {
$proceed = false;
}
}
if ($proceed) {
if (REDCapManagement::isEmailOrEmails($email)) {
$hasEmails[$email] = $info;
} else {
$missingEmails[] = $info;
}
}
}
if (!empty($hasEmails) && !empty($missingEmails)) {
$returnItems = [];
foreach ($hasEmails as $sourceEmail => $sourceInfo) {
foreach ($missingEmails as $destInfo) {
$returnItems[] = [
"source" => $sourceInfo,
"dest" => $destInfo,
"email" => $sourceEmail,
];
}
}
return $returnItems;
} else {
return [];
}
}
# the main function that updates the matches hash based on name-matching
# takes a while at first run, but only updates for those specified in $updatedRecordsByPid
private function updateMatches($pidsSource, $firstNames, $lastNames, $updatedRecordsByPid) {
if (date("d") <= 7) {
# reset once a month, on the first week of the month, to weed out dated matches
# cleanSharingItems() already removes bad matches
$priorSearchedFor = [];
} else {
$priorSearchedFor = Application::getSystemSetting(self::SHARING_SETTING) ?: [];
}
foreach ($updatedRecordsByPid as $pid => $records) {
Application::log("Looking for matches", $pid);
foreach ($records as $recordId) {
$firstName = $firstNames[$pid][$recordId] ?? "";
$lastName = $lastNames[$pid][$recordId] ?? "";
foreach ($pidsSource as $sourcePid) {
if (!empty($firstNames[$sourcePid]) && !empty($lastNames[$sourcePid]) && ($sourcePid != $pid)) {
foreach ($lastNames[$sourcePid] as $sourceRecordId => $ln) {
$fn = $firstNames[$sourcePid][$sourceRecordId] ?? "";
$foundMatch = false;
foreach (NameMatcher::explodeFirstName($firstName) as $pidFn) {
foreach (NameMatcher::explodeLastName($lastName) as $pidLn) {
if (NameMatcher::matchName($pidFn, $pidLn, $fn, $ln)) {
$foundMatch = true;
$newLicensePlate = "$pid:$recordId";
$oldLicensePlate = "$sourcePid:$sourceRecordId";
Application::log("New Match between $oldLicensePlate and $newLicensePlate: $pidFn $pidLn and $fn $ln", $pid);
Application::log("New Match between $oldLicensePlate and $newLicensePlate: $pidFn $pidLn and $fn $ln", $sourcePid);
$foundInPrior = false;
foreach ($priorSearchedFor as $i => $matches) {
if (in_array($oldLicensePlate, $matches) && in_array($newLicensePlate, $matches)) {
$foundInPrior = true;
} elseif (in_array($oldLicensePlate, $matches) && !in_array($newLicensePlate, $matches)) {
$priorSearchedFor[$i][] = $newLicensePlate;
$foundInPrior = true;
}
}
if (!$foundInPrior) {
$priorSearchedFor[] = [$oldLicensePlate, $newLicensePlate];
}
break;
}
}
if ($foundMatch) {
break;
}
}
}
}
}
}
}
$this->disableUserBasedSettingPermissions();
Application::saveSystemSetting(self::SHARING_SETTING, $priorSearchedFor);
}
private static function explodeAllNames($lastName, $firstName) {
$combos = [];
foreach (NameMatcher::explodeFirstName($firstName) as $fn) {
foreach (NameMatcher::explodeLastName($lastName) as $ln) {
if ($fn && $ln) {
$name = "$fn $ln";
$combos[$name] = ["first" => $fn, "last" => $ln];
}
}
}
return array_values($combos);
}
public function copyWranglerData(&$pidsUpdated, $infoArray) {
if (count($infoArray) < 2) {
return;
}
$pubDataByPid = [];
$grantDataByPid = [];
$originalPid = CareerDev::getPid();
foreach ($infoArray as $info) {
$currPid = $info['pid'];
if (!isset($pubDataByPid[$currPid]) || !isset($grantDataByPid[$currPid])) {
$citationFields = ['record_id', 'citation_pmid', 'citation_include'];
CareerDev::setPid($currPid);
$pubDataByPid[$currPid] = Download::fieldsForRecordsByPid($currPid, $citationFields, [$info['record']]);
$grantDataByPid[$currPid] = self::getToImport($currPid, $info['record']);
}
}
CareerDev::setPid($originalPid);
foreach ($infoArray as $sourceInfo) {
foreach ($infoArray as $destInfo) {
if (($destInfo['pid'] != $sourceInfo['pid']) || ($destInfo['record'] != $sourceInfo['record'])) {
$sourcePubData = $pubDataByPid[$sourceInfo['pid']] ?? [];
$destPubData = $pubDataByPid[$destInfo['pid']] ?? [];
$sourceToImport = $grantDataByPid[$sourceInfo['pid']] ?? [];
$destToImport = $grantDataByPid[$destInfo['pid']] ?? [];
$hasCopiedPubData = $this->copyPubData($sourceInfo, $destInfo, $sourcePubData, $destPubData);
$hasCopiedGrantData = $this->copyGrantData($destInfo, $sourceToImport, $destToImport);
if (
($hasCopiedGrantData || $hasCopiedPubData)
&& !in_array($destInfo['pid'], $pidsUpdated)
) {
$pidsUpdated[] = $destInfo['pid'];
}
}
}
}
}
private function copyPubData($sourceInfo, $destInfo, $sourceData, $destData) {
$sourcePMIDs = self::transformREDCapDataToPMIDsAndIncludes($sourceData, $sourceInfo['record']);
$destPMIDs = self::transformREDCapDataToPMIDsAndIncludes($destData, $destInfo['record']);
$uploadData = [];
foreach ($sourcePMIDs as $pmid => $sourceAry) {
$sourceIncludeStatus = $sourceAry['include'];
if (($sourceIncludeStatus !== "") && isset($destPMIDs[$pmid])) {
$destIncludeStatus = $destPMIDs[$pmid]['include'];
$destInstance = $destPMIDs[$pmid]['instance'];
if ($destIncludeStatus === "") {
$uploadData[] = [
"record_id" => $destInfo['record'],
"redcap_repeat_instrument" => "citation",
"redcap_repeat_instance" => $destInstance,
"citation_include" => $sourceIncludeStatus,
];
}
}
}
if (!empty($uploadData)) {
Application::log("Sharing publication wrangling data from {$sourceInfo['pid']} (record {$sourceInfo['record']}) to {$destInfo['pid']}(record {$destInfo['record']})");
try {
Upload::rows($uploadData, $destInfo['token'], $destInfo['server']);
return true; // data shared
} catch (\Exception $e) {
Application::log("Warning: Data sharing publication upload failed! ".$e->getMessage());
return false; // data sharing failed
}
} else {
return false; // no data shared
}
}
private static function transformREDCapDataToPMIDsAndIncludes($redcapData, $recordId) {
$pmids = [];
foreach ($redcapData as $row) {
if (($row['redcap_repeat_instrument'] == "citation") && ($row['record_id'] == $recordId) && $row['citation_pmid']) {
$pmids[$row['citation_pmid']] = [
"include" => $row['citation_include'],
"instance" => $row['redcap_repeat_instance'],
];
}
}
return $pmids;
}
private static function getToImport($pid, $recordId) {
$fields = ["record_id", "summary_calculate_to_import"];
$redcapData = Download::fieldsForRecordsByPid($pid, $fields, [$recordId]);
$normativeRow = REDCapManagement::getNormativeRow($redcapData);
$toImport = [];
if ($normativeRow['summary_calculate_to_import']) {
$toImport = json_decode($normativeRow['summary_calculate_to_import'], true);
if ($toImport === false) {
$toImport = [];
}
}
return $toImport;
}
private function copyGrantData($destInfo, $sourceToImport, $destToImport) {
# ??? Custom Grants
if (!empty($sourceToImport)) {
$destChanged = false;
foreach ($sourceToImport as $key => $value) {
if (!isset($destToImport[$key])) { // copies only new information; does not copy in case of conflict
$destToImport[$key] = $value;
$destChanged = true;
}
}
if ($destChanged) {
$uploadRow = [
"record_id" => $destInfo['record'],
"redcap_repeat_instrument" => "",
"redcap_repeat_instance" => "",
"summary_calculate_to_import" => json_encode($destToImport),
];
try {
Upload::oneRow($uploadRow, $destInfo['token'], $destInfo['server']);
return true; // data sharing succeeded
} catch (\Exception $e) {
Application::log("Warning: Data sharing publication upload failed! ".$e->getMessage());
return false; // data sharing failed
}
}
}
return false; // no data to copy
}
private function cleanupFormData($forms, $destInfo, $destMetadataFields) {
foreach ($forms as $instrument => $sharingData) {
if (($sharingData['formType'] == "repeating") && ($sharingData['debug_field'] ?? false)) {
$debugField = $sharingData['debug_field'];
$completeField = $instrument."_complete";
$relevantFields = array_unique(array_merge(["record_id", $completeField], DataDictionaryManagement::filterFieldsForPrefix($destMetadataFields, $sharingData['prefix'])));
$redcapData = Download::fieldsForRecords($destInfo['token'], $destInfo['server'], $relevantFields, [$destInfo['record']]);
$instancesToDelete = [];
foreach ($redcapData as $row) {
if (($row['redcap_repeat_instrument'] == $instrument) && isset($row[$debugField]) && ($row[$debugField] === "")) {
$instancesToDelete[] = $row['redcap_repeat_instance'];
}
}
if (!empty($instancesToDelete)) {
Upload::deleteFormInstances($destInfo['token'], $destInfo['server'], $destInfo['pid'], $sharingData['prefix'], $destInfo['record'], $instancesToDelete);
}
}
}
}
private function copyFormData(&$completes, &$pidsUpdated, $forms, $infoArray, $metadataFieldsByPid, $choicesByPid) {
$originalPid = CareerDev::getPid();
$repeatingFormsByPid = [];
foreach ($infoArray as $info) {
CareerDev::setPid($info['pid']);
$repeatingFormsByPid[$info['pid']] = DataDictionaryManagement::getRepeatingForms($info['pid']);
foreach (array_keys($forms) as $instrument) {
if (!isset($completes[$instrument][$info['pid']])) {
$field = $instrument . "_complete";
if (in_array($instrument, $repeatingFormsByPid[$info['pid']])) {
$completes[$instrument][$info['pid']] = Download::oneFieldWithInstances($info['token'], $info['server'], $field);
} else {
$completes[$instrument][$info['pid']] = Download::oneField($info['token'], $info['server'], $field);
}
}
}
}
CareerDev::setPid($originalPid);
foreach ($completes as $instrument => $completeData) {
$pidsProcessed = $this->processInstrument(
$instrument,
$forms,
$completeData,
$infoArray,
$choicesByPid,
$metadataFieldsByPid,
$repeatingFormsByPid
);
$pidsUpdated = array_unique(array_merge($pidsProcessed, $pidsUpdated));
}
}
private function dedupRecordInstances($infoArray, $fields, $instrument) {
$dataFields = array_unique(array_merge(["record_id", $instrument."_complete"], $fields));
foreach ($infoArray as $info) {
$redcapData = Download::fieldsForRecordsByPid($info['pid'], $dataFields, [$info['record']]);
$seenItems = [];
foreach ($redcapData as $row) {
$item = "";
foreach ($fields as $field) {
if ($item != "") {
$item .= ":";
}
$item .= $row[$field];
}
if ($item == "") {
continue;
}
if ($row['redcap_repeat_instrument'] == $instrument) {
if (in_array($item, $seenItems)) {
\REDCap::deleteRecord($info['pid'], $info['record'], null, null, $instrument, $row['redcap_repeat_instance']);
} else {
$seenItems[] = $item;
}
}
}
}
}
private function dedupChoicesOnlyError($projToken, $projServer, $projPid, $instrument) {