forked from openemr/openemr
/
clinical_rules.php
1421 lines (1255 loc) · 49.9 KB
/
clinical_rules.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
// Copyright (C) 2010 Brady Miller <brady@sparmy.com>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// Functions are kept here that will support the clinical rules.
require_once(dirname(__FILE__) . "/patient.inc");
require_once(dirname(__FILE__) . "/forms.inc");
require_once(dirname(__FILE__) . "/formdata.inc.php");
require_once(dirname(__FILE__) . "/options.inc.php");
// Display the clinical summary widget.
// Parameters:
// $patient_id - pid of selected patient
// $dateTarget - target date. If blank then will test with current date as target.
function clinical_summary_widget($patient_id,$dateTarget='') {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Collect active actions
$actions = test_rules_clinic('','passive_alert',$dateTarget,'reminders',$patient_id);
// Display the actions
foreach ($actions as $action) {
if ($action['custom_flag']) {
// Start link for reminders that use the custom rules input screen
echo "<a href='../rules/patient_data.php?category=" .
htmlspecialchars( $action['category'], ENT_QUOTES) . "&item=" .
htmlspecialchars( $action['item'], ENT_QUOTES) .
"' class='iframe medium_modal' onclick='top.restoreSession()'>";
}
else if ($action['clin_rem_link']) {
// Start link for reminders that use the custom rules input screen
echo "<a href='../../../" . $action['reminder_message'] .
"' class='iframe medium_modal' onclick='top.restoreSession()'>";
}
else {
// continue, since no link will be created
}
// Display Reminder Details
echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$action['category']) .
": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$action['item']);
if ($action['custom_flag'] || $action['clin_rem_link']) {
// End link for reminders that use an html link
echo "</a>";
}
// Display due status
if ($action['due_status']) {
// Color code the status (red for past due, yellow for due, and black for soon due)
if ($action['due_status'] == "past_due") {
echo " (<span style='color:red'>";
}
else if ($action['due_status'] == "due") {
echo " (<span style='color:green'>";
}
else {
echo " (<span>";
}
echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$action['due_status']) . "</span>)<br>";
}
else {
echo "<br>";
}
}
}
// Test the clinic rules of entire clinic and create a report or patient reminders
// (can also test on one patient or patients of one provider)
// Parameters:
// $provider - id of a selected provider. If blank, then will test entire clinic.
// $type - rule filter (active_alert,passive_alert,cqm,patient_reminder). If blank then will test all rules.
// $dateTarget - target date. If blank then will test with current date as target.
// $mode - choose either 'report' or 'reminders' (required)
// $patient_id - pid of patient. If blank then will check all patients.
// Return:
// Returns a two-dimensional array of results that depends on the mode:
// reminders mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
// report mode - returns an array of rows for the Clinical Quality Measures (CQM) report
function test_rules_clinic($provider='',$type='',$dateTarget='',$mode='',$patient_id='') {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Prepare the results array
$results = array();
// Collect all patient ids
$patientData = array();
if (!empty($patient_id)) {
// only look at the selected patient
array_push($patientData,$patient_id);
}
else {
if (empty($provider)) {
// Look at entire practice
$rez = sqlStatement("SELECT `pid` FROM `patient_data`");
for($iter=0; $row=sqlFetchArray($rez); $iter++) {
$patientData[$iter]=$row;
}
}
else {
// Look at one provider
$rez = sqlStatement("SELECT `pid` FROM `patient_data` " .
"WHERE providerID=?", array($provider) );
for($iter=0; $row=sqlFetchArray($rez); $iter++) {
$patientData[$iter]=$row;
}
}
}
// Go through each patient(s)
//
// If in report mode, then tabulate for each rule:
// Total Patients
// Patients that pass the filter
// Patients that pass the target
// If in reminders mode, then create reminders for each rule:
// Reminder that action is due soon
// Reminder that action is due
// Reminder that action is post-due
//Collect applicable rules
if ($mode == "reminders") {
// Use per patient custom rules (if exist)
$rules = resolve_rules_sql($type,$patient_id);
}
else { // $mode = "report"
// Only use default rules (do not use patient custom rules
$rules = resolve_rules_sql($type);
}
foreach( $rules as $rowRule ) {
// If in reminder mode then need to collect the measurement dates
// from rule_reminder table
$target_dates = array();
if ($mode == "reminders") {
// Calculate the dates to check for
if ($type == "patient_reminder") {
$reminder_interval_type = "patient_reminder";
}
else { // $type == "passive_alert" or $type == "active_alert"
$reminder_interval_type = "clinical_reminder";
}
$target_dates = calculate_reminder_dates($rowRule['id'], $dateTarget, $reminder_interval_type);
}
else { // $mode == "reports"
// Only use the target date in the report
$target_dates[0] = $dateTarget;
}
//Reset the counters
$total_patients = 0;
$pass_filter = 0;
$pass_target = 0;
foreach( $patientData as $rowPatient ) {
// Count the total patients
$total_patients++;
$dateCounter = 1; // for reminder mode to keep track of which date checking
foreach ( $target_dates as $dateFocus ) {
//Skip if date is set to SKIP
if ($dateFocus == "SKIP") {
$dateCounter++;
continue;
}
//Set date counter and reminder token (applicable for reminders only)
if ($dateCounter == 1) {
$reminder_due = "soon_due";
}
else if ($dateCounter == 2) {
$reminder_due = "due";
}
else { // $dateCounter == 3
$reminder_due = "past_due";
}
// Check if pass filter
$passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
if ($passFilter) {
$pass_filter++;
}
else {
$dateCounter++;
continue;
}
// Check if pass target
$passTarget = test_targets($rowPatient['pid'],$rowRule['id'],'',$dateFocus);
if ($passTarget) {
$pass_target++;
break;
}
else {
if ($mode == "reminders") {
// place the actions into the reminder return array
$actionArray = resolve_action_sql($rowRule['id'],'1');
foreach ($actionArray as $action) {
$action_plus = $action;
$action_plus['due_status'] = $reminder_due;
$action_plus['pid'] = $rowPatient['pid'];
$results = reminder_results_integrate($results, $action_plus);
}
}
}
$dateCounter++;
}
}
// Calculate and save the data for the rule
if ($pass_filter > 0) {
$percentage = number_format(($pass_target/$pass_filter)*100) . xl('%');
}
else {
$percentage = "0". xl('%');
}
if ($mode == "report") {
$newRow=array("main", $rowRule['id'], $total_patients, $pass_filter, $pass_target, $percentage);
array_push($results, $newRow);
}
// Find the number of target groups, and go through each one if more than one
$targetGroups = numberTargetGroups($rowRule['id']);
if ($targetGroups > 1) {
if ($mode == "reminders") {
$start_id = 2;
}
else { // $mode == "report"
$start_id = 1;
}
for ($i = $start_id; $i <= $targetGroups; $i++){
//Reset the target counter
$pass_target = 0;
foreach( $patientData as $rowPatient ) {
$dateCounter = 1; // for reminder mode to keep track of which date checking
foreach ( $target_dates as $dateFocus ) {
//Skip if date is set to SKIP
if ($dateFocus == "SKIP") {
$dateCounter++;
continue;
}
//Set date counter and reminder token (applicable for reminders only)
if ($dateCounter == 1) {
$reminder_due = "soon_due";
}
else if ($dateCounter == 2) {
$reminder_due = "due";
}
else { // $dateCounter == 3
$reminder_due = "past_due";
}
//Check if pass target
$passTarget = test_targets($rowPatient['pid'],$rowRule['id'],$i,$dateFocus);
if ($passTarget) {
$pass_target++;
break;
}
else {
if ($mode == "reminders") {
// place the actions into the reminder return array
$actionArray = resolve_action_sql($rowRule['id'],$i);
foreach ($actionArray as $action) {
$action_plus = $action;
$action_plus['due_status'] = $reminder_due;
$action_plus['pid'] = $rowPatient['pid'];
$results = reminder_results_integrate($results, $action_plus);
}
}
}
$dateCounter++;
}
}
// Calculate and save the data for the rule
if ($pass_filter > 0) {
$percentage = number_format(($pass_target/$pass_filter)*100) . xl('%');
}
else {
$percentage = "0". xl('%');
}
// Collect action for title (just use the first one, if more than one)
$actionArray = resolve_action_sql($rowRule['id'],$i);
$action = $actionArray[0];
if ($mode == "report") {
$newRow=array("sub", $action['category']."::".$action['item'], " ", " ", $pass_target, $percentage);
array_push($results, $newRow);
}
}
}
}
// Return the data
return $results;
}
// Test filter of a selected rule on a selected patient
// Parameters:
// $patient_id - pid of selected patient.
// $rule - id(string) of selected rule
// $dateTarget - target date.
// Return:
// boolean (if pass filter then true, otherwise false)
function test_filter($patient_id,$rule,$dateTarget) {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Collect patient information
$patientData = getPatientData($patient_id, "sex, DATE_FORMAT(DOB,'%Y %m %d') as DOB_TS");
// -------- Special Filters --------
// Check for special flag required by many of the CQM rules, that uses a standard
// measurement year (Jan1-Dec31). This adjusted date would then be used for
// date to calculate patient age and as the start range if filtering for clinic
// appointments. The value (usually will be 1) of this
// contains how many years to include.
$adjustedDate1 = '';
$adjustedDate2 = '';
$filter = resolve_filter_sql($rule,'filt_measure_period');
if (!empty($filter)) {
$row = $filter[0];
if ($row['method_detail'] == "year") {
$tempDateArray = explode("-",$dateTarget);
$tempYear = $tempDateArray[0];
// Set too one second before the measurement period
$adjustedDate1 = ($tempYear - $row['value']) . "-12-31 23:59:59";
// Set too the first second of the measurement period
$adjustedDate2 = ($tempYear - ($row['value']-1)) . "-01-01 00:00:00";
// Set target date to the last second of the measurement period
$dateTarget = ($tempYear - ($row['value']-1)) . "-12-31 23:59:59";
}
}
// -------- Age Filter ------------
// Calculate patient age in years and months
if (!empty($adjustedDate1)) {
// See above Special Filters section in for details.
$patientAgeYears = convertDobtoAgeYearDecimal($patientData['DOB_TS'],$adjustedDate1);
$patientAgeMonths = convertDobtoAgeMonthDecimal($patientData['DOB_TS'],$adjustedDate1);
}
else {
$patientAgeYears = convertDobtoAgeYearDecimal($patientData['DOB_TS'],$dateTarget);
$patientAgeMonths = convertDobtoAgeMonthDecimal($patientData['DOB_TS'],$dateTarget);
}
// Min age (year) Filter (includes) (assume that there in not more than one of each)
$filter = resolve_filter_sql($rule,'filt_age_min');
if (!empty($filter)) {
$row = $filter[0];
if ($row ['method_detail'] == "year") {
if ( $row['value'] && ($row['value'] > $patientAgeYears) ) {
return false;
}
}
if ($row ['method_detail'] == "month") {
if ( $row['value'] && ($row['value'] > $patientAgeMonths) ) {
return false;
}
}
}
// Max age (year) Filter (includes) (assume that there in not more than one of each)
$filter = resolve_filter_sql($rule,'filt_age_max');
if (!empty($filter)) {
$row = $filter[0];
if ($row ['method_detail'] == "year") {
if ( $row['value'] && ($row['value'] < $patientAgeYears) ) {
return false;
}
}
if ($row ['method_detail'] == "month") {
if ( $row['value'] && ($row['value'] < $patientAgeMonths) ) {
return false;
}
}
}
// -------- Gender Filter ---------
// Gender Filter (includes) (assume that there in not more than one of each)
$filter = resolve_filter_sql($rule,'filt_sex');
if (!empty($filter)) {
$row = $filter[0];
if ( $row['value'] && ($row['value'] != $patientData['sex']) ) {
return false;
}
}
// -------- Database Filter ------
// Database Filter (includes)
$filter = resolve_filter_sql($rule,'filt_database');
if ((!empty($filter)) && !database_check($patient_id,$filter,'',$dateTarget)) return false;
// -------- Lists Filter ----
// Set up lists filter, which is fully customizable and currently includes diagnoses, meds,
// surgeries and allergies.
$filter = resolve_filter_sql($rule,'filt_lists');
if ((!empty($filter)) && !lists_check($patient_id,$filter,$dateTarget)) return false;
// Set up exclusion filter
$filter = resolve_filter_sql($rule,'filt_lists',0);
if ((!empty($filter)) && lists_check($patient_id,$filter,$dateTarget)) return false;
// -------- Clinic Visit(s) Filter --------
$filter = resolve_filter_sql($rule,'filt_encounter_min');
if (!empty($filter)) {
$row = $filter[0];
// For total number of appointments, simply get number of encounters
if (!empty($adjustedDate2)) {
// See above Special Filters section in for details.
$encounters = getEncounters($patient_id,$adjustedDate2,$dateTarget);
}
else {
$encounters = getEncounters($patient_id,'',$dateTarget);
}
(empty($encounters)) ? $totalNumberAppt = 0 : $totalNumberAppt = count($encounters);
if ($row['value'] && $totalNumberAppt < $row['value']) return false;
}
// Passed all filters, so return true.
return true;
}
// Return the number of target groups of a selected rule
// Parameters:
// $rule - id(string) of rule
// Return:
// integer, number of target groups associated with rule
function numberTargetGroups($rule) {
$numberGroups = 1;
$sql = sqlQuery("SELECT max(`group_id`) as numberGroups FROM `rule_target` " .
"WHERE `id`=?", array($rule) );
if ($sql['numberGroups']) $numberGroups = $sql['numberGroups'];
return $numberGroups;
}
// Test targets of a selected rule on a selected patient
// Parameters:
// $patient_id - pid of selected patient.
// $rule - id(string) of selected rule (if blank, then will ignore grouping)
// $group_id - group id of target group
// $dateTarget - target date.
// Return:
// boolean (if target passes then true, otherwise false)
function test_targets($patient_id,$rule,$group_id='',$dateTarget) {
// -------- Interval Target ----
$interval = resolve_target_sql($rule,$group_id,'target_interval');
// -------- Database Target ----
// Database Target (includes)
$target = resolve_target_sql($rule,$group_id,'target_database');
if ((!empty($target)) && !database_check($patient_id,$target,$interval,$dateTarget)) return false;
// -------- Procedure (labs,imaging,test,procedures,etc) Target ----
// Procedure Target (includes)
$target = resolve_target_sql($rule,$group_id,'target_proc');
if ((!empty($target)) && !procedure_check($patient_id,$target,$interval,$dateTarget)) return false;
// -------- Appointment Target ----
// Appointment Target (includes) (Specialized functionality for appointment reminders)
$target = resolve_target_sql($rule,$group_id,'target_appt');
if ((!empty($target)) && appointment_check($patient_id,$dateTarget)) return false;
// Passed all target tests, so return true.
return true;
}
// Function to return active rules
// Parameters:
// $type - rule filter (active_alert,passive_alert,cqm,patient_reminder)
// $patient_id - pid of selected patient. (if custom rule does not exist then
// will use the default rule.
// Return: array containing rules
function resolve_rules_sql($type='',$patient_id='0') {
// Collect all default rules into an array
$sql = sqlStatement("SELECT * FROM `clinical_rules` WHERE `pid`=0 ORDER BY `id`");
$returnArray= array();
for($iter=0; $row=sqlFetchArray($sql); $iter++) {
array_push($returnArray,$row);
}
// Now collect the pertinent rules
$newReturnArray = array();
// Need to select rules (use custom if exist)
foreach ($returnArray as $rule) {
$customRule = sqlQuery("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule['id'],$patient_id) );
// Decide if use default vs custom rule (preference given to custom rule)
if (!empty($customRule)) {
$goRule = $customRule;
}
else {
$goRule = $rule;
}
// Use the chosen rule if set
if (!empty($type)) {
if ($goRule['active'] == 1 && $goRule["${type}_flag"] == 1) {
// active, so use the rule
array_push($newReturnArray,$goRule);
}
}
else {
if ($goRule['active'] == 1) {
// active, so use the rule
array_push($newReturnArray,$goRule);
}
}
}
$returnArray = $newReturnArray;
return $returnArray;
}
// Function to return applicable reminder dates (relative)
// Parameters:
// $rule - id(string) of selected rule
// $reminder_method - string label of filter type
// Return: array containing reminder features
function resolve_reminder_sql($rule,$reminder_method) {
$sql = sqlStatement("SELECT `method_detail`, `value` FROM `rule_reminder` " .
"WHERE `id`=? AND `method`=?", array($rule, $reminder_method) );
$returnArray= array();
for($iter=0; $row=sqlFetchArray($sql); $iter++) {
array_push($returnArray,$row);
}
return $returnArray;
}
// Function to return applicable filters
// Parameters:
// $rule - id(string) of selected rule
// $filter_method - string label of filter type
// $include_flag - to allow selection for included or excluded filters
// Return: array containing filters
function resolve_filter_sql($rule,$filter_method,$include_flag=1) {
$sql = sqlStatement("SELECT `method_detail`, `value`, `required_flag` FROM `rule_filter` " .
"WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $filter_method, $include_flag) );
$returnArray= array();
for($iter=0; $row=sqlFetchArray($sql); $iter++) {
array_push($returnArray,$row);
}
return $returnArray;
}
// Function to return applicable targets
// Parameters:
// $rule - id(string) of selected rule
// $group_id - group id of target group (if blank, then will ignore grouping)
// $target_method - string label of target type
// $include_flag - to allow selection for included or excluded targets
// Return: array containing targets
function resolve_target_sql($rule,$group_id='',$target_method,$include_flag=1) {
if ($group_id) {
$sql = sqlStatement("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
"WHERE `id`=? AND `group_id`=? AND `method`=? AND `include_flag`=?", array($rule, $group_id, $target_method, $include_flag) );
}
else {
$sql = sqlStatement("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
"WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $target_method, $include_flag) );
}
$returnArray= array();
for($iter=0; $row=sqlFetchArray($sql); $iter++) {
array_push($returnArray,$row);
}
return $returnArray;
}
// Function to return applicable actions
// Parameters:
// $rule - id(string) of selected rule
// $group_id - group id of target group (if blank, then will ignore grouping)
// Return: array containing actions
function resolve_action_sql($rule,$group_id='') {
if ($group_id) {
$sql = sqlStatement("SELECT b.category, b.item, b.clin_rem_link, b.reminder_message, b.custom_flag " .
"FROM `rule_action` as a " .
"JOIN `rule_action_item` as b " .
"ON a.category = b.category AND a.item = b.item " .
"WHERE a.id=? AND a.group_id=?", array($rule,$group_id) );
}
else {
$sql = sqlStatement("SELECT b.category, b.item, b.value, b.custom_flag " .
"FROM `rule_action` as a " .
"JOIN `rule_action_item` as b " .
"ON a.category = b.category AND a.item = b.item " .
"WHERE a.id=?", array($rule) );
}
$returnArray= array();
for($iter=0; $row=sqlFetchArray($sql); $iter++) {
array_push($returnArray,$row);
}
return $returnArray;
}
// Function to check database filters and targets
// Parameters:
// $patient_id - pid of selected patient.
// $filter - array containing filter/target elements
// $interval - used for the interval elements
// $dateTarget - target date. blank is current date.
// Return: boolean if check passed, otherwise false
function database_check($patient_id,$filter,$interval='',$dateTarget='') {
$isMatch = false; //matching flag
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Unpackage interval information
// (Assume only one for now and only pertinent for targets)
$intervalType = '';
$intervalValue = '';
if (!empty($interval)) {
$intervalType = $interval[0]['value'];
$intervalValue = $interval[0]['interval'];
}
foreach( $filter as $row ) {
// Row description
// [0]=>special modes
$temp_df = explode("::",$row['value']);
if ($temp_df[0] == "CUSTOM") {
// Row description
// [0]=>special modes(CUSTOM) [1]=>category [2]=>item [3]=>complete? [4]=>number of hits comparison [5]=>number of hits
if (exist_custom_item($patient_id, $temp_df[1], $temp_df[2], $temp_df[3], $temp_df[4], $temp_df[5], $intervalType, $intervalValue, $dateTarget)) {
// Record the match
$isMatch = true;
}
else {
// If this is a required entry then return false
if ($row['required_flag']) return false;
}
}
else if ($temp_df[0] == "LIFESTYLE") {
// Row description
// [0]=>special modes(LIFESTYLE) [1]=>column [2]=>status
if (exist_lifestyle_item($patient_id, $temp_df[1], $temp_df[2], $dateTarget)) {
// Record the match
$isMatch = true;
}
else {
// If this is a required entry then return false
if ($row['required_flag']) return false;
}
}
else {
// Default mode
// Row description
// [0]=>special modes(BLANK) [1]=>table [2]=>column [3]=>value comparison [4]=>value [5]=>number of hits comparison [6]=>number of hits
if (exist_database_item($patient_id, $temp_df[1], $temp_df[2], $temp_df[3], $temp_df[4], $temp_df[5], $temp_df[6], $intervalType, $intervalValue, $dateTarget)) {
// Record the match
$isMatch = true;
}
else {
// If this is a required entry then return false
if ($row['required_flag']) return false;
}
}
}
// return results of check
return $isMatch;
}
// Function to check procedure filters and targets
// Parameters:
// $patient_id - pid of selected patient.
// $filter - array containing filter/target elements
// $interval - used for the interval elements
// $dateTarget - target date. blank is current date.
// Return: boolean if check passed, otherwise false
function procedure_check($patient_id,$filter,$interval='',$dateTarget='') {
$isMatch = false; //matching flag
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Unpackage interval information
// (Assume only one for now and only pertinent for targets)
$intervalType = '';
$intervalValue = '';
if (!empty($interval)) {
$intervalType = $interval[0]['value'];
$intervalValue = $interval[0]['interval'];
}
foreach( $filter as $row ) {
// Row description
// [0]=>title [1]=>code [2]=>value comparison [3]=>value [4]=>number of hits comparison [5]=>number of hits
// code description
// <type(ICD9,CPT)>:<identifier>; etc.
$temp_df = explode("::",$row['value']);
if (exist_procedure_item($patient_id, $temp_df[0], $temp_df[1], $temp_df[2], $temp_df[3], $temp_df[4], $temp_df[5], $intervalType, $intervalValue, $dateTarget)) {
// Record the match
$isMatch = true;
}
else {
// If this is a required entry then return false
if ($row['required_flag']) return false;
}
}
// return results of check
return $isMatch;
}
// Function to check for appointment
// Parameters:
// $patient_id - pid of selected patient.
// $dateTarget - target date.
// Return: boolean if appt exist, otherwise false
function appointment_check($patient_id,$dateTarget='') {
$isMatch = false; //matching flag
// Set date to current if not set (although should always be set)
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
$dateTargetRound = date('Y-m-d',$dateTarget);
// Set current date
$currentDate = date('Y-m-d H:i:s');
$currentDateRound = date('Y-m-d',$dateCurrent);
// Basically, if the appointment is within the current date to the target date,
// then return true. (will not send reminders on same day as appointment)
$sql = sqlStatement("SELECT openemr_postcalendar_events.pc_eid, " .
"openemr_postcalendar_events.pc_title, " .
"openemr_postcalendar_events.pc_eventDate, " .
"openemr_postcalendar_events.pc_startTime, " .
"openemr_postcalendar_events.pc_endTime " .
"FROM openemr_postcalendar_events " .
"WHERE openemr_postcalendar_events.pc_eventDate > ? " .
"AND openemr_postcalendar_events.pc_eventDate <= ? " .
"AND openemr_postcalendar_events.pc_pid = ?", array($currentDate,$dateTarget,$patient_id) );
// return results of check
//
// TODO: Figure out how to have multiple appointment and changing appointment reminders.
// Plan to send back array of appt info (eid, time, date, etc.)
// to do this.
if (sqlNumRows($sql) > 0) {
$isMatch = true;
}
return $isMatch;
}
// Function to check lists filters and targets
// Customizable and currently includes diagnoses, medications,
// allergies and surgeries.
// Parameters:
// $patient_id - pid of selected patient.
// $filter - array containing lists filter/target elements
// $dateTarget - target date. blank is current date.
// Return: boolean if check passed, otherwise false
function lists_check($patient_id,$filter,$dateTarget) {
$isMatch = false; //matching flag
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
foreach ( $filter as $row ) {
if (exist_lists_item($patient_id, $row['method_detail'], $row['value'], $dateTarget)) {
// Record the match
$isMatch = true;
}
else {
// If this is a required entry then return false
if ($row['required_flag']) return false;
}
}
// return results of check
return $isMatch;
}
// Function to check for existance of data in database for a patient
// Parameters:
// $patient_id - pid of selected patient.
// $table - selected mysql table
// $column - selected mysql column
// $data_comp - data comparison (eq,ne,gt,ge,lt,le)
// $data - selected data in the mysql database
// $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
// $num_items_thres - number of items threshold
// $intervalType - type of interval (ie. year)
// $intervalValue - searched for within this many times of the interval type
// $dateTarget - target date.
// Return: boolean if check passed, otherwise false
function exist_database_item($patient_id,$table,$column='',$data_comp,$data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Collect the correct column label for patient id in the table
$patient_id_label = collect_database_label('pid',$table);
// Get the interval sql query string
$dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
// If just checking for existence (ie. data is empty),
// then simply set the comparison operator to ne.
if (empty($data)) {
$data_comp = "ne";
}
// get the appropriate sql comparison operator
$compSql = convertCompSql($data_comp);
// check for items
if (empty($column)) {
// simple search for any table entries
$sql = sqlStatement("SELECT * " .
"FROM `" . add_escape_custom($table) . "` " .
"WHERE `" . add_escape_custom($patient_id_label) . "`=?", array($patient_id) );
}
else {
// search for number of specific items
$sql = sqlStatement("SELECT `" . add_escape_custom($column) . "` " .
"FROM `" . add_escape_custom($table) . "` " .
"WHERE `" . add_escape_custom($column) ."`" . $compSql . "? " .
"AND `" . add_escape_custom($patient_id_label) . "`=? " .
$dateSql, array($data,$patient_id) );
}
// See if number of returned items passes the comparison
return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
}
// Function to check for existence of procedure(s) for a patient
// Parameters:
// $patient_id - pid of selected patient.
// $proc_title - procedure title
// $proc_code - procedure identifier code (array)
// $result_comp - results comparison (eq,ne,gt,ge,lt,le)
// $result_data - results data
// $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
// $num_items_thres - number of items threshold
// $intervalType - type of interval (ie. year)
// $intervalValue - searched for within this many times of the interval type
// $dateTarget - target date.
// Return: boolean if check passed, otherwise false
function exist_procedure_item($patient_id,$proc_title,$proc_code,$result_comp,$result_data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Set the table exception (for looking up pertinent date and pid sql columns)
$table = "PROCEDURE-EXCEPTION";
// Collect the correct column label for patient id in the table
$patient_id_label = collect_database_label('pid',$table);
// Get the interval sql query string
$dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
//
// TODO
// Figure out a way to use the identifiers codes
// TODO
//
// If just checking for existence (ie result_data is empty),
// then simply set the comparison operator to ne.
if (empty($result_data)) {
$result_comp = "ne";
}
// get the appropriate sql comparison operator
$compSql = convertCompSql($result_comp);
// collect specific items that fulfill request
$sql = sqlStatement("SELECT procedure_result.result " .
"FROM `procedure_type`, " .
"`procedure_order`, " .
"`procedure_report`, " .
"`procedure_result` " .
"WHERE procedure_type.procedure_type_id = procedure_order.procedure_type_id " .
"AND procedure_order.procedure_order_id = procedure_report.procedure_order_id " .
"AND procedure_report.procedure_report_id = procedure_result.procedure_report_id " .
"AND procedure_type.name = ? " .
"AND procedure_result.result " . $compSql . " ? " .
"AND " . add_escape_custom($patient_id_label) . " = ? " .
$dateSql, array($proc_title,$result_data,$patient_id) );
// See if number of returned items passes the comparison
return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
}
// Function to check for existance of data for a patient in the rule_patient_data table
// Parameters:
// $patient_id - pid of selected patient.
// $category - label in category column
// $item - label in item column
// $complete - label in complete column (YES,NO, or blank)
// $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
// $num_items_thres - number of items threshold
// $intervalType - type of interval (ie. year)
// $intervalValue - searched for within this many times of the interval type
// $dateTarget - target date.
// Return: boolean if check passed, otherwise false
function exist_custom_item($patient_id,$category,$item,$complete,$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget) {
// Set the table
$table = 'rule_patient_data';
// Collect the correct column label for patient id in the table
$patient_id_label = collect_database_label('pid',$table);
// Get the interval sql query string
$dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
// search for number of specific items
$sql = sqlStatement("SELECT `result` " .
"FROM `" . add_escape_custom($table) . "` " .
"WHERE `category`=? " .
"AND `item`=? " .
"AND `complete`=? " .
"AND `" . add_escape_custom($patient_id_label) . "`=? " .
$dateSql, array($category,$item,$complete,$patient_id) );
// See if number of returned items passes the comparison
return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
}
// Function to check for existance of data for a patient in lifestyle section
// Parameters:
// $patient_id - pid of selected patient.
// $lifestyle - selected label of mysql column of patient history
// $status - specific status of selected lifestyle element
// $dateTarget - target date. blank is current date.
// Return: boolean if check passed, otherwise false
function exist_lifestyle_item($patient_id,$lifestyle,$status,$dateTarget) {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Collect pertinent history data
$history = getHistoryData($patient_id, $lifestyle,'',$dateTarget);
// See if match
$stringFlag = strstr($history[$lifestyle], "|".$status);
if (empty($status)) {
// Only ensuring any data has been entered into the field
$stringFlag = true;
}
if ( $history[$lifestyle] &&
$history[$lifestyle] != '|0|' &&
$stringFlag ) {
return true;
}
else {
return false;
}
}
// Function to check for lists item of a patient
// Fully customizable and includes diagnoses, medications,
// allergies, and surgeries.
// Parameters:
// $patient_id - pid of selected patient.
// $type - type (medical_problem, allergy, medication, etc)
// $value - value searching for
// $dateTarget - target date. blank is current date.
// Return: boolean if check passed, otherwise false
function exist_lists_item($patient_id,$type,$value,$dateTarget) {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
if ($type == "medical_problem") {