-
Notifications
You must be signed in to change notification settings - Fork 4
/
small_base.php
1929 lines (1781 loc) · 69.5 KB
/
small_base.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\FlightTrackerExternalModule;
use PhpParser\Node\Expr\AssignOp\BitwiseOr;
use \Vanderbilt\CareerDevLibrary\Citation;
use \Vanderbilt\CareerDevLibrary\CohortConfig;
use \Vanderbilt\CareerDevLibrary\Cohorts;
use \Vanderbilt\CareerDevLibrary\Consortium;
use \Vanderbilt\CareerDevLibrary\CronManager;
use \Vanderbilt\CareerDevLibrary\Definitions;
use \Vanderbilt\CareerDevLibrary\Download;
use \Vanderbilt\CareerDevLibrary\EmailManager;
use \Vanderbilt\CareerDevLibrary\Filter;
use \Vanderbilt\CareerDevLibrary\Grant;
use \Vanderbilt\CareerDevLibrary\GrantFactory;
use \Vanderbilt\CareerDevLibrary\GrantLexicalTranslator;
use \Vanderbilt\CareerDevLibrary\Grants;
use \Vanderbilt\CareerDevLibrary\LDAP;
use \Vanderbilt\CareerDevLibrary\Links;
use \Vanderbilt\CareerDevLibrary\NameMatcher;
use \Vanderbilt\CareerDevLibrary\NavigationBar;
use \Vanderbilt\CareerDevLibrary\NIHExPORTER;
use \Vanderbilt\CareerDevLibrary\OracleConnection;
use \Vanderbilt\CareerDevLibrary\Publications;
use \Vanderbilt\CareerDevLibrary\REDCapManagement;
use \Vanderbilt\CareerDevLibrary\Scholar;
use \Vanderbilt\CareerDevLibrary\Upload;
use \Vanderbilt\CareerDevLibrary\iCite;
use \Vanderbilt\CareerDevLibrary\Application;
use \Vanderbilt\CareerDevLibrary\ConnectionStatus;
use \Vanderbilt\CareerDevLibrary\DataDictionaryManagement;
use \Vanderbilt\CareerDevLibrary\FeatureSwitches;
use \Vanderbilt\CareerDevLibrary\DateManagement;
use \Vanderbilt\CareerDevLibrary\Sanitizer;
use \Vanderbilt\CareerDevLibrary\URLManagement;
use \Vanderbilt\CareerDevLibrary\FileManagement;
use \Vanderbilt\CareerDevLibrary\Dashboard;
use \Vanderbilt\CareerDevLibrary\ReactNIHTables;
use \Vanderbilt\CareerDevLibrary\NIHTables;
require_once(__DIR__."/autoload.php");
ini_set("memory_limit", "4096M");
ini_set("auto_detect_line_endings", true);
if (!Application::isWebBrowser() && CareerDev::getPid()) {
date_default_timezone_set(CareerDev::getTimezone());
}
$pid = Sanitizer::sanitize(isset($module) ? $module->getProjectId($_GET['pid'] ?? "") : Sanitizer::sanitizePid($_GET['pid'] ?? ""));
if (!$pid && !Application::isWebBrowser() && is_array($argv) && (count($argv) >= 2) && in_array($argv[1], Application::getPids())) {
$pid = $argv[1];
$_GET['pid'] = $pid;
}
if (!$pid) {
if (isset($_GET['project_id']) && $_GET['project_id']) {
$pid = CareerDev::getSetting("pid", $_GET['project_id']);
} else {
$pid = CareerDev::getSetting("pid");
}
$_GET['pid'] = $pid;
}
define('INSTITUTION', CareerDev::getInstitution($pid));
define('PROGRAM_NAME', CareerDev::getProgramName());
define("ENVIRONMENT", "prod"); // for Oracle database connectivity
if (!isset($module) || !$module) {
$module = Application::getModule();
}
if (!$module) {
throw new \Exception("The base class has no module!");
}
$token = Application::getSetting("token", $pid);
try {
$token = Application::checkOrResetToken($token, $pid);
} catch (\Exception $e) {
if (!$token && USERID && $module->canRedirectToInstall()) {
header("Location: ".CareerDev::link("install.php"));
} else if (Sanitizer::sanitize($_GET['page'] ?? "") != "install") {
throw $e;
}
}
$server = Application::getSetting("server", $pid);
$event_id = Application::getSetting("event_id", $pid);
$tokenName = Application::getSetting("tokenName", $pid);
$adminEmail = Application::getSetting("admin_email", $pid);
$grantClass = Application::getSetting("grant_class", $pid);
$GLOBALS['pid'] = $pid;
$GLOBALS['server'] = $server;
$GLOBALS['token'] = $token;
$GLOBALS['tokenName'] = $tokenName;
$GLOBALS['event_id'] = $event_id;
$GLOBALS['module'] = $module;
$GLOBALS['adminEmail'] = $adminEmail;
$GLOBALS['grantClass'] = $grantClass;
set_exception_handler('\Vanderbilt\FlightTrackerExternalModule\displayException');
// set_error_handler('\Vanderbilt\FlightTrackerExternalModule\displayError');
############# FUNCTIONS ################
function displayException($exception) {
global $pid;
$header = "Flight Tracker Error!";
Application::log("Exception: ".$exception->getMessage(), $pid);
echo "<div class='red padded max-width' style='text-align: center;'><strong>".$header."</strong><br/>".$exception->getMessage()."<br/>File: ".$exception->getFile()."; Line: ".$exception->getLine()."<br/><code class='alignLeft'>".$exception->getTraceAsString()."</code></div>";
}
function displayError($error) {
# unimplemented
}
function getBaseAwardNumber($num) {
return Grant::translateToBaseAwardNumber($num);
}
function getDepartmentChoices() {
$choices2 = [];
$choices2[104300] = "Anesthesiology [104300]";
$choices2[104250] = "Biochemistry [104250]";
$choices2[120450] = "Biological Sciences [120450]";
$choices2[104785] = "Biomedical Informatics [104785]";
$choices2[104286] = "Cancer Biology [104286]";
$choices2[104280] = "Cell and Developmental Biology [104280]";
$choices2[104226] = "Center for Human Genetics Research [104226]";
$choices2[120430] = "Chemistry [120430]";
$choices2[104791] = "Emergency Medicine/Administration [104791]";
$choices2[104625] = "Health Policy [104625]";
$choices2[104782] = "Hearing And Speech Sciences [104782]";
$choices2[104216] = "Institute for Global Health [104216]";
$choices2[130100] = "Kennedy Center Institute (MC) [130100]";
$choices2[122450] = "Mechanical Engineering [122450]";
$choices2[104368] = "Medicine [104368]";
$choices2[104383] = "Medicine/Allergy Pulmonary & Critical Care [104383]";
$choices2[104333] = "Medicine/Cardiovascular Medicine [104333]";
$choices2[104342] = "Medicine/Clinical Pharmacology [104342]";
$choices2[104348] = "Medicine/Dermatology [104348]";
$choices2[104351] = "Medicine/Diabetes Endocrinology [104351]";
$choices2[104370] = "Medicine/Epidemiology [104370]";
$choices2[104355] = "Medicine/Gastroenterology [104355]";
$choices2[104366] = "Medicine/General Internal Medicine [104366]";
$choices2[104353] = "Medicine/Genetic Medicine [104353]";
$choices2[104379] = "Medicine/Hematology Oncology [104379]";
$choices2[104362] = "Medicine/Infectious Disease [104362]";
$choices2[104375] = "Medicine/Nephrology [104375]";
$choices2[104386] = "Medicine/Rheumatology [104386]";
$choices2[104336] = "Medicine/Stahlman Cardio Research [104336]";
$choices2[104270] = "Molecular Physiology & Biophysics [104270]";
$choices2[104400] = "Neurology [104400]";
$choices2[104407] = "Neurology/Cognitive Disorders [104407]";
$choices2[104403] = "Neurology/Epilepsy [104403]";
$choices2[104412] = "Neurology/Immunology [104412]";
$choices2[104409] = "Neurology/Movement Disorders [104409]";
$choices2[104415] = "Neurology/Neuromuscular [104415]";
$choices2[104418] = "Neurology/Oncology [104418]";
$choices2[104410] = "Neurology/Sleep Disorders [104410]";
$choices2[104425] = "Obstetrics and Gynecology [104425]";
$choices2[104450] = "Ophthalmology [104450]";
$choices2[104481] = "Ortho - Oncology [104481]";
$choices2[104475] = "Orthopaedics and Rehabilitation [104475]";
$choices2[999999] = "Other (999999)";
$choices2[104781] = "Otolaryngology [104781]";
$choices2[104500] = "Pathology [104500]";
$choices2[104555] = "Pediatrics/Adolescent Medicine [104555]";
$choices2[104565] = "Pediatrics/Cardiology [104565]";
$choices2[104570] = "Pediatrics/Child Development [104570]";
$choices2[104568] = "Pediatrics/Clinical Research Office [104568]";
$choices2[104582] = "Pediatrics/Emergency Medicine [104582]";
$choices2[104580] = "Pediatrics/Endocrinology [104580]";
$choices2[104585] = "Pediatrics/Gastroenterology [104585]";
$choices2[104595] = "Pediatrics/General Pediatrics [104595]";
$choices2[104590] = "Pediatrics/Genetics [104590]";
$choices2[104598] = "Pediatrics/Hematology [104598]";
$choices2[104623] = "Pediatrics/Hospital Medicine [104623]";
$choices2[104606] = "Pediatrics/Infectious Disease [104606]";
$choices2[104610] = "Pediatrics/Neonatology [104610]";
$choices2[104600] = "Pediatrics/Neurology [104600]";
$choices2[104621] = "Pediatrics/Pulmonary [104621]";
$choices2[104592] = "Pediatrics/Vanderbilt-Meharry Center in Sickle Cell [104592]";
$choices2[104290] = "Pharmacology [104290]";
$choices2[104291] = "Pharmacology/Clin Pharm [104291]";
$choices2[104795] = "Physical Medicine and Rehabilitation [104795]";
$choices2[104529] = "Psychiatry/Adult Psychiatry [104529]";
$choices2[104535] = "Psychiatry/Child & Adolescent Psychiatry [104535]";
$choices2[120660] = "Psychology [120660]";
$choices2[104675] = "Radiation Oncology [104675]";
$choices2[104650] = "Radiology and Radiological Science [104650]";
$choices2[106052] = "School of Nursing - Research Faculty [106052]";
$choices2[104703] = "Section of Surgical Science [104703]";
$choices2["SFS"] = "Service Free Stipends [SFS]";
$choices2[126230] = "Special Education [126230]";
$choices2[104477] = "Sports Medicine [104477]";
$choices2[104705] = "Surgery [104705]";
$choices2[104714] = "Surgery/Liver Transplant [104714]";
$choices2[104760] = "Surgery/Pediatric Surgery [104760]";
$choices2[104709] = "Surgery/Surgical Oncology [104709]";
$choices2[104726] = "Surgery/Thoracic Surgery [104726]";
$choices2[104717] = "Surgery/Trauma [104717]";
$choices2[104775] = "Urologic Surgery [104775]";
$choices2[104201] = "Vanderbilt Vaccine Center [104201]";
$choices2[104268] = "Biostatistics (104268)";
$choices2[104267] = "Biostatistics/Cancer Biostatistics (104267)";
$choices2[104202] = "Center for Biomedical Ethics and Society (104202)";
$choices2[104790] = "Emergency Medicine (104790)";
$choices2[104204] = "Institute of Medicine and Public Health (104204)";
$choices2[120727] = "Medicine, Health & Society (120727)";
}
function getReverseAwardTypes() {
return Grant::getReverseAwardTypes();
}
function getAwardTypes() {
return Grant::getAwardTypes();
}
# return boolean
function coeusNameMatch($n1, $n2) {
if (($n1 == "ho") || ($n2 == "ho") && (($n1 == "holden") || ($n2 == "holden"))) {
if ($n1 == $n2) {
return true;
}
} else {
if (preg_match("/^".$n1."/", $n2) || preg_match("/^".$n2."/", $n1)) {
return true;
}
}
if (preg_match("/[\(\-]".$n1."/", $n2) || preg_match("/[\(\-]".$n2."/", $n1)) {
return true;
}
return false;
}
# get rid of trailing initial
function coeusFixForMatch($n) {
$n = preg_replace("/\s+\w\.$/", "", $n);
$n = preg_replace("/\s+\w$/", "", $n);
$n = str_replace("???", "", $n);
return strtolower($n);
}
# returns true/false over whether the names "match"
function coeusMatch($fn1, $ln1, $fn2, $ln2) {
if (preg_match("/\s+\(.+\)/", $fn1)) {
$fn1 = preg_replace("/\s+\(.+\)/", "", $fn1);
}
$ln1s = array($ln1);
if (preg_match("/[\s\-]/", $ln1)) {
array_push($ln1s, preg_replace("/\-/", " ", $ln1), preg_replace("/\s/", "-", $ln1));
}
if (preg_match("/[a-z][A-Z]/", $ln1)) {
array_push($ln1s, preg_replace("/([a-z])([A-z])/", "$1 $2", $ln1));
}
if (preg_match("/[a-z] [A-Z]/", $ln1)) {
array_push($ln1s, preg_replace("/([a-z]) ([A-z])/", "$1$2", $ln1));
}
if (preg_match("/\s+\(.+\)/", $fn2)) {
$fn2 = preg_replace("/\s+\(.+\)/", "", $fn2);
}
$ln2s = array($ln2);
if (preg_match("/[\s\-]/", $ln2)) {
array_push($ln2s, preg_replace("/\-/", " ", $ln2), preg_replace("/\s/", "-", $ln2));
}
if (preg_match("/[a-z][A-Z]/", $ln2)) {
array_push($ln2s, preg_replace("/([a-z])([A-z])/", "$1 $2", $ln2));
}
if (preg_match("/[a-z] [A-Z]/", $ln2)) {
array_push($ln2s, preg_replace("/([a-z]) ([A-z])/", "$1$2", $ln2));
}
foreach ($ln1s as $ln1a) {
foreach ($ln2s as $ln2a) {
if ($fn1 && $ln1a && $fn2 && $ln2a) {
$fn1 = coeusFixForMatch($fn1);
$fn2 = coeusFixForMatch($fn2);
$ln1a = coeusFixForMatch($ln1a);
$ln2a = coeusFixForMatch($ln2a);
if (coeusNameMatch($fn1, $fn2) && coeusNameMatch($ln1a, $ln2a)) {
return true;
}
}
}
}
return false;
}
# returns recordId that matches
# returns "" if no match
function matchName($first, $last) {
global $token, $server;
return NameMatcher::matchName($first, $last, $token, $server);
}
# returns an array of recordId's that matches respective last, first
# returns "" if no match
function matchNames($firsts, $lasts) {
global $token, $server;
return NameMatcher::matchNames($firsts, $lasts, $token, $server);
}
function prettyMoney($n, $displayCents = TRUE) {
return REDCapManagement::prettyMoney($n, $displayCents);
}
function pretty($n, $numDecimalPlaces = 3) {
return REDCapManagement::pretty($n, $numDecimalPlaces);
}
function downloadURL($url) {
global $pid;
return REDCapManagement::downloadURL($url, $pid);
}
# given two timestamps (UNIX) $start, $end - let's call this duration.
# provide the timestamps of a larger period, $yearStart, $yearEnd
# figures the fraction of the year that is filled by the duration
# returns value | 0 <= value <= 1
function calculateFractionEffort($start, $end, $yearStart, $yearEnd) {
if ($start && $end) {
$grantDur = $end - $start;
$yearDur = $yearEnd - $yearStart;
$currDur = 0;
if (($start >= $yearStart) && ($start <= $yearEnd)) {
if ($end > $yearEnd) {
$currDur = $yearEnd - $start;
} else {
$currDur = $end - $start;
}
} else if (($end >= $yearStart) && ($end <= $yearEnd)) {
# currStart before yearStart
$currDur = $end - $yearStart;
} else if (($end > $yearEnd) && ($start < $yearStart)) {
$currDur = $yearDur;
}
return $currDur / $grantDur;
}
return 0;
}
# helper function to add to grant totals
# totals is the array with the totals (fields direct, vumc, nonvumc)
# row is the REDCap row with either COEUS or RePORTER/ExPORTER data
# instrument is coeus or exporter, or reporter, or custom
# fraction is the amount of the budget to be allocated for the current year. 0 <= value <= 1
# base award numbers are those base award numbers in reporter that do not need to be included from COEUS
function addToGrantTotals($totals, $row, $instrument, $fraction, $usedBaseAwardNumbers) {
if ($instrument == "coeus") {
$awardNo = $row['coeus_sponsor_award_number'];
$baseAwardNumber = getBaseAwardNumber($awardNo);
if ($row['coeus_direct_cost_budget_period']) {
$part = floor($fraction * $row['coeus_direct_cost_budget_period']);
$totals['direct'] += $part;
// echo "SUMMARY GRANTS A $fraction direct {$row['coeus_direct_cost_budget_period']} Adding $part = {$totals['direct']} $awardNo\n";
} else {
// echo "SUMMARY GRANTS B\n";
}
if (!in_array($baseAwardNumber, $usedBaseAwardNumbers) && $row['coeus_total_cost_budget_period']) {
$part = floor($fraction * $row['coeus_total_cost_budget_period']);
$totals['vumc'] += $part;
// echo "SUMMARY GRANTS C $fraction total {$row['coeus_total_cost_budget_period']} Adding $part = {$totals['vumc']} $awardNo\n";
} else {
// echo "SUMMARY GRANTS D '{$row['coeus_total_cost_budget_period']}' $baseAwardNumber: ".json_encode($usedBaseAwardNumbers)."\n";
}
} else if ($instrument == "exporter") {
$awardNo = $row['exporter_full_project_num'];
$baseAwardNumber = getBaseAwardNumber($awardNo);
if ($row['exporter_org_name'] && preg_match("/vanderbilt/", strtolower($row['exporter_org_name']))) {
if (!in_array($baseAwardNumber, $usedBaseAwardNumbers) && $row['exporter_total_cost']) {
$part = floor($fraction * $row['exporter_total_cost']);
$totals['vumc'] += $part;
// echo "SUMMARY GRANTS E $fraction total {$row['exporter_total_cost']} Adding $part = {$totals['vumc']} $awardNo\n";
} else {
// echo "SUMMARY GRANTS F $awardNo seen before\n";
}
} else {
$totals['nonvumc'] += floor($fraction * $row['exporter_total_cost']);
}
} else if ($instrument == "reporter") {
$awardNo = $row['reporter_projectnumber'];
$baseAwardNumber = getBaseAwardNumber($awardNo);
if ($row['reporter_orgname'] && preg_match("/vanderbilt/", strtolower($row['reporter_orgname']))) {
if (!in_array($baseAwardNumber, $usedBaseAwardNumbers) && $row['reporter_totalcostamount']) {
$part = floor($fraction * $row['reporter_totalcostamount']);
$totals['vumc'] += $part;
// echo "SUMMARY GRANTS G $fraction total {$row['reporter_totalcostamount']} Adding $part = {$totals['vumc']} $awardNo\n";
} else {
// echo "SUMMARY GRANTS H $awardNo seen before\n";
}
} else {
$totals['nonvumc'] += floor($fraction * $row['reporter_totalcostamount']);
}
} else if ($instrument == "custom_grant") {
$awardNo = $row['custom_number'];
$baseAwardNumber = getBaseAwardNumber($awardNo);
if (!in_array($baseAwardNumber, $usedBaseAwardNumbers) && $row['custom_costs']) {
$totals['direct'] += floor($fraction * $row['custom_costs']);
$totals['vumc'] += floor($fraction * $row['custom_costs']);
}
}
return $totals;
}
# gets the time from a RePORTER formatting (YYYY-MM-DDThh:mm:ss);
function getReporterTime($dt) {
if (!$dt) {
return "";
}
$nodes = preg_split("/T/", $dt);
if (count($nodes) != 2) {
return "";
}
return $nodes[1];
}
# gets the date from a RePORTER formatting (YYYY-MM-DDThh:mm:ss);
# returns YYYY-MM-DD
function getReporterDate($dt) {
return REDCapManagement::getReporterDateInYMD($dt);
}
function getCohorts($row) {
$ary = array();
$years = getCohort($row);
$ary[] = $years;
$KL2s = array("VCTRSKL2", "KL2", "VPSD", "VCTRS");
for ($i = 1; $i <= 15; $i++) {
# KL2 or Internal K
if (preg_match("/KL2/", $row['summary_award_sponsorno_'.$i]) || (in_array($row['summary_award_sponsorno_'.$i], $KL2s) && ($row['summary_award_type_'.$i] == 2)) || ($row['summary_award_type_'.$i] == 1)) {
if (!in_array("KL2s + Int_Ks", $ary)) {
$ary[] = "KL2s + Int_Ks";
}
}
}
return $ary;
}
function getCohort($row) {
$begins = array(1998, 2003, 2008, 2013);
$ends = array(2002, 2007, 2012, 2017);
for ($i = 1; $i <= 15; $i++) {
if ($row['summary_award_date_'.$i] && ($row['summary_award_type_'.$i] >= 1) && ($row['summary_award_type_'.$i] <= 4)) {
$nodes = preg_split("/-/", $row['summary_award_date_'.$i]);
for ($j = 0; $j < count($begins); $j++) {
if (($begins[$j] <= $nodes[0]) && ($ends[$j] >= $nodes[0])) {
return $begins[$j]."-".$ends[$j];
}
}
}
}
return "";
}
function json_encode_with_spaces($data) {
return REDCapManagement::json_encode_with_spaces($data);
}
function YMD2MDY($ymd) {
return REDCapManagement::YMD2MDY($ymd);
}
function MDY2YMD($mdy) {
return REDCapManagement::MDY2YMD($mdy);
}
function getLabels($metadata) {
return REDCapManagement::getLabels($metadata);
}
function getChoices($metadata) {
return REDCapManagement::getChoices($metadata);
}
function getAlphabetizedNames($token, $server) {
$names = Download::names($token, $server);
$lastNames = Download::lastnames($token, $server);
asort($lastNames);
$orderedNames = array();
foreach ($lastNames as $recordId => $lastName) {
$orderedNames[$recordId] = $names[$recordId];
}
return $orderedNames;
}
function getNamesForRow($row) {
$firstNamesPre = preg_split("/[\s\-]/", $row['identifier_first_name']);
$firstNames = array();
foreach ($firstNamesPre as $firstName) {
if (preg_match("/^\(.+\)$/", $firstName, $matches)) {
$match = preg_replace("/^\(/", "", $matches[0]);
$match = preg_replace("/\)$/", "", $match);
$firstNames[] = $match;
} else {
$firstNames[] = $firstName;
}
}
$lastNames = preg_split("/[\s\-]/", $row['identifier_last_name']);
$names = array($row['identifier_first_name']." ".$row['identifier_last_name']);
foreach ($firstNames as $firstName) {
foreach ($lastNames as $lastName) {
if (!in_array($firstName." ".$lastName, $names)) {
$names[] = $firstName." ".$lastName;
}
}
}
return $names;
}
# returns two-item array;
# first item: from array("Converted", "On Internal K", "On External K", "Left", "Not Converted")
# second item: the time the event has happened or will happen. NULL if Not Converted
function getConvertedStatus($normativeRow) {
if ($normativeRow['summary_first_r01']) {
return array("Converted", $normativeRow['summary_first_r01']);
}
if ($normativeRow['summary_left_vanderbilt']) {
return array("Left", $normativeRow['summary_left_vanderbilt']);
}
if ($normativeRow["summary_last_external_k"]) {
$today = time();
$start = strtotime($normativeRow['summary_last_external_k']);
$endDate = date("m-d", $start);
$endYear = date("Y", $start) + 5;
$end = strtotime($endYear."-".$endDate);
$extKs = array(3, 4);
for ($i = 1; $i <= 15; $i++) {
if (in_array($normativeRow['summary_award_type_'.$i], $extKs)) {
if ($normativeRow['summary_award_end_date_'.$i]) {
$currEndTs = strtotime($normativeRow['summary_award_end_date_'.$i]);
if ($currEndTs > $end) {
$end = $currEndTs;
}
}
}
}
if ($end > $today) {
return array("On External K", date("Y-m-d", $end));
}
}
if ($normativeRow["summary_last_any_k"]) {
$today = time();
$start = strtotime($normativeRow['summary_last_any_k']);
$endDate = date("m-d", $start);
$endYear = date("Y", $start) + 3;
$end = strtotime($endYear."-".$endDate);
$allKs = array(1, 2, 3, 4);
for ($i = 1; $i <= 15; $i++) {
if (in_array($normativeRow['summary_award_type_'.$i], $allKs)) {
if ($normativeRow['summary_award_end_date_'.$i]) {
$currEndTs = strtotime($normativeRow['summary_award_end_date_'.$i]);
if ($currEndTs) {
$end = $currEndTs;
}
}
}
}
if ($end > $today) {
return array("On Internal K", date("Y-m-d", $end));
}
}
return array("Not Converted", null);
}
function getNextRecord($record) {
global $token, $server;
$records = Download::recordIds($token, $server);
$i = 0;
foreach ($records as $rec) {
if ($rec == $record) {
if ($i + 1 < count($records)) {
return $records[$i + 1];
} else {
return $records[0];
}
}
$i++;
}
}
function decodeCitations($citationStr) {
$citationAry = array();
if ($citationStr) {
$citationAry = json_decode($citationStr, true);
}
return $citationAry;
}
function saveSetting($setting, $value) {
global $module;
$module->setProjectSetting($setting, $value);
}
function getSetting($setting) {
global $module;
return $module->getProjectSetting($setting);
}
function getSurveys() {
$emailSurveys = getSetting(getSurveySettingName());
if ($emailSurveys && !empty($emailSurveys)) {
return $emailSurveys;
} else {
$default = array(
"Initial Survey" => "check_date",
"Follow-Up Survey(s)" => "followup_date",
);
$json = json_encode($default);
saveEmailSetting(getSurveySettingName(), $default);
return $default;
}
}
function getSurveyTypes() {
return getSurveys();
}
function getAllEmailSettings() {
return getSurveySettings();
}
function getSurveySettings() {
return getAllSettings();
}
function saveEmailSetting($setting, $value) {
return saveSetting($setting, $value);
}
function getEmailSetting($setting) {
return getSetting($setting);
}
function dateSort(&$data) {
$newData = array();
foreach ($data as $key => $date) {
$newData[$key] = strtotime($date);
}
arsort($newData);
$returnData = array();
foreach ($newData as $key => $ts) {
$returnData[$key] = $data[$key];
}
return $returnData;
}
function getSurveySettingName() {
return "surveys";
}
function getAllSettings() {
global $module;
$data = $module->getProjectSetting(CareerDev::getGeneralSettingName());
if (is_array($data)) {
$isDate = TRUE;
foreach ($data as $key => $value) {
if (!preg_match("/^\d\d\d\d-\d+-\d+$/", $value)) {
$isDate = FALSE;
break;
}
}
if ($isDate) {
dateSort($data);
}
return $data;
}
return array();
}
function convertTo1DArray($ary) {
$ary2 = array();
foreach ($ary as $i => $id) {
array_push($ary2, $id);
}
return $ary2;
}
function indexREDCapData($redcapData) {
return REDCapManagement::indexREDCapData($redcapData);
}
function getIndexedRedcapData($token, $server, $fields, $cohort = "", $metadata = array()) {
if ($token && $server && $fields && !empty($fields)) {
if ($cohort) {
$records = Download::cohortRecordIds($token, $server, Application::getModule(), $cohort);
} else {
$records = Download::recordIds($token, $server);
}
$redcapData = Download::fieldsForRecords($token, $server, $fields, $records);
return indexREDCapData($redcapData);
}
return array();
}
function getCohortSelect($token, $server, $pid) {
$page = Sanitizer::sanitize($_GET['page'] ?? "");
$prefix = Sanitizer::sanitize($_GET['prefix'] ?? "");
$html = "<select onchange='var base = \"?page=".urlencode($page)."&prefix=".urlencode($prefix)."&pid=$pid\"; if ($(this).val()) { window.location.href = base+\"&cohort=\" + $(this).val(); } else { window.location.href = base; }'>\n";
$cohorts = new Cohorts($token, $server, CareerDev::getModule());
$cohortTitles = $cohorts->getCohortTitles();
$html .= "<option value=''>---ALL---</option>\n";
foreach ($cohortTitles as $title) {
$html .= "<option value='$title'";
if ($title == $_GET['cohort']) {
$html .= " selected";
}
$html .= ">$title</option>\n";
}
$html .= "</select>\n";
return $html;
}
function getCohortHeaderHTML() {
$html = "";
$html .= "<div class='subnav'>\n";
$html .= "<a class='yellow' href='".CareerDev::link("cohorts/addCohort.php")."'>Add a New Cohort</a>";
$html .= "<a class='yellow' href='".CareerDev::link("cohorts/viewCohorts.php")."'>View Existing Cohorts</a>";
$html .= "<a class='purple' href='".CareerDev::link("cohorts/manageCohorts.php")."'>Manage Cohorts</a>";
$html .= "<a class='purple' href='".CareerDev::link("cohorts/exportCohort.php")."'>Export a Cohort</a>";
$html .= "<a class='green' href='".CareerDev::link("cohorts/profile.php")."'>Cohort Profiles</a>";
$html .= "<a class='green' href='".CareerDev::link("cohorts/selectCohort.php")."'>View Cohort Metrics</a>";
# this CSS gives dropdowns enough space to stay above the footer
# I put it here so that it'd only apply to cohorts, not other pages, which seem not to have this problem
$html .= "<style>
#ui-id-1 { padding-bottom: 75px; }
.ui-dialog #ui-id-1 { padding-bottom: 0; }
</style>";
$html .= "</div>\n";
return $html;
}
function makeHTMLId($id) {
return REDCapManagement::makeHTMLId($id);
}
function makeSafe($htmlStr) {
$htmlStr = REDCapManagement::stripHTML($htmlStr);
$htmlStr = REDCapManagement::sanitize($htmlStr);
return $htmlStr;
}
function changeTextColorOfLink($str, $color) {
return Links::changeTextColorOfLink($str, $color);
}
function isAssoc($ary) {
if (empty($ary)) {
return FALSE;
}
return array_keys($ary) !== range(0, count($ary) - 1);
}
function avg($ary) {
return array_sum($ary) / count($ary);
}
function quartile($ary, $quartile) {
if (!is_int($quartile)) {
return FALSE;
}
if (($quartile < 0) || ($quartile > 4)) {
return FALSE;
}
if (isAssoc($ary)) {
return FALSE;
}
sort($ary);
$size = count($ary);
switch($quartile) {
case 0:
return $ary[0];
case 1:
$ary2 = array();
for ($i = 0; $i < $size / 2; $i++) {
array_push($ary2, $ary[$i]);
}
return getMedian($ary2);
case 2:
return getMedian($ary);
case 3:
$ary2 = array();
for ($i = (int) ceil($size / 2); $i < $size; $i++) {
array_push($ary2, $ary[$i]);
}
return getMedian($ary2);
case 4:
return $ary[$size - 1];
}
}
function getMedian($ary) {
sort($ary);
$size = count($ary);
if ($size % 2 == 0) {
$idx = (int) ($size / 2);
return ($ary[$idx - 1] + $ary[$idx]) / 2;
} else {
$idx = (int) (($size - 1) / 2);
return $ary[$idx];
}
}
function removeBrandLogo() {
global $module;
$module->removeProjectSetting(getBrandLogoName());
}
function saveBrandLogo($base64) {
global $module;
$module->setProjectSetting(getBrandLogoName(), $base64);
}
function getFieldForCurrentEmailSetting() {
return EmailManager::getFieldForCurrentEmailSetting();
}
function isEmailAddress($str) {
if (preg_match("/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/", $str)) {
return TRUE;
}
return FALSE;
}
function getBrandLogoName($currModule = NULL) {
if ($currModule) {
return $currModule->getBrandLogoName();
}
global $module;
return $module->getBrandLogoName();
}
function getBrandLogo($currModule = NULL) {
if ($currModule) {
return $currModule->getBrandLogo();
}
global $module;
return $module->getBrandLogo();
}
function makeHeaders($module = NULL, $token = NULL, $server = NULL, $pid = NULL, $tokenName = NULL) {
if (!$module) { global $module; }
if (!$token) { global $token; }
if (!$server) { global $server; }
if (!$pid) { global $pid; }
if (!$tokenName) { global $tokenName; }
if ($module) {
return $module->makeHeaders($token, $server, $pid, $tokenName);
}
return "";
}
function isREDCap() {
return CareerDev::isREDCap();
}
function isFAQ() {
return CareerDev::isFAQ();
}
# eligibility determined by whether on K award (3 years for internal Ks; 5 years for external Ks)
# returns false if ineligible
# else returns index (1-15) of summary award
function findEligibleAward($row) {
if (isset($_GET['test'])) {
echo "findEligibleAward with ".$row['record_id']."<br>";
}
if ($row['redcap_repeat_instance'] !== "") {
return false;
}
$rs = array(5, 6);
$hasR = false;
for ($i = 1; $i <= Grants::$MAX_GRANTS; $i++) {
if (in_array($row['summary_award_type_'.$i], $rs)) {
$hasR = true;
}
}
if ($hasR) {
if (isset($_GET['test'])) {
echo $row['record_id']." has R<br>";
}
return false;
}
$extKs = array(3, 4);
for ($i = 1; $i <= Grants::$MAX_GRANTS; $i++) {
if (in_array($row['summary_award_type_'.$i], $extKs)) {
$diff = Grants::datediff(date("Y-m-d"), $row['summary_award_date_'.$i], "y");
$intendedYearSpan = Application::getIndividualKLength();
if ($row['summary_award_end_date_'.$i]) {
$intendedYearSpan = Grants::datediff($row['summary_award_end_date_'.$i], $row['summary_award_date_'.$i], "y");
}
if (isset($_GET['test'])) {
echo $row['record_id']." comparing $diff and $intendedYearSpan for $i<br>";
}
if ($diff <= $intendedYearSpan) {
return $i;
}
}
}
$intKs = array(1, 2);
for ($i = 1; $i <= Grants::$MAX_GRANTS; $i++) {
if (in_array($row['summary_award_type_'.$i], $intKs)) {
$diff = Grants::datediff(date("Y-m-d"), $row['summary_award_date_'.$i], "y");
$intendedYearSpan = 0;
if ($row['summary_award_type_'.$i] == 1) {
$intendedYearSpan = Application::getInternalKLength();
} else if ($row['summary_award_type_'.$i] == 2) {
$intendedYearSpan = Application::getK12KL2Length();
}
if ($row['summary_award_end_date_'.$i]) {
$intendedYearSpan = Grants::datediff($row['summary_award_end_date_'.$i], $row['summary_award_date_'.$i], "y");
}
if (isset($_GET['test'])) {
echo $row['record_id']." comparing $diff and $intendedYearSpan for $i<br>";
}
if ($diff <= $intendedYearSpan) {
return $i;
}
}
}
if (isset($_GET['test'])) {
echo $row['record_id']." returning FALSE<br>";
}
return false;
}
# $data is JSON or array structure from JSON in REDCap format
# returns a set of REDCap data sorted by last name
# if a record does not have a name, it is appended at the end
function alphabetizeREDCapData($data) {
if (!is_array($data)) {
$data = json_decode($data, true);
}
if ($data) {
$names = array();
$excluded = array();
if (!isAssoc($data)) {
foreach ($data as $row) {
if ($row['identifier_last_name'] && $row['identifier_first_name']) {
$names[$row['record_id']] = $row['identifier_last_name'].", ".$row['identifier_first_name'];
}
}
foreach ($data as $row) {
if (!in_array($row['record_id'], $excluded) && !isset($names[$row['record_id']])) {
$excluded[] = $row['record_id'];
}
}
} else {
foreach ($data as $recordId => $rows) {
foreach ($rows as $row) {
if ($row['identifier_last_name'] && $row['identifier_first_name']) {
$names[$row['record_id']] = $row['identifier_last_name'].", ".$row['identifier_first_name'];
}
}
}
foreach ($data as $recordId => $rows) {
foreach ($rows as $row) {
if (!in_array($row['record_id'], $excluded) && !isset($names[$row['record_id']])) {
$excluded[] = $row['record_id'];
}
}
}
}
asort($names);
$returnData = array();
foreach ($names as $recordId => $name) {
if (!isAssoc($data)) {
foreach ($data as $row) {
if ($recordId == $row['record_id']) {
$returnData[] = $row;
}
}
} else {
foreach ($data as $recordIdData => $rows) {
if ($recordId == $recordIdData) {
$returnData[$recordId] = $rows;
}
}
}
}
foreach ($excluded as $recordId) {
if (!isAssoc($data)) {
foreach ($data as $row) {