generated from susom/redcap-em-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHTNapi.php
1928 lines (1611 loc) · 77.1 KB
/
HTNapi.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 Stanford\HTNapi;
require_once( "emLoggerTrait.php" );
require_once( 'HTNdashboard.php' );
require_once( 'HTNtree.php' );
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
class HTNapi extends \ExternalModules\AbstractExternalModule {
use emLoggerTrait;
private $dashboard
,$tree;
public $enabledProjects;
public function __construct() {
parent::__construct();
// Other code to run when object is instantiated
}
//Load the pertinent EM stuff, as well as the broken off Classes for Dashboard and Tree
public function loadEM(){
$this->getEnabledProjects();
$this->dashboard = new \Stanford\HTNapi\HTNdashboard($this);
$this->tree = new \Stanford\HTNapi\HTNtree($this);
// what else? API stuff?
session_start();
}
//DEFAULT TREES
public function getDefaultTrees($provider_id=0){
$this->loadEM();
return $this->tree->getDefaultTrees($provider_id);
}
public function getDefaultMeds(){
$this->loadEM();
return $this->tree->getDefaultMeds();
}
public function getDrugList(){
$this->loadEM();
return $this->tree->getDrugList();
}
//Get All Patients
public function dashBoardInterface($provider_id, $super_delegate=null, $dag_admin=null){
$this->loadEM();
// $this->emDebug("super delegate", $_SESSION["logged_in_user"]['super_delegate']);
$intf = $this->dashboard->getAllPatients($provider_id, $super_delegate, $dag_admin);
$intf["ptree"] = $this->treeLogic($provider_id);
$intf["super_delegate"] = !empty($_SESSION["logged_in_user"]['super_delegate']) ? $this->dashboard->getAllProviders() : array();
return $intf;
}
//Get All Patients
public function getPatientDetails($record_id){
$this->loadEM();
return $this->dashboard->getPatientDetails($record_id);
}
//Login Provider
public function loginProvider($login_email, $login_pw, $already_hashed=false){
$this->loadEM();
return $this->dashboard->loginProvider($login_email, $login_pw, $already_hashed);
}
//REgister PRovider
public function registerProvider($post){
$this->loadEM();
return $this->dashboard->registerProvider($post);
}
//EDIT PRovider
public function editProvider($post){
$this->loadEM();
$this->dashboard->editProvider($post);
}
public function getProvider($provider_id){
$this->loadEM();
return $this->dashboard->getProvider($provider_id);
}
public function sendResetPassword($login_email){
$this->loadEM();
return $this->dashboard->sendResetPassword($login_email);
}
public function updateProviderPassword($record_id, $login_email, $rawpw){
$this->loadEM();
return $this->dashboard->updateProviderPassword($record_id, $login_email, $rawpw);
}
public function flagPatientForDeletion($patient_record_id){
$this->loadEM();
return $this->dashboard->flagPatientForDeletion($patient_record_id);
}
//EDIT LAB READING
public function updateLabReading($record_id, $lab, $reading){
$this->loadEM();
// update the shortcut data in patient baseline
$next_instance_id = $this->getNextInstanceId($record_id, "labs_log", "lab_ts");
$data_log = array(
"record_id" => $record_id,
"redcap_repeat_instance" => $next_instance_id,
"redcap_repeat_instrument" => "labs_log",
"lab_name" => $lab,
"lab_value" => $reading,
"lab_token" => "manual",
"lab_ts" => Date("Y-m-d")
);
$r = \REDCap::saveData($this->enabledProjects["patients"]["pid"], 'json', json_encode(array($data_log)) );
$this->emDebug("update lab reading", $r , $data_log);
return array("errors" => $r["errors"], "data"=> $data_log);
}
/**
* Load all enabled projects with this EM
*/
public function getEnabledProjects() {
$enabledProjects = array();
$projects = \ExternalModules\ExternalModules::getEnabledProjects($this->PREFIX);
while($project = db_fetch_assoc($projects)){
$pid = $project['project_id'];
$name = $project['name'];
$url = APP_PATH_WEBROOT . 'ProjectSetup/index.php?pid=' . $project['project_id'];
$mode = $this->getProjectSetting("em-mode", $pid);
$enabledProjects[$mode] = array(
'pid' => $pid,
'name' => $name,
'url' => $url,
'mode' => $mode
);
}
$this->enabledProjects = $enabledProjects;
// $this->emDebug($this->enabledProjects, "Enabled Projects");
}
//show enabled projects
public function showEnabledProjects(){
return $this->enabledProjects;
}
public function sendPatientConsent($patient_id, $consent_url , $consent_email){
$this->loadEM();
return $this->dashboard->sendPatientConsent($patient_id, $consent_url , $consent_email);
}
public function getProviderbyEmail($provider_email){
$this->loadEM();
return $this->dashboard->getProviderbyEmail($provider_email);
}
public function newPatientConsent($provider_id=null){
$this->loadEM();
return $this->dashboard->newPatientConsent($provider_id);
}
public function addPatient($post){
$this->loadEM();
return $this->dashboard->addPatient($post);
}
public function treeLogic($provider_id){
$this->loadEM();
return $this->tree->treeLogic($provider_id);
}
public function saveTemplate($provider_id, $post){
$this->loadEM();
return $this->tree->saveTemplate($provider_id, $post);
}
public function acceptRecommendation($patient_details){
$this->loadEM();
$next_instance_id = $this->getNextInstanceId($patient_details["record_id"], "treatment_status_log", "ptree_log_ts");
// ONLY UPDATE THIS WHEN IT RXCHANGE ACTUALLY ACCEPTED
// add log to treattment_status_log
$data_log = array(
"record_id" => $patient_details["record_id"],
"redcap_repeat_instance" => $next_instance_id,
"redcap_repeat_instrument" => "treatment_status_log",
"ptree_log_prev_step" => $patient_details["patient_treatment_status"],
"ptree_log_current_step" => $patient_details["patient_rec_tree_step"],
"ptree_current_meds" => $patient_details["current_drugs"],
"ptree_log_comment" => $patient_details["provider_comment"],
"ptree_log_ts" => Date("Y-m-d H:i:s")
);
$r = \REDCap::saveData($this->enabledProjects["patients"]["pid"], 'json', json_encode(array($data_log)) );
// $this->emDebug("Saving the treatment step log?", $data_log);
// update the shortcut data in patient baseline
$data = array(
"record_id" => $patient_details["record_id"],
"patient_rec_tree_step" => '',
"patient_treatment_status" => $patient_details["patient_rec_tree_step"],
"filter" => '',
"last_update_ts" => Date("Y-m-d H:i:s")
);
// TODO THIS timestamp IS WHEN THE LAST RECOMMENDATION WAS MADE or Accepted, DONT MAKE ANOTHER ONE FOR 2 WEEKS at LEAST
$r = \REDCap::saveData($this->enabledProjects["patients"]["pid"], 'json', json_encode(array($data)), "overwrite" );
// $this->emDebug("Accepting rx change", $data);
$this->updateRecLog($patient_details["record_id"], $patient_details["patient_rec_tree_step"]);
return array("rec saved");
}
public function declineRecommendation($patient_details){
$this->loadEM();
// update the shortcut data in patient baseline
$data = array(
"record_id" => $patient_details["record_id"],
"patient_rec_tree_step" => '',
"filter" => ''
);
$r = \REDCap::saveData($this->enabledProjects["patients"]["pid"], 'json', json_encode(array($data)), "overwrite" );
$this->updateRecLog($patient_details["record_id"], $step_id, true);
return array("rec declined");
}
public function updateRecLog($record_id, $step_id , $reject=false){
$this->emDebug("updateing a recLog", $record_id, $step_id, $reject);
if(!empty($step_id)){
$fields = array("record_id", "rec_step");
$filter = "[rec_step] = $step_id and [record_id] = $record_id";
$params = array(
'return_format' => 'json',
'fields' => $fields,
'filterLogic' => $filter
);
$q = \REDCap::getData($params);
$rows = json_decode($q,1);
foreach($rows as $row){
if($row["redcap_repeat_instrument"] == "recommendations_log"){
$instance_id = $row["redcap_repeat_instance"];
$temp = array(
"redcap_repeat_instance" => $instance_id,
"redcap_repeat_instrument" => "recommendations_log",
"record_id" => $record_id,
"rec_accepted" => ($reject ? "0" : "1"),
);
$data[] = $temp;
$r = \REDCap::saveData($this->enabledProjects["patients"]["pid"], 'json', json_encode($data) );
// $this->emDebug("accept/reject recommendtation", $data, $r);
}
}
}
}
public function getPatientBaselineFields(){
$this->loadEM();
$script_fieldnames = \REDCap::getFieldNames("patient_baseline");
return $script_fieldnames;
}
public function sendToPharmacy($patient){
//TODO, FIGURE OUT PHARMACY API
$this->emDebug("SEND TO PHARMACY FOR patient, NONE FOR NOW, IRB ISSUES");
return;
}
public function verifyAccount($verification_email,$verification_token){
$this->loadEM();
return $this->dashboard->verifyAccount($verification_email,$verification_token);
}
public function makeEmailVerifyToken(){
return $this->generateRandomString(10,false,true);
}
// Creates random alphanumeric string
public function generateRandomString($length=25, $addNonAlphaChars=false, $onlyHandEnterableChars=false, $alphaCharsOnly=false) {
// Use character list that is human enterable by hand or for regular hashes (i.e. for URLs)
if ($onlyHandEnterableChars) {
$characters = '34789ACDEFHJKLMNPRTWXY'; // Potential characters to use (omitting 150QOIS2Z6GVU)
} else {
$characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789'; // Potential characters to use
if ($addNonAlphaChars) $characters .= '~.$#@!%^&*-';
}
// If returning only letter, then remove all non-alphas from $characters
if ($alphaCharsOnly) {
$characters = preg_replace("/[^a-zA-Z]/", "", $characters);
}
// Build string
$strlen_characters = strlen($characters);
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, $strlen_characters-1)];
}
// If hash matches a number in Scientific Notation, then fetch another one
// (because this could cause issues if opened in certain software - e.g. Excel)
if (preg_match('/^\d+E\d/', $string)) {
return generateRandomString($length, $addNonAlphaChars, $onlyHandEnterableChars);
}
return $string;
}
/*
BELOW HERE IS ALL THE OMRON AUTHORIZATION WORK FLOW STUFF
*/
//get oauthURL to presetn to Patient
public function emailOmronAuthRequest($patient){
$result = false;
if( !empty($patient) && isset($patient["record_id"]) && isset($patient["patient_email"]) ){
$auth_link = $this->getOAUTHurl($patient["record_id"]);
$msg_arr = array();
$msg_arr[] = "<p>Dear " . $patient["patient_fname"] . "</p>";
$msg_arr[] = "<p>In order to participate in this study, we need access to your Blood Pressure Cuff data.</p>";
$msg_arr[] = "<p>If you have not downloaded and set up your <b>Omron Heart Advisor</b> App yet, Please download them first.</p>";
$msg_arr[] = "<p><a href='https://apps.apple.com/us/app/omron-heartadvisor/id1444973178' target='_blank'>Apple App Store</a> or <a href='https://play.google.com/store/apps/details?id=com.omronhealthcare.heartadvisor&hl=en_US&gl=US' target='_blank'>Google Play Store</a></p>";
$msg_arr[] = "<p>Please click this <a href='".$this->getURL("pages/oauth.php", true, true)."&state=".$patient["record_id"]."'>link</a> to start the process of authorizing us to retrieve your data from Omron.<p>";
$msg_arr[] = "<p>Thank You! <br> Stanford HypertensionStudy Team</p>";
$message = implode("\r\n", $msg_arr);
$to = $patient["patient_email"];
$from = "no-reply@stanford.edu";
$subject = "HTN Study Needs Your Authorization";
$fromName = "Stanford Hypertension Study Team";
$result = \REDCap::email($to, $from, $subject, $message);
if($result){
$data = array(
"record_id" => $patient["record_id"],
"omron_auth_request_ts" => date("Y-m-d H:i:s")
);
$r = \REDCap::saveData("json", json_encode(array($data)) );
}
// $this->emDebug("emailing patient", $result,$this->enabledProjects["patients"]["pid"], $r);
}
return $result;
}
public function dailySurveyCheck(){
$this->loadEM();
//FIRST GET ALL THE PEOPLE
//THEN DETERMINE WHAT DAY THEYVE JOINED
//IF MULTIPLE OF 7 THEN SEND SURVEY INSTANCE
$filter = "";
$fields = array("record_id","patient_add_ts");
$params = array(
'project_id' => $this->enabledProjects["patients"]["pid"],
'return_format' => 'json',
'fields' => $fields,
'filterLogic' => $filter
);
$q = \REDCap::getData($params);
$records = json_decode($q, true);
foreach($records as $patient){
$record_id = $patient["record_id"];
$patient_added = $patient["patient_add_ts"];
$dateOne = new \DateTime();
$dateTwo = new \DateTime($patient_added);
$days_since = $dateOne->diff($dateTwo)->format("%a");
$weekly_anni = $days_since % 7;
if($weekly_anni === 0){
$this->emDebug("Patient # $record_id 'weekly' anniversery" );
//if patient has weekly anniversary lets mark it.
$filter = "";
$fields = array("record_id","message_ts");
$params = array(
'project_id' => $this->enabledProjects["patients"]["pid"],
'return_format' => 'json',
'fields' => $fields,
'records' => $record_id,
'filterLogic' => $filter
);
$q = \REDCap::getData($params);
$records = json_decode($q, true);
$most_recent_message = array_pop($records);
$current_instance_id = 0;
if(!empty($most_recent_message["message_ts"])){
$current_instance_id= $most_recent_message["redcap_repeat_instance"];
$test_date = new \DateTime($most_recent_message["message_ts"]);
$most_recent_date = $dateOne->diff($test_date)->format("%a");
if($most_recent_date < 7){
$this->emDebug("This patient already got this weeks survey $most_recent_date days ago");
//they had a survey within the last week, no need
continue;
}
}
$next_instance_id = $current_instance_id +1;
//create survey link if it gets past here
$survey_link = \REDCap::getSurveyLink($record_id, "communications", "", $next_instance_id);
if($survey_link){
$data = array(
"record_id" => $record_id,
"weekly_patient_survey" => $survey_link
);
$r = \REDCap::saveData($this->enabledProjects["patients"]["pid"], "json", json_encode(array($data)));
if(empty($r["errors"])){
echo "weekly survey queued for patient # $record_id <br>";
$this->emDebug("only patient #$record_id needs a weekly survey", $survey_link, $r);
}
}
}
}
// $msg_arr = array();
// $msg_arr[] = "<p>Dear " . $patient["patient_fname"] . "</p>";
// $msg_arr[] = "<p>Please take a moment to answer your <a href='$survey_link' target='_blank'>weekly survey</a> for the Digital Hypertension Management System.</p>";
// $msg_arr[] = "<p>Thank You! <br> Stanford HypertensionStudy Team</p>";
// $message = implode("\r\n", $msg_arr);
// $to = $patient["patient_email"];
// $from = "no-reply@stanford.edu";
// $subject = "Weekly Stanford Digital Hypertension Management System Survey";
// $fromName = "Stanford Hypertension Study Team";
// $this->emDebug("emailing patient", $result,$this->enabledProjects["patients"]["pid"], $r);
return ;
}
public function dailySurveyClear(){
$this->loadEM();
$filter = "[weekly_patient_survey] <> ''";
$fields = array("record_id","patient_add_ts");
$params = array(
'project_id' => $this->enabledProjects["patients"]["pid"],
'return_format' => 'json',
'fields' => $fields,
'filterLogic' => $filter
);
$q = \REDCap::getData($params);
$records = json_decode($q, true);
foreach($records as $patient){
$record_id = $patient["record_id"];
$data = array(
"record_id" => $record_id,
"weekly_patient_survey" => ""
);
$r = \REDCap::saveData($this->enabledProjects["patients"]["pid"], "json", json_encode(array($data)), "overwrite");
if(empty($r["errors"])){
echo "removing weekly survey for patient #$record_id";
}
}
}
//get oauthURL to presetn to Patient
public function getOAUTHurl($record_id = null){
$oauth_url = null;
if($record_id){
$client_id = $this->getProjectSetting("omron-client-id");
$oauth_url = $this->getProjectSetting("omron-auth-url");
$oauth_postback = $this->getProjectSetting("omron-postback");
$oauth_scope = $this->getProjectSetting("omron-auth-scope");
$oauth_params = array(
"client_id" => $client_id,
"response_type" => "code",
"scope" => $oauth_scope,
"redirect_uri" => $oauth_postback,
"state" => $record_id
);
$oauth_params["state"] = $record_id;
$oauth_url .= "/connect/authorize?". http_build_query($oauth_params);
}
return $oauth_url;
}
// gets or refresh omron access token
public function getOrRefreshOmronAccessToken($token, $refresh = false) {
$client_id = $this->getProjectSetting("omron-client-id");
$client_secret = $this->getProjectSetting("omron-client-secret");
$redirect_uri = $this->getProjectSetting("omron-postback"); // Ensure this is correct and URL-encoded
$omron_url = $this->getProjectSetting("omron-api-url");
$oauth_scope = $this->getProjectSetting("omron-auth-scope");
// Token endpoint
$token_url = $omron_url . "/connect/token";
// Data to be sent in the POST request
$data = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri
);
if ($refresh) {
$data['grant_type'] = 'refresh_token';
$data['refresh_token'] = $token;
} else {
$data['grant_type'] = 'authorization_code';
$data['code'] = $token;
}
// cURL initiation and setting options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the cURL session and close it
$result = curl_exec($ch);
if (curl_errno($ch)) {
$this->emDebug("Curl error: " . curl_error($ch));
}
curl_close($ch);
// Decode JSON response
$response = json_decode($result, true);
// Log the response for debugging purposes
// $this->emDebug("getOrRefreshOmronAccessToken", $api_url, $token_url, $data, array_keys($response));
return $response;
}
//returns array, expects JWT token
public function decodeJWT($token){
return json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $token)[1]))), true);
}
// gets or refresh omron access token
public function getOmronAPIData($omron_access_token, $omron_token_type, $hook_timestamp=null, $limit=null, $type="bloodpressure", $includeHourlyActivity=false, $sortOrder="asc"){
//There are two typical use cases when you will use the Omron API to retrieve data for a user:
// To retrieve historical data at the time the user authorizes your application
// To retrieve data whenever your application receives notification that an upload has occurred
$omron_url = $this->getProjectSetting("omron-api-url");
$data = array(
"type" => $type,
"sortOrder" => $sortOrder
);
// OPTIONAL
if($limit){
$data["limit"] = $limit;
}
if($includeHourlyActivity){
$data["includeHourlyActivity"] = $includeHourlyActivity;
}
if(!$hook_timestamp){
//supposed to default to "from the beginning" with this field empty, but it appears to be required?
$hook_timestamp = date("Y")."-".date("m")."-01";
}
$data["since"] = $hook_timestamp;
$api_url = $omron_url . "/api/measurement";
$ch = curl_init($api_url);
$this->emDebug("$api_url");
$header_data = array();
array_push($header_data, "Authorization: $omron_token_type $omron_access_token");
array_push($header_data, 'Content-Type: application/x-www-form-urlencoded');
array_push($header_data, 'Content-Length: ' . strlen(http_build_query($data)));
array_push($header_data, 'Cache-Control: no-cache' );
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 105200);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
$info = curl_getinfo($ch);
$result = curl_exec($ch);
$this->emDebug("curl call", $result);
curl_close($ch);
return $result;
}
// get Omron Token Details by OmronClientId
public function getTokenDetails($omron_client_id){
$filter = "[omron_client_id] = '$omron_client_id'";
$fields = array("record_id","omron_access_token","omron_token_type");
$params = array(
'project_id' => $this->enabledProjects["patients"]["pid"],
'return_format' => 'json',
'fields' => $fields,
'filterLogic' => $filter
);
$q = \REDCap::getData($params);
$records = json_decode($q, true);
if(empty($records)){
$this->emDebug("Omron getTokenDetail() : Could not find Patient with omron_client_id = $omron_client_id", $params);
return false;
}
$this->emDebug("found token details");
return current($records);
}
// get data via API and recurse if pagination
public function recurseSaveOmronApiData($omron_client_id, $since_ts = null, $token_details = array()) {
$this->loadEM();
$first_pass = false;
if (empty($token_details)) {
$first_pass = true;
$token_details = $this->getTokenDetails($omron_client_id);
if (!$token_details) {
return false;
}
}
$record_id = $token_details["record_id"];
$omron_access_token = $token_details["omron_access_token"];
$omron_token_type = $token_details["omron_token_type"];
if (!empty($since_ts) || $first_pass) {
$adjusted_since_ts = date("Y-m-d", strtotime($since_ts .' -1 day'));
$result = $this->getOmronAPIData($omron_access_token, $omron_token_type, $adjusted_since_ts);
$api_data = json_decode($result, true);
// Check status
if ($api_data["status"] !== 0) {
$this->emDebug("Error fetching data for Omron ID $omron_client_id: " . $api_data["reason"]);
return [
'status' => false,
'reason' => $api_data["reason"] ?? 'Unknown error',
'errorCode' => $api_data["errorCode"] ?? null,
];
}
// Process API data if status is successful
$truncated = $api_data["result"]["truncated"];
$bp_readings = $api_data["result"]["bloodPressure"];
$bp_instance_data = $this->getBPInstanceData($record_id);
$next_instance_id = $bp_instance_data["next_instance_id"];
$used_bp_id = $bp_instance_data["used_bp_id"];
$data = [];
foreach ($bp_readings as $reading) {
$omron_bp_id = $reading["id"];
if (in_array($omron_bp_id, $used_bp_id)) continue;
$data[] = [
"redcap_repeat_instance" => $next_instance_id++,
"redcap_repeat_instrument" => "bp_readings_log",
"record_id" => $record_id,
"omron_bp_id" => $omron_bp_id,
"bp_reading_ts" => date("Y-m-d H:i:s", strtotime($reading["dateTime"])),
"bp_reading_local_ts" => date("Y-m-d H:i:s", strtotime($reading["dateTimeLocal"])),
"bp_systolic" => $reading["systolic"],
"bp_diastolic" => $reading["diastolic"],
"bp_units" => $reading["bloodPressureUnits"],
"bp_pulse" => $reading["pulse"],
"bp_pulse_units" => $reading["pulseUnits"],
"bp_device_type" => $reading["deviceType"],
];
}
$save_result = \REDCap::saveData($this->enabledProjects["patients"]["pid"], 'json', json_encode($data));
if (empty($save_result["errors"])) {
$this->emDebug("Saved Omron BP readings for record_id $record_id");
// Get the most recent reading if data was saved successfully
$most_recent_reading = end($bp_readings);
// Handle pagination if necessary
if ($truncated) {
return $this->recurseSaveOmronApiData($omron_client_id, $most_recent_reading["dateTime"], $token_details);
} else {
$this->evaluateOmronBPavg($record_id);
return [
'status' => $most_recent_reading,
];
}
} else {
$this->emDebug("Error saving data for record_id $record_id", $save_result["errors"]);
return ['status' => false, 'reason' => 'Error saving data', 'details' => $save_result["errors"]];
}
}
}
//DELETE AFTER VERIfY
public function checkBPvsThreshold_old($bp_data, $target_threshold, $control_condition = 0.6, $external_avg = null) {
// Filter for data within the last 2 weeks
$two_weeks_ago = strtotime('-2 weeks');
$recent_bp_data = array_filter($bp_data, function($bp) use ($two_weeks_ago) {
return strtotime($bp["bp_reading_ts"]) >= $two_weeks_ago;
});
// If there are at least 4 recent data points, use those; otherwise, use all data
if (count($recent_bp_data) >= 4) {
$bp_data = $recent_bp_data;
}
// Use external average if provided
if ($external_avg !== null) {
$mean_of_data = $external_avg;
$is_above = $mean_of_data > $target_threshold ? true : false;
return $is_above ? $mean_of_data : false;
}
// Split data into dates + AM/PM
$ampm_datapoints = array();
$this->emDebug("last two weeks or alltime?", $bp_data);
foreach ($bp_data as $bp) {
$sys_ts = $bp["bp_reading_ts"];
$sys_reading = $bp["bp_systolic"];
$am_pm = date("a", strtotime($sys_ts));
$daykey = date("ymd", strtotime($sys_ts));
if (!array_key_exists($daykey, $ampm_datapoints)) {
$ampm_datapoints[$daykey] = array("am" => [], "pm" => []);
}
array_push($ampm_datapoints[$daykey][$am_pm], $sys_reading);
}
// Average each day's AM/PM splits (max 2 data points per day)
$total_datapoints = array();
$above_thresh = array();
foreach ($ampm_datapoints as $daydata) {
if (!empty($daydata["am"])) {
$am_data = array_sum($daydata["am"]) / count($daydata["am"]);
$above = $am_data > $target_threshold ? 1 : 0;
array_push($total_datapoints, $am_data);
array_push($above_thresh, $above);
}
if (!empty($daydata["pm"])) {
$pm_data = array_sum($daydata["pm"]) / count($daydata["pm"]);
$above = $pm_data > $target_threshold ? 1 : 0;
array_push($total_datapoints, $pm_data);
array_push($above_thresh, $above);
}
}
$this->emDebug("total datapoints and above_thresh", $total_datapoints, $above_thresh);
// Calculate control condition % and mean of data
$thresh_check = count($above_thresh) * $control_condition;
$total_above = array_sum($above_thresh);
$mean_of_data = $total_datapoints ? round(array_sum($total_datapoints) / count($total_datapoints)) : 0;
$this->emDebug("mean data, threshcheck, ttoal", $mean_of_data, $thresh_check, $total_above);
// Return mean if above threshold; otherwise, return false
return $total_above > $thresh_check && count($above_thresh) >= 4 ? $mean_of_data : false;
}
public function checkBPvsThreshold($bp_data, $target_threshold, $control_condition = 0.6, $external_avg = null) {
// Filter BP data to the last 2 weeks
$two_weeks_ago = strtotime('-2 weeks');
$recent_bp_data = array_filter($bp_data, fn($bp) => strtotime($bp["bp_reading_ts"]) >= $two_weeks_ago);
// Use recent data if there are at least 4 records, otherwise use all data
$bp_data = count($recent_bp_data) >= 4 ? $recent_bp_data : $bp_data;
// Use external average if provided and determine if it's above the threshold
if ($external_avg !== null) {
return $external_avg > $target_threshold ? $external_avg : false;
}
// Organize data into AM/PM readings for each day
$ampm_data = [];
foreach ($bp_data as $bp) {
$date_key = date("ymd", strtotime($bp["bp_reading_ts"]));
$am_pm_key = date("a", strtotime($bp["bp_reading_ts"]));
$ampm_data[$date_key][$am_pm_key][] = $bp["bp_systolic"];
}
// Calculate daily averages and whether each average is above the threshold
$total_datapoints = [];
$above_threshold_counts = 0;
foreach ($ampm_data as $day_data) {
foreach (['am', 'pm'] as $period) {
if (!empty($day_data[$period])) {
$average = array_sum($day_data[$period]) / count($day_data[$period]);
$total_datapoints[] = $average;
$above_threshold_counts += ($average > $target_threshold) ? 1 : 0;
}
}
}
// Calculate the control threshold and mean
$required_above_count = floor(count($total_datapoints) * $control_condition);
$mean_of_data = !empty($total_datapoints) ? round(array_sum($total_datapoints) / count($total_datapoints)) : 0;
// Return mean if threshold met; otherwise, return false
return $above_threshold_counts >= $required_above_count && count($total_datapoints) >= 4 ? $mean_of_data : false;
}
//DELETE AFTER VERIFY
public function evaluateOmronBPavg_old($record_id, $external_avg = null) {
$this->loadEM();
$this->emDebug("Starting evaluation for record", $record_id);
// Get patient Misc Data data, AND threshold targets
$params = array(
'project_id' => $this->enabledProjects["patients"]["pid"],
'records' => array($record_id),
'return_format' => 'json',
'fields' => array("record_id",
"filter",
"patient_bp_target_systolic",
"patient_bp_target_diastolic",
"patient_bp_target_pulse",
"custom_target_sys_lower",
"custom_target_k_upper",
"custom_target_k_lower",
"custom_target_slowhr",
"custom_target_cr",
"custom_target_na",
"current_treatment_plan_id",
"patient_treatment_status",
"patient_physician_id",
"last_update_ts")
);
$q = \REDCap::getData($params);
$records = json_decode($q, true);
$patient = current($records);
extract($patient, EXTR_PREFIX_ALL, 'pat');
$provider_id = $pat_patient_physician_id;
$current_tree = $pat_current_treatment_plan_id;
$current_step = empty($pat_patient_treatment_status) ? 0 : $pat_patient_treatment_status;
$target_systolic = $pat_patient_bp_target_systolic;
//THESE ARENT NECESSARY FOR NOW
$target_diastolic = $pat_patient_bp_target_diastolic;
$target_pulse = $pat_patient_bp_target_pulse;
$rec_step = $pat_patient_rec_tree_step;
$dash_filter = json_decode($pat_filter, 1);
// Prepare custom targets
$custom_targets = [];
if (!empty($pat_custom_target_sys_lower)) {
$custom_targets["sys_avg_lower"] = $pat_custom_target_sys_lower;
}
if (!empty($pat_custom_target_k_upper)) {
$custom_targets["k_upper"] = $pat_custom_target_k_upper;
}
if (!empty($pat_custom_target_k_lower)) {
$custom_targets["k_lower"] = $pat_custom_target_k_lower;
}
if (!empty($pat_custom_target_cr)) {
$custom_targets["cr_upper"] = $pat_custom_target_cr;
}
if (!empty($pat_custom_target_na)) {
$custom_targets["na_lower"] = $pat_custom_target_na;
}
if (!empty($pat_custom_target_slowhr)) {
$custom_targets["hr_lower"] = $pat_custom_target_slowhr;
}
$this->emDebug("Pull Initial data and current step for Patient record_id $record_id", $patient, $current_step, $custom_targets);
if (!empty($target_systolic)) {
// Get the last 2 weeks' worth of BP data
$filter = "[bp_reading_ts] > '" . date("Y-m-d H:i:s", strtotime('-2 weeks')) . "'";
$filter = "";
$params = array(
'project_id' => $this->enabledProjects["patients"]["pid"],
'records' => array($record_id),
'return_format' => 'json',
'fields' => array("record_id",
"omron_bp_id",
"bp_reading_ts",
"bp_systolic",
"bp_diastolic",
"bp_pulse"),
'filterLogic' => $filter
);
$q = \REDCap::getData($params);
$records = json_decode($q, true);
$pulse_sum = 0;
$pulse_count = 0;
foreach ($records as $record) {
if (!empty($record['bp_pulse'])) {
$pulse_sum += $record['bp_pulse'];
$pulse_count++;
}
}
$mean_bp_pulse = $pulse_count > 0 ? $pulse_sum / $pulse_count : null;
$this->emDebug("Pull last 2 weeks BP Data for Patient record_id $record_id: ", $mean_bp_pulse);
// Fetch recent lab values WITHIN THe last 2 weeks(??)
$filter = "[lab_ts] > '" . date("Y-m-d", strtotime('-2 weeks')) . "'";
$filter = "";
$params = array(
'project_id' => $this->enabledProjects["patients"]["pid"],
'records' => array($record_id),
'return_format' => 'json',
'fields' => array("record_id", "lab_name", "lab_value", "lab_ts"),
'filterLogic' => $filter
);
$q = \REDCap::getData($params);
$labs = json_decode($q, true);
$lab_values = array();
if (!empty($labs)) {
foreach ($labs as $lab) {
$lab_values[$lab["lab_name"]] = $lab["lab_value"];
}
}
$this->emDebug("Pull last 2 weeks lab values?", $lab_values);
$lab_k = isset($lab_values["k"]) ? $lab_values["k"] : null;
$lab_na = isset($lab_values["na"]) ? $lab_values["na"] : null;
$lab_cr = isset($lab_values["cr"]) ? $lab_values["cr"] : null;
// Check for side effects first
$provider_trees = $this->tree->treeLogic($provider_id);
$treelogic = $provider_trees[$current_tree];
$current_tree_step = $treelogic["logicTree"][$current_step];
$this->emDebug("what the heck wheres my tree", $provider_id, $current_step, $current_tree, $current_tree_step);
$this->emDebug("Check sideeffects first", $current_tree_step, $lab_k, $lab_na, $lab_cr, $mean_bp_pulse, $external_avg, $custom_targets);
$side_effects_next_step = $this->evaluateSideEffects($current_tree_step, $lab_k, $lab_na, $lab_cr, $mean_bp_pulse, $external_avg, $custom_targets);
if ($side_effects_next_step !== null) {
$next_step = $side_effects_next_step;
} else {
// Evaluate BP vs Threshold only if no side effects detected
$is_above = $this->checkBPvsThreshold($records, $target_systolic, .6, $external_avg);
$systolic_mean = $is_above ? $is_above : false; // If uncontrolled, return the mean of the last 2 weeks
$this->emDebug("if falls thruogh side effects, then do controlled/uncontrolled", $is_above, $systolic_mean);
if ($is_above) {
$uncontrolled_next_step = (isset($current_tree_step["bp_status"]) && is_array($current_tree_step["bp_status"]) && array_key_exists("Uncontrolled", $current_tree_step["bp_status"]))
? $current_tree_step["bp_status"]["Uncontrolled"]
: null;
$next_step = $uncontrolled_next_step;
$this->emDebug("if uncontrolled go to next step", $current_tree_step);
}
}
$this->emDebug("Hey its Uncontrolled a", $next_step);
if (isset($next_step)) {
$current_update_ts = date("Y-m-d H:i:s");
$need_lab = false;
$this->emDebug("Hey its Uncontrolled b", $next_step);
if (empty($lab_values)) {
$need_lab = true;
} elseif (!empty($next_step["k"]) && !isset($lab_values["k"])) {
$need_lab = true;
} elseif (!empty($next_step["cr"]) && !isset($lab_values["cr"])) {
$need_lab = true;
} elseif (!empty($next_step["na"]) && !isset($lab_values["na"])) {
$need_lab = true;