CDR engine updates:
[openemr.git] / library / clinical_rules.php
blob78e5d52ff5d02847547cd21e056b7f498459cb6c
1 <?php
2 // Copyright (C) 2011 by following authors:
3 // -Brady Miller <brady@sparmy.com>
4 // -Ensofttek, LLC
5 // -Medical Information Integration, LLC
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License
9 // as published by the Free Software Foundation; either version 2
10 // of the License, or (at your option) any later version.
12 // Functions are kept here that will support the clinical rules.
14 require_once(dirname(__FILE__) . "/patient.inc");
15 require_once(dirname(__FILE__) . "/forms.inc");
16 require_once(dirname(__FILE__) . "/formdata.inc.php");
17 require_once(dirname(__FILE__) . "/options.inc.php");
19 // Display the clinical summary widget.
20 // Parameters:
21 // $patient_id - pid of selected patient
22 // $mode - choose either 'reminders-all' or 'reminders-due' (required)
23 // $dateTarget - target date. If blank then will test with current date as target.
24 // $organize_mode - Way to organize the results (default or plans)
25 function clinical_summary_widget($patient_id,$mode,$dateTarget='',$organize_mode='default') {
27 // Set date to current if not set
28 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
30 // Collect active actions
31 $actions = test_rules_clinic('','passive_alert',$dateTarget,$mode,$patient_id,'',$organize_mode);
33 // Display the actions
34 foreach ($actions as $action) {
36 // Deal with plan names first
37 if ($action['is_plan']) {
38 echo "<br><b>";
39 echo htmlspecialchars( xl("Plan"), ENT_NOQUOTES) . ": ";
40 echo generate_display_field(array('data_type'=>'1','list_id'=>'clinical_plans'),$action['id']);
41 echo "</b><br>";
42 continue;
45 if ($action['custom_flag']) {
46 // Start link for reminders that use the custom rules input screen
47 echo "<a href='../rules/patient_data.php?category=" .
48 htmlspecialchars( $action['category'], ENT_QUOTES) . "&item=" .
49 htmlspecialchars( $action['item'], ENT_QUOTES) .
50 "' class='iframe medium_modal' onclick='top.restoreSession()'>";
52 else if ($action['clin_rem_link']) {
53 // Start link for reminders that use the custom rules input screen
54 echo "<a href='../../../" . $action['reminder_message'] .
55 "' class='iframe medium_modal' onclick='top.restoreSession()'>";
57 else {
58 // continue, since no link will be created
61 // Display Reminder Details
62 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$action['category']) .
63 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$action['item']);
65 if ($action['custom_flag'] || $action['clin_rem_link']) {
66 // End link for reminders that use an html link
67 echo "</a>";
70 // Display due status
71 if ($action['due_status']) {
72 // Color code the status (red for past due, purple for due, green for not due and black for soon due)
73 if ($action['due_status'] == "past_due") {
74 echo "&nbsp;&nbsp;(<span style='color:red'>";
76 else if ($action['due_status'] == "due") {
77 echo "&nbsp;&nbsp;(<span style='color:purple'>";
79 else if ($action['due_status'] == "not_due") {
80 echo "&nbsp;&nbsp;(<span style='color:green'>";
82 else {
83 echo "&nbsp;&nbsp;(<span>";
85 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$action['due_status']) . "</span>)<br>";
87 else {
88 echo "<br>";
94 // Display the active screen reminder.
95 // Parameters:
96 // $patient_id - pid of selected patient
97 // $mode - choose either 'reminders-all' or 'reminders-due' (required)
98 // $dateTarget - target date. If blank then will test with current date as target.
99 // $organize_mode - Way to organize the results (default or plans)
100 function active_alert_summary($patient_id,$mode,$dateTarget='',$organize_mode='default') {
102 // Set date to current if not set
103 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
105 // Collect active actions
106 $actions = test_rules_clinic('','active_alert',$dateTarget,$mode,$patient_id,'',$organize_mode);
108 if (empty($actions)) {
109 return false;
112 $returnOutput = "";
114 // Display the actions
115 foreach ($actions as $action) {
117 // Deal with plan names first
118 if ($action['is_plan']) {
119 $returnOutput .= "<br><b>";
120 $returnOutput .= htmlspecialchars( xl("Plan"), ENT_NOQUOTES) . ": ";
121 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'clinical_plans'),$action['id']);
122 $returnOutput .= "</b><br>";
123 continue;
126 // Display Reminder Details
127 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$action['category']) .
128 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$action['item']);
130 // Display due status
131 if ($action['due_status']) {
132 // Color code the status (red for past due, purple for due, green for not due and black for soon due)
133 if ($action['due_status'] == "past_due") {
134 $returnOutput .= "&nbsp;&nbsp;(<span style='color:red'>";
136 else if ($action['due_status'] == "due") {
137 $returnOutput .= "&nbsp;&nbsp;(<span style='color:purple'>";
139 else if ($action['due_status'] == "not_due") {
140 $returnOutput .= "&nbsp;&nbsp;(<span style='color:green'>";
142 else {
143 $returnOutput .= "&nbsp;&nbsp;(<span>";
145 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$action['due_status']) . "</span>)<br>";
147 else {
148 $returnOutput .= "<br>";
151 return $returnOutput;
154 // Test the clinic rules of entire clinic and create a report or patient reminders
155 // (can also test on one patient or patients of one provider)
156 // Parameters:
157 // $provider - id of a selected provider. If blank, then will test entire clinic. If 'collate_outer' or
158 // 'collate_inner', then will test each provider in entire clinic; outer will nest plans
159 // inside collated providers, while inner will nest the providers inside the plans (note
160 // inner and outer are only different if organize_mode is set to plans).
161 // $type - rule filter (active_alert,passive_alert,cqm,amc,patient_reminder). If blank then will test all rules.
162 // $dateTarget - target date. If blank then will test with current date as target.
163 // If an array, then is holding two dates ('dateBegin' and 'dateTarget')
164 // $mode - choose either 'report' or 'reminders-all' or 'reminders-due' (required)
165 // $patient_id - pid of patient. If blank then will check all patients.
166 // $plan - test for specific plan only
167 // $organize_mode - Way to organize the results (default, plans)
168 // 'default':
169 // Returns a two-dimensional array of results organized by rules:
170 // reminders-due mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
171 // reminders-all mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
172 // report mode - returns an array of rows for the Clinical Quality Measures (CQM) report
173 // 'plans':
174 // Returns similar to default, but organizes by the active plans
175 // $options - can hold various option (for now, used to hold the manual number of labs for the AMC report)
177 function test_rules_clinic($provider='',$type='',$dateTarget='',$mode='',$patient_id='',$plan='',$organize_mode='default',$options=array()) {
179 // If dateTarget is an array, then organize them.
180 if (is_array($dateTarget)) {
181 $dateArray = $dateTarget;
182 $dateTarget = $dateTarget['dateTarget'];
185 // Set date to current if not set
186 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
188 // Prepare the results array
189 $results = array();
191 // If set the $provider to collate_outer (or collate_inner without plans organize mode),
192 // then run through this function recursively and return results.
193 if (($provider == "collate_outer") || ($provider == "collate_inner" && $organize_mode != 'plans')) {
194 // First, collect an array of all providers
195 $query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
196 $ures = sqlStatement($query);
197 // Second, run through each provider recursively
198 while ($urow = sqlFetchArray($ures)) {
199 $newResults = test_rules_clinic($urow['id'],$type,$dateTarget,$mode,$patient_id,$plan,$organize_mode);
200 if (!empty($newResults)) {
201 $provider_item['is_provider'] = TRUE;
202 $provider_item['prov_lname'] = $urow['lname'];
203 $provider_item['prov_fname'] = $urow['fname'];
204 $provider_item['npi'] = $urow['npi'];
205 $provider_item['federaltaxid'] = $urow['federaltaxid'];
206 array_push($results,$provider_item);
207 $results = array_merge($results,$newResults);
210 // done, so now can return results
211 return $results;
214 // If set organize-mode to plans, then collects active plans and run through this
215 // function recursively and return results.
216 if ($organize_mode == "plans") {
217 // First, collect active plans
218 $plans_resolve = resolve_plans_sql($plan,$patient_id);
219 // Second, run through function recursively
220 foreach ($plans_resolve as $plan_item) {
221 // (if collate_inner, then nest a collation of providers within each plan)
222 if ($provider == "collate_inner") {
223 // First, collect an array of all providers
224 $query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
225 $ures = sqlStatement($query);
226 // Second, run through each provider recursively
227 $provider_results = array();
228 while ($urow = sqlFetchArray($ures)) {
229 $newResults = test_rules_clinic($urow['id'],$type,$dateTarget,$mode,$patient_id,$plan_item['id']);
230 if (!empty($newResults)) {
231 $provider_item['is_provider'] = TRUE;
232 $provider_item['prov_lname'] = $urow['lname'];
233 $provider_item['prov_fname'] = $urow['fname'];
234 $provider_item['npi'] = $urow['npi'];
235 $provider_item['federaltaxid'] = $urow['federaltaxid'];
236 array_push($provider_results,$provider_item);
237 $provider_results = array_merge($provider_results,$newResults);
240 if (!empty($provider_results)) {
241 $plan_item['is_plan'] = TRUE;
242 array_push($results,$plan_item);
243 $results = array_merge($results,$provider_results);
246 else {
247 // (not collate_inner, so do not nest providers within each plan)
248 $newResults = test_rules_clinic($provider,$type,$dateTarget,$mode,$patient_id,$plan_item['id']);
249 if (!empty($newResults)) {
250 $plan_item['is_plan'] = TRUE;
251 array_push($results,$plan_item);
252 $results = array_merge($results,$newResults);
256 // done, so now can return results
257 return $results;
260 // Collect all patient ids
261 $patientData = array();
262 if (!empty($patient_id)) {
263 // only look at the selected patient
264 $patientData[0]['pid'] = $patient_id;
266 else {
267 if (empty($provider)) {
268 // Look at entire practice
269 $rez = sqlStatement("SELECT `pid` FROM `patient_data`");
270 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
271 $patientData[$iter]=$row;
274 else {
275 // Look at one provider
276 $rez = sqlStatement("SELECT `pid` FROM `patient_data` " .
277 "WHERE providerID=?", array($provider) );
278 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
279 $patientData[$iter]=$row;
283 // Go through each patient(s)
285 // If in report mode, then tabulate for each rule:
286 // Total Patients
287 // Patients that pass the filter
288 // Patients that pass the target
289 // If in reminders mode, then create reminders for each rule:
290 // Reminder that action is due soon
291 // Reminder that action is due
292 // Reminder that action is post-due
294 //Collect applicable rules
295 if ($mode != "report") {
296 // Use per patient custom rules (if exist)
297 $rules = resolve_rules_sql($type,$patient_id,FALSE,$plan);
299 else { // $mode = "report"
300 // Only use default rules (do not use patient custom rules)
301 $rules = resolve_rules_sql($type,$patient_id,FALSE,$plan);
304 foreach( $rules as $rowRule ) {
306 // If using cqm or amc type, then use the hard-coded rules set.
307 // Note these rules are only used in report mode.
308 if ($rowRule['cqm_flag'] || $rowRule['amc_flag']) {
310 require_once( dirname(__FILE__)."/classes/rulesets/ReportManager.php");
311 $manager = new ReportManager();
312 if ($rowRule['amc_flag']) {
313 // Send array of dates ('dateBegin' and 'dateTarget')
314 $tempResults = $manager->runReport( $rowRule, $patientData, $dateArray, $options );
316 else {
317 // Send target date
318 $tempResults = $manager->runReport( $rowRule, $patientData, $dateTarget );
320 if (!empty($tempResults)) {
321 foreach ($tempResults as $tempResult) {
322 array_push($results,$tempResult);
326 // Go on to the next rule
327 continue;
330 // If in reminder mode then need to collect the measurement dates
331 // from rule_reminder table
332 $target_dates = array();
333 if ($mode != "report") {
334 // Calculate the dates to check for
335 if ($type == "patient_reminder") {
336 $reminder_interval_type = "patient_reminder";
338 else { // $type == "passive_alert" or $type == "active_alert"
339 $reminder_interval_type = "clinical_reminder";
341 $target_dates = calculate_reminder_dates($rowRule['id'], $dateTarget, $reminder_interval_type);
343 else { // $mode == "report"
344 // Only use the target date in the report
345 $target_dates[0] = $dateTarget;
348 //Reset the counters
349 $total_patients = 0;
350 $pass_filter = 0;
351 $exclude_filter = 0;
352 $pass_target = 0;
354 // Find the number of target groups
355 $targetGroups = returnTargetGroups($rowRule['id']);
357 if ( (count($targetGroups) == 1) || ($mode == "report") ) {
358 //skip this section if not report and more than one target group
359 foreach( $patientData as $rowPatient ) {
361 // Count the total patients
362 $total_patients++;
364 $dateCounter = 1; // for reminder mode to keep track of which date checking
365 foreach ( $target_dates as $dateFocus ) {
367 //Skip if date is set to SKIP
368 if ($dateFocus == "SKIP") {
369 $dateCounter++;
370 continue;
373 //Set date counter and reminder token (applicable for reminders only)
374 if ($dateCounter == 1) {
375 $reminder_due = "soon_due";
377 else if ($dateCounter == 2) {
378 $reminder_due = "due";
380 else { // $dateCounter == 3
381 $reminder_due = "past_due";
384 // First, deal with deceased patients
385 // (for now will simply not pass the filter, but can add a database item
386 // if ever want to create rules for dead people)
387 // Could also place this function at the total_patients level if wanted.
388 // (But then would lose the option of making rules for dead people)
389 // Note using the dateTarget rather than dateFocus
390 if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
391 continue;
394 // Check if pass filter
395 $passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
396 if ($passFilter === "EXCLUDED") {
397 // increment EXCLUDED and pass_filter counters
398 // and set as FALSE for reminder functionality.
399 $pass_filter++;
400 $exclude_filter++;
401 $passFilter = FALSE;
403 if ($passFilter) {
404 // increment pass filter counter
405 $pass_filter++;
407 else {
408 $dateCounter++;
409 continue;
412 // Check if pass target
413 $passTarget = test_targets($rowPatient['pid'],$rowRule['id'],'',$dateFocus);
414 if ($passTarget) {
415 // increment pass target counter
416 $pass_target++;
417 // send to reminder results
418 if ($mode == "reminders-all") {
419 // place the completed actions into the reminder return array
420 $actionArray = resolve_action_sql($rowRule['id'],'1');
421 foreach ($actionArray as $action) {
422 $action_plus = $action;
423 $action_plus['due_status'] = "not_due";
424 $action_plus['pid'] = $rowPatient['pid'];
425 $results = reminder_results_integrate($results, $action_plus);
428 break;
430 else {
431 // send to reminder results
432 if ($mode != "report") {
433 // place the uncompleted actions into the reminder return array
434 $actionArray = resolve_action_sql($rowRule['id'],'1');
435 foreach ($actionArray as $action) {
436 $action_plus = $action;
437 $action_plus['due_status'] = $reminder_due;
438 $action_plus['pid'] = $rowPatient['pid'];
439 $results = reminder_results_integrate($results, $action_plus);
443 $dateCounter++;
448 // Calculate and save the data for the rule
449 $percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
450 if ($mode == "report") {
451 $newRow=array('is_main'=>TRUE,'total_patients'=>$total_patients,'excluded'=>$exclude_filter,'pass_filter'=>$pass_filter,'pass_target'=>$pass_target,'percentage'=>$percentage);
452 $newRow=array_merge($newRow,$rowRule);
453 array_push($results, $newRow);
456 // Now run through the target groups if more than one
457 if (count($targetGroups) > 1) {
458 foreach ($targetGroups as $i) {
460 //Reset the target counter
461 $pass_target = 0;
463 foreach( $patientData as $rowPatient ) {
465 $dateCounter = 1; // for reminder mode to keep track of which date checking
466 foreach ( $target_dates as $dateFocus ) {
468 //Skip if date is set to SKIP
469 if ($dateFocus == "SKIP") {
470 $dateCounter++;
471 continue;
474 //Set date counter and reminder token (applicable for reminders only)
475 if ($dateCounter == 1) {
476 $reminder_due = "soon_due";
478 else if ($dateCounter == 2) {
479 $reminder_due = "due";
481 else { // $dateCounter == 3
482 $reminder_due = "past_due";
485 // First, deal with deceased patients
486 // (for now will simply not pass the filter, but can add a database item
487 // if ever want to create rules for dead people)
488 // Could also place this function at the total_patients level if wanted.
489 // (But then would lose the option of making rules for dead people)
490 // Note using the dateTarget rather than dateFocus
491 if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
492 continue;
495 // Check if pass filter
496 $passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
497 if ($passFilter === "EXCLUDED") {
498 $passFilter = FALSE;
500 if (!$passFilter) {
501 // increment pass filter counter
502 $dateCounter++;
503 continue;
506 //Check if pass target
507 $passTarget = test_targets($rowPatient['pid'],$rowRule['id'],$i,$dateFocus);
508 if ($passTarget) {
509 // increment pass target counter
510 $pass_target++;
511 // send to reminder results
512 if ($mode == "reminders-all") {
513 // place the completed actions into the reminder return array
514 $actionArray = resolve_action_sql($rowRule['id'],$i);
515 foreach ($actionArray as $action) {
516 $action_plus = $action;
517 $action_plus['due_status'] = "not_due";
518 $action_plus['pid'] = $rowPatient['pid'];
519 $results = reminder_results_integrate($results, $action_plus);
522 break;
524 else {
525 // send to reminder results
526 if ($mode != "report") {
527 // place the actions into the reminder return array
528 $actionArray = resolve_action_sql($rowRule['id'],$i);
529 foreach ($actionArray as $action) {
530 $action_plus = $action;
531 $action_plus['due_status'] = $reminder_due;
532 $action_plus['pid'] = $rowPatient['pid'];
533 $results = reminder_results_integrate($results, $action_plus);
537 $dateCounter++;
541 // Calculate and save the data for the rule
542 $percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
544 // Collect action for title (just use the first one, if more than one)
545 $actionArray = resolve_action_sql($rowRule['id'],$i);
546 $action = $actionArray[0];
547 if ($mode == "report") {
548 $newRow=array('is_sub'=>TRUE,'action_category'=>$action['category'],'action_item'=>$action['item'],'total_patients'=>'','excluded'=>'','pass_filter'=>'','pass_target'=>$pass_target,'percentage'=>$percentage);
549 array_push($results, $newRow);
555 // Return the data
556 return $results;
559 // Test filter of a selected rule on a selected patient
560 // Parameters:
561 // $patient_id - pid of selected patient.
562 // $rule - id(string) of selected rule
563 // $dateTarget - target date.
564 // Return:
565 // boolean (if pass filter then TRUE, if excluded then 'EXCLUDED', if not pass filter then FALSE)
566 function test_filter($patient_id,$rule,$dateTarget) {
568 // Set date to current if not set
569 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
571 // Collect patient information
572 $patientData = getPatientData($patient_id, "sex, DATE_FORMAT(DOB,'%Y %m %d') as DOB_TS");
575 // ----------------- INCLUSIONS -----------------
578 // -------- Age Filter (inclusion) ------------
579 // Calculate patient age in years and months
580 $patientAgeYears = convertDobtoAgeYearDecimal($patientData['DOB_TS'],$dateTarget);
581 $patientAgeMonths = convertDobtoAgeMonthDecimal($patientData['DOB_TS'],$dateTarget);
583 // Min age (year) Filter (assume that there in not more than one of each)
584 $filter = resolve_filter_sql($rule,'filt_age_min');
585 if (!empty($filter)) {
586 $row = $filter[0];
587 if ($row ['method_detail'] == "year") {
588 if ( $row['value'] && ($row['value'] > $patientAgeYears) ) {
589 return false;
592 if ($row ['method_detail'] == "month") {
593 if ( $row['value'] && ($row['value'] > $patientAgeMonths) ) {
594 return false;
598 // Max age (year) Filter (assume that there in not more than one of each)
599 $filter = resolve_filter_sql($rule,'filt_age_max');
600 if (!empty($filter)) {
601 $row = $filter[0];
602 if ($row ['method_detail'] == "year") {
603 if ( $row['value'] && ($row['value'] < $patientAgeYears) ) {
604 return false;
607 if ($row ['method_detail'] == "month") {
608 if ( $row['value'] && ($row['value'] < $patientAgeMonths) ) {
609 return false;
614 // -------- Gender Filter (inclusion) ---------
615 // Gender Filter (assume that there in not more than one of each)
616 $filter = resolve_filter_sql($rule,'filt_sex');
617 if (!empty($filter)) {
618 $row = $filter[0];
619 if ( $row['value'] && ($row['value'] != $patientData['sex']) ) {
620 return false;
624 // -------- Database Filter (inclusion) ------
625 // Database Filter
626 $filter = resolve_filter_sql($rule,'filt_database');
627 if ((!empty($filter)) && !database_check($patient_id,$filter,'',$dateTarget)) return false;
629 // -------- Lists Filter (inclusion) ----
630 // Set up lists filter, which is fully customizable and currently includes diagnoses, meds,
631 // surgeries and allergies.
632 $filter = resolve_filter_sql($rule,'filt_lists');
633 if ((!empty($filter)) && !lists_check($patient_id,$filter,$dateTarget)) return false;
635 // -------- Procedure (labs,imaging,test,procedures,etc) Filter (inlcusion) ----
636 // Procedure Target (includes) (may need to include an interval in the future)
637 $filter = resolve_filter_sql($rule,'filt_proc');
638 if ((!empty($filter)) && !procedure_check($patient_id,$filter,'',$dateTarget)) return false;
641 // ----------------- EXCLUSIONS -----------------
644 // -------- Lists Filter (EXCLUSION) ----
645 // Set up lists EXCLUSION filter, which is fully customizable and currently includes diagnoses, meds,
646 // surgeries and allergies.
647 $filter = resolve_filter_sql($rule,'filt_lists',0);
648 if ((!empty($filter)) && lists_check($patient_id,$filter,$dateTarget)) return "EXCLUDED";
650 // Passed all filters, so return true.
651 return true;
654 // Return an array containing existing group ids for a rule
655 // Parameters:
656 // $rule - id(string) of rule
657 // Return:
658 // array, listing of group ids
659 function returnTargetGroups($rule) {
661 $sql = sqlStatement("SELECT DISTINCT `group_id` FROM `rule_target` " .
662 "WHERE `id`=?", array($rule) );
664 $groups = array();
665 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
666 array_push($groups,$row['group_id']);
668 return $groups;
671 // Test targets of a selected rule on a selected patient
672 // Parameters:
673 // $patient_id - pid of selected patient.
674 // $rule - id(string) of selected rule (if blank, then will ignore grouping)
675 // $group_id - group id of target group
676 // $dateTarget - target date.
677 // Return:
678 // boolean (if target passes then true, otherwise false)
679 function test_targets($patient_id,$rule,$group_id='',$dateTarget) {
681 // -------- Interval Target ----
682 $interval = resolve_target_sql($rule,$group_id,'target_interval');
684 // -------- Database Target ----
685 // Database Target (includes)
686 $target = resolve_target_sql($rule,$group_id,'target_database');
687 if ((!empty($target)) && !database_check($patient_id,$target,$interval,$dateTarget)) return false;
689 // -------- Procedure (labs,imaging,test,procedures,etc) Target ----
690 // Procedure Target (includes)
691 $target = resolve_target_sql($rule,$group_id,'target_proc');
692 if ((!empty($target)) && !procedure_check($patient_id,$target,$interval,$dateTarget)) return false;
694 // -------- Appointment Target ----
695 // Appointment Target (includes) (Specialized functionality for appointment reminders)
696 $target = resolve_target_sql($rule,$group_id,'target_appt');
697 if ((!empty($target)) && appointment_check($patient_id,$dateTarget)) return false;
699 // Passed all target tests, so return true.
700 return true;
703 // Function to return active plans
704 // Parameters:
705 // $type - plan type filter (normal or cqm or blank)
706 // $patient_id - pid of selected patient. (if custom plan does not exist then
707 // will use the default plan)
708 // $configurableOnly - true if only want the configurable (per patient) plans
709 // (ie. ignore cqm plans)
710 // Return: array containing plans
711 function resolve_plans_sql($type='',$patient_id='0',$configurableOnly=FALSE) {
713 if ($configurableOnly) {
714 // Collect all default, configurable (per patient) plans into an array
715 // (ie. ignore the cqm rules)
716 $sql = sqlStatement("SELECT * FROM `clinical_plans` WHERE `pid`=0 AND `cqm_flag` !=1 ORDER BY `id`");
718 else {
719 // Collect all default plans into an array
720 $sql = sqlStatement("SELECT * FROM `clinical_plans` WHERE `pid`=0 ORDER BY `id`");
722 $returnArray= array();
723 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
724 array_push($returnArray,$row);
727 // Now collect the pertinent plans
728 $newReturnArray = array();
730 // Need to select rules (use custom if exist)
731 foreach ($returnArray as $plan) {
732 $customPlan = sqlQuery("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan['id'],$patient_id) );
734 // Decide if use default vs custom plan (preference given to custom plan)
735 if (!empty($customPlan)) {
736 if ($type == "cqm" ) {
737 // For CQM , do not use custom plans (these are to create standard clinic wide reports)
738 $goPlan = $plan;
740 else {
741 // merge the custom plan with the default plan
742 $mergedPlan = array();
743 foreach ($customPlan as $key => $value) {
744 if ($value == NULL && preg_match("/_flag$/",$key)) {
745 // use default setting
746 $mergedPlan[$key] = $plan[$key];
748 else {
749 // use custom setting
750 $mergedPlan[$key] = $value;
753 $goPlan = $mergedPlan;
756 else {
757 $goPlan = $plan;
760 // Use the chosen plan if set
761 if (!empty($type)) {
762 if ($goPlan["${type}_flag"] == 1) {
763 // active, so use the plan
764 array_push($newReturnArray,$goPlan);
767 else {
768 if ($goPlan['normal_flag'] == 1 ||
769 $goPlan['cqm_flag'] == 1) {
770 // active, so use the plan
771 array_push($newReturnArray,$goPlan);
775 $returnArray = $newReturnArray;
777 return $returnArray;
780 // Function to return a specific plan
781 // Parameters:
782 // $plan - id(string) of plan
783 // $patient_id - pid of selected patient. (if set to 0, then will return
784 // the default rule).
785 // Return: array containing a rule
786 function collect_plan($plan,$patient_id='0') {
788 return sqlQuery("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan,$patient_id) );
792 // Function to set a specific plan activity for a specific patient
793 // Parameters:
794 // $plan - id(string) of plan
795 // $type - plan filter (normal,cqm)
796 // $setting - activity of plan (yes,no,default)
797 // $patient_id - pid of selected patient.
798 // Return: nothing
799 function set_plan_activity_patient($plan,$type,$setting,$patient_id) {
801 // Don't allow messing with the default plans here
802 if ($patient_id == "0") {
803 return;
806 // Convert setting
807 if ($setting == "on") {
808 $setting = 1;
810 else if ($setting == "off") {
811 $setting = 0;
813 else { // $setting == "default"
814 $setting = NULL;
817 // Collect patient specific plan, if already exists.
818 $query = "SELECT * FROM `clinical_plans` WHERE `id` = ? AND `pid` = ?";
819 $patient_plan = sqlQuery($query, array($plan,$patient_id) );
821 if (empty($patient_plan)) {
822 // Create a new patient specific plan with flags all set to default
823 $query = "INSERT into `clinical_plans` (`id`, `pid`) VALUES (?,?)";
824 sqlStatement($query, array($plan, $patient_id) );
827 // Update patient specific row
828 $query = "UPDATE `clinical_plans` SET `" . add_escape_custom($type) . "_flag`= ? WHERE id = ? AND pid = ?";
829 sqlStatement($query, array($setting,$plan,$patient_id) );
833 // Function to return active rules
834 // Parameters:
835 // $type - rule filter (active_alert,passive_alert,cqm,amc,patient_reminder)
836 // $patient_id - pid of selected patient. (if custom rule does not exist then
837 // will use the default rule)
838 // $configurableOnly - true if only want the configurable (per patient) rules
839 // (ie. ignore cqm and amc rules)
840 // $plan - collect rules for specific plan
841 // Return: array containing rules
842 function resolve_rules_sql($type='',$patient_id='0',$configurableOnly=FALSE,$plan='') {
844 if ($configurableOnly) {
845 // Collect all default, configurable (per patient) rules into an array
846 // (ie. ignore the cqm and amc rules)
847 $sql = sqlStatement("SELECT * FROM `clinical_rules` WHERE `pid`=0 AND `cqm_flag` !=1 AND `amc_flag` !=1 ORDER BY `id`");
849 else {
850 // Collect all default rules into an array
851 $sql = sqlStatement("SELECT * FROM `clinical_rules` WHERE `pid`=0 ORDER BY `id`");
853 $returnArray= array();
854 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
855 array_push($returnArray,$row);
858 // Now filter rules for plan (if applicable)
859 if (!empty($plan)) {
860 $planReturnArray = array();
861 foreach ($returnArray as $rule) {
862 $standardRule = sqlQuery("SELECT * FROM `clinical_plans_rules` " .
863 "WHERE `plan_id`=? AND `rule_id`=?", array($plan,$rule['id']) );
864 if (!empty($standardRule)) {
865 array_push($planReturnArray,$rule);
868 $returnArray = $planReturnArray;
871 // Now collect the pertinent rules
872 $newReturnArray = array();
874 // Need to select rules (use custom if exist)
875 foreach ($returnArray as $rule) {
876 $customRule = sqlQuery("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule['id'],$patient_id) );
878 // Decide if use default vs custom rule (preference given to custom rule)
879 if (!empty($customRule)) {
880 if ($type == "cqm" || $type == "amc" ) {
881 // For CQM and AMC, do not use custom rules (these are to create standard clinic wide reports)
882 $goRule = $rule;
884 else {
885 // merge the custom rule with the default rule
886 $mergedRule = array();
887 foreach ($customRule as $key => $value) {
888 if ($value == NULL && preg_match("/_flag$/",$key)) {
889 // use default setting
890 $mergedRule[$key] = $rule[$key];
892 else {
893 // use custom setting
894 $mergedRule[$key] = $value;
897 $goRule = $mergedRule;
900 else {
901 $goRule = $rule;
904 // Use the chosen rule if set
905 if (!empty($type)) {
906 if ($goRule["${type}_flag"] == 1) {
907 // active, so use the rule
908 array_push($newReturnArray,$goRule);
911 else {
912 // no filter, so return the rule
913 array_push($newReturnArray,$goRule);
916 $returnArray = $newReturnArray;
918 return $returnArray;
921 // Function to return a specific rule
922 // Parameters:
923 // $rule - id(string) of rule
924 // $patient_id - pid of selected patient. (if set to 0, then will return
925 // the default rule).
926 // Return: array containing a rule
927 function collect_rule($rule,$patient_id='0') {
929 return sqlQuery("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule,$patient_id) );
933 // Function to set a specific rule activity for a specific patient
934 // Parameters:
935 // $rule - id(string) of rule
936 // $type - rule filter (active_alert,passive_alert,cqm,amc,patient_reminder)
937 // $setting - activity of rule (yes,no,default)
938 // $patient_id - pid of selected patient.
939 // Return: nothing
940 function set_rule_activity_patient($rule,$type,$setting,$patient_id) {
942 // Don't allow messing with the default rules here
943 if ($patient_id == "0") {
944 return;
947 // Convert setting
948 if ($setting == "on") {
949 $setting = 1;
951 else if ($setting == "off") {
952 $setting = 0;
954 else { // $setting == "default"
955 $setting = NULL;
958 // Collect patient specific rule, if already exists.
959 $query = "SELECT * FROM `clinical_rules` WHERE `id` = ? AND `pid` = ?";
960 $patient_rule = sqlQuery($query, array($rule,$patient_id) );
962 if (empty($patient_rule)) {
963 // Create a new patient specific rule with flags all set to default
964 $query = "INSERT into `clinical_rules` (`id`, `pid`) VALUES (?,?)";
965 sqlStatement($query, array($rule, $patient_id) );
968 // Update patient specific row
969 $query = "UPDATE `clinical_rules` SET `" . add_escape_custom($type) . "_flag`= ? WHERE id = ? AND pid = ?";
970 sqlStatement($query, array($setting,$rule,$patient_id) );
974 // Function to return applicable reminder dates (relative)
975 // Parameters:
976 // $rule - id(string) of selected rule
977 // $reminder_method - string label of filter type
978 // Return: array containing reminder features
979 function resolve_reminder_sql($rule,$reminder_method) {
980 $sql = sqlStatement("SELECT `method_detail`, `value` FROM `rule_reminder` " .
981 "WHERE `id`=? AND `method`=?", array($rule, $reminder_method) );
983 $returnArray= array();
984 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
985 array_push($returnArray,$row);
987 return $returnArray;
990 // Function to return applicable filters
991 // Parameters:
992 // $rule - id(string) of selected rule
993 // $filter_method - string label of filter type
994 // $include_flag - to allow selection for included or excluded filters
995 // Return: array containing filters
996 function resolve_filter_sql($rule,$filter_method,$include_flag=1) {
997 $sql = sqlStatement("SELECT `method_detail`, `value`, `required_flag` FROM `rule_filter` " .
998 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $filter_method, $include_flag) );
1000 $returnArray= array();
1001 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1002 array_push($returnArray,$row);
1004 return $returnArray;
1007 // Function to return applicable targets
1008 // Parameters:
1009 // $rule - id(string) of selected rule
1010 // $group_id - group id of target group (if blank, then will ignore grouping)
1011 // $target_method - string label of target type
1012 // $include_flag - to allow selection for included or excluded targets
1013 // Return: array containing targets
1014 function resolve_target_sql($rule,$group_id='',$target_method,$include_flag=1) {
1016 if ($group_id) {
1017 $sql = sqlStatement("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
1018 "WHERE `id`=? AND `group_id`=? AND `method`=? AND `include_flag`=?", array($rule, $group_id, $target_method, $include_flag) );
1020 else {
1021 $sql = sqlStatement("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
1022 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $target_method, $include_flag) );
1025 $returnArray= array();
1026 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1027 array_push($returnArray,$row);
1029 return $returnArray;
1032 // Function to return applicable actions
1033 // Parameters:
1034 // $rule - id(string) of selected rule
1035 // $group_id - group id of target group (if blank, then will ignore grouping)
1036 // Return: array containing actions
1037 function resolve_action_sql($rule,$group_id='') {
1039 if ($group_id) {
1040 $sql = sqlStatement("SELECT b.category, b.item, b.clin_rem_link, b.reminder_message, b.custom_flag " .
1041 "FROM `rule_action` as a " .
1042 "JOIN `rule_action_item` as b " .
1043 "ON a.category = b.category AND a.item = b.item " .
1044 "WHERE a.id=? AND a.group_id=?", array($rule,$group_id) );
1046 else {
1047 $sql = sqlStatement("SELECT b.category, b.item, b.value, b.custom_flag " .
1048 "FROM `rule_action` as a " .
1049 "JOIN `rule_action_item` as b " .
1050 "ON a.category = b.category AND a.item = b.item " .
1051 "WHERE a.id=?", array($rule) );
1054 $returnArray= array();
1055 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1056 array_push($returnArray,$row);
1058 return $returnArray;
1061 // Function to check database filters and targets
1062 // Parameters:
1063 // $patient_id - pid of selected patient.
1064 // $filter - array containing filter/target elements
1065 // $interval - used for the interval elements
1066 // $dateTarget - target date. blank is current date.
1067 // Return: boolean if check passed, otherwise false
1068 function database_check($patient_id,$filter,$interval='',$dateTarget='') {
1069 $isMatch = false; //matching flag
1071 // Set date to current if not set
1072 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1074 // Unpackage interval information
1075 // (Assume only one for now and only pertinent for targets)
1076 $intervalType = '';
1077 $intervalValue = '';
1078 if (!empty($interval)) {
1079 $intervalType = $interval[0]['value'];
1080 $intervalValue = $interval[0]['interval'];
1083 foreach( $filter as $row ) {
1084 // Row description
1085 // [0]=>special modes
1086 $temp_df = explode("::",$row['value']);
1088 if ($temp_df[0] == "CUSTOM") {
1089 // Row description
1090 // [0]=>special modes(CUSTOM) [1]=>category [2]=>item [3]=>complete? [4]=>number of hits comparison [5]=>number of hits
1091 if (exist_custom_item($patient_id, $temp_df[1], $temp_df[2], $temp_df[3], $temp_df[4], $temp_df[5], $intervalType, $intervalValue, $dateTarget)) {
1092 // Record the match
1093 $isMatch = true;
1095 else {
1096 // If this is a required entry then return false
1097 if ($row['required_flag']) return false;
1100 else if ($temp_df[0] == "LIFESTYLE") {
1101 // Row description
1102 // [0]=>special modes(LIFESTYLE) [1]=>column [2]=>status
1103 if (exist_lifestyle_item($patient_id, $temp_df[1], $temp_df[2], $dateTarget)) {
1104 // Record the match
1105 $isMatch = true;
1107 else {
1108 // If this is a required entry then return false
1109 if ($row['required_flag']) return false;
1112 else {
1113 // Default mode
1114 // Row description
1115 // [0]=>special modes(BLANK) [1]=>table [2]=>column [3]=>value comparison [4]=>value [5]=>number of hits comparison [6]=>number of hits
1116 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)) {
1117 // Record the match
1118 $isMatch = true;
1120 else {
1121 // If this is a required entry then return false
1122 if ($row['required_flag']) return false;
1127 // return results of check
1128 return $isMatch;
1131 // Function to check procedure filters and targets
1132 // Parameters:
1133 // $patient_id - pid of selected patient.
1134 // $filter - array containing filter/target elements
1135 // $interval - used for the interval elements
1136 // $dateTarget - target date. blank is current date.
1137 // Return: boolean if check passed, otherwise false
1138 function procedure_check($patient_id,$filter,$interval='',$dateTarget='') {
1139 $isMatch = false; //matching flag
1141 // Set date to current if not set
1142 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1144 // Unpackage interval information
1145 // (Assume only one for now and only pertinent for targets)
1146 $intervalType = '';
1147 $intervalValue = '';
1148 if (!empty($interval)) {
1149 $intervalType = $interval[0]['value'];
1150 $intervalValue = $interval[0]['interval'];
1153 foreach( $filter as $row ) {
1154 // Row description
1155 // [0]=>title [1]=>code [2]=>value comparison [3]=>value [4]=>number of hits comparison [5]=>number of hits
1156 // code description
1157 // <type(ICD9,CPT4)>:<identifier>||<type(ICD9,CPT4)>:<identifier>||<identifier> etc.
1158 $temp_df = explode("::",$row['value']);
1159 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)) {
1160 // Record the match
1161 $isMatch = true;
1163 else {
1164 // If this is a required entry then return false
1165 if ($row['required_flag']) return false;
1169 // return results of check
1170 return $isMatch;
1173 // Function to check for appointment
1174 // Parameters:
1175 // $patient_id - pid of selected patient.
1176 // $dateTarget - target date.
1177 // Return: boolean if appt exist, otherwise false
1178 function appointment_check($patient_id,$dateTarget='') {
1179 $isMatch = false; //matching flag
1181 // Set date to current if not set (although should always be set)
1182 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1183 $dateTargetRound = date('Y-m-d',$dateTarget);
1185 // Set current date
1186 $currentDate = date('Y-m-d H:i:s');
1187 $currentDateRound = date('Y-m-d',$dateCurrent);
1189 // Basically, if the appointment is within the current date to the target date,
1190 // then return true. (will not send reminders on same day as appointment)
1191 $sql = sqlStatement("SELECT openemr_postcalendar_events.pc_eid, " .
1192 "openemr_postcalendar_events.pc_title, " .
1193 "openemr_postcalendar_events.pc_eventDate, " .
1194 "openemr_postcalendar_events.pc_startTime, " .
1195 "openemr_postcalendar_events.pc_endTime " .
1196 "FROM openemr_postcalendar_events " .
1197 "WHERE openemr_postcalendar_events.pc_eventDate > ? " .
1198 "AND openemr_postcalendar_events.pc_eventDate <= ? " .
1199 "AND openemr_postcalendar_events.pc_pid = ?", array($currentDate,$dateTarget,$patient_id) );
1201 // return results of check
1203 // TODO: Figure out how to have multiple appointment and changing appointment reminders.
1204 // Plan to send back array of appt info (eid, time, date, etc.)
1205 // to do this.
1206 if (sqlNumRows($sql) > 0) {
1207 $isMatch = true;
1210 return $isMatch;
1213 // Function to check lists filters and targets
1214 // Customizable and currently includes diagnoses, medications,
1215 // allergies and surgeries.
1216 // Parameters:
1217 // $patient_id - pid of selected patient.
1218 // $filter - array containing lists filter/target elements
1219 // $dateTarget - target date. blank is current date.
1220 // Return: boolean if check passed, otherwise false
1221 function lists_check($patient_id,$filter,$dateTarget) {
1222 $isMatch = false; //matching flag
1224 // Set date to current if not set
1225 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1227 foreach ( $filter as $row ) {
1228 if (exist_lists_item($patient_id, $row['method_detail'], $row['value'], $dateTarget)) {
1229 // Record the match
1230 $isMatch = true;
1232 else {
1233 // If this is a required entry then return false
1234 if ($row['required_flag']) return false;
1238 // return results of check
1239 return $isMatch;
1242 // Function to check for existance of data in database for a patient
1243 // Parameters:
1244 // $patient_id - pid of selected patient.
1245 // $table - selected mysql table
1246 // $column - selected mysql column
1247 // $data_comp - data comparison (eq,ne,gt,ge,lt,le)
1248 // $data - selected data in the mysql database
1249 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1250 // $num_items_thres - number of items threshold
1251 // $intervalType - type of interval (ie. year)
1252 // $intervalValue - searched for within this many times of the interval type
1253 // $dateTarget - target date.
1254 // Return: boolean if check passed, otherwise false
1255 function exist_database_item($patient_id,$table,$column='',$data_comp,$data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
1257 // Set date to current if not set
1258 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1260 // Collect the correct column label for patient id in the table
1261 $patient_id_label = collect_database_label('pid',$table);
1263 // Get the interval sql query string
1264 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1266 // If just checking for existence (ie. data is empty),
1267 // then simply set the comparison operator to ne.
1268 if (empty($data)) {
1269 $data_comp = "ne";
1272 // get the appropriate sql comparison operator
1273 $compSql = convertCompSql($data_comp);
1275 // check for items
1276 if (empty($column)) {
1277 // simple search for any table entries
1278 $sql = sqlStatement("SELECT * " .
1279 "FROM `" . add_escape_custom($table) . "` " .
1280 "WHERE `" . add_escape_custom($patient_id_label) . "`=?", array($patient_id) );
1282 else {
1283 // search for number of specific items
1284 $sql = sqlStatement("SELECT `" . add_escape_custom($column) . "` " .
1285 "FROM `" . add_escape_custom($table) . "` " .
1286 "WHERE `" . add_escape_custom($column) ."`" . $compSql . "? " .
1287 "AND `" . add_escape_custom($patient_id_label) . "`=? " .
1288 $dateSql, array($data,$patient_id) );
1291 // See if number of returned items passes the comparison
1292 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1295 // Function to check for existence of procedure(s) for a patient
1296 // Parameters:
1297 // $patient_id - pid of selected patient.
1298 // $proc_title - procedure title
1299 // $proc_code - procedure identifier code (array of <type(ICD9,CPT4)>:<identifier>||<type(ICD9,CPT4)>:<identifier>||<identifier> etc.)
1300 // $result_comp - results comparison (eq,ne,gt,ge,lt,le)
1301 // $result_data - results data
1302 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1303 // $num_items_thres - number of items threshold
1304 // $intervalType - type of interval (ie. year)
1305 // $intervalValue - searched for within this many times of the interval type
1306 // $dateTarget - target date.
1307 // Return: boolean if check passed, otherwise false
1308 function exist_procedure_item($patient_id,$proc_title,$proc_code,$result_comp,$result_data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
1310 // Set date to current if not set
1311 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1313 // Set the table exception (for looking up pertinent date and pid sql columns)
1314 $table = "PROCEDURE-EXCEPTION";
1316 // Collect the correct column label for patient id in the table
1317 $patient_id_label = collect_database_label('pid',$table);
1319 // Get the interval sql query string
1320 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1322 // If just checking for existence (ie result_data is empty),
1323 // then simply set the comparison operator to ne.
1324 if (empty($result_data)) {
1325 $result_comp = "ne";
1328 // get the appropriate sql comparison operator
1329 $compSql = convertCompSql($result_comp);
1331 // explode the code array
1332 $codes= array();
1333 if (!empty($proc_code)) {
1334 $codes = explode("||",$proc_code);
1336 else {
1337 $codes[0] = '';
1340 // ensure proc_title is at least blank
1341 if (empty($proc_title)) {
1342 $proc_title = '';
1345 // collect specific items (use both title and/or codes) that fulfill request
1346 $sqlBindArray=array();
1347 $sql_query = "SELECT procedure_result.result " .
1348 "FROM `procedure_type`, " .
1349 "`procedure_order`, " .
1350 "`procedure_report`, " .
1351 "`procedure_result` " .
1352 "WHERE procedure_type.procedure_type_id = procedure_order.procedure_type_id " .
1353 "AND procedure_order.procedure_order_id = procedure_report.procedure_order_id " .
1354 "AND procedure_report.procedure_report_id = procedure_result.procedure_report_id " .
1355 "AND ";
1356 foreach ($codes as $tem) {
1357 $sql_query .= "( ( (procedure_type.standard_code = ? AND procedure_type.standard_code != '') " .
1358 "OR (procedure_type.procedure_code = ? AND procedure_type.procedure_code != '') ) OR ";
1359 array_push($sqlBindArray,$tem,$tem);
1361 $sql_query .= "(procedure_type.name = ? AND procedure_type.name != '') ) " .
1362 "AND procedure_result.result " . $compSql . " ? " .
1363 "AND " . add_escape_custom($patient_id_label) . " = ? " . $dateSql;
1364 array_push($sqlBindArray,$proc_title,$result_data,$patient_id);
1365 $sql = sqlStatement($sql_query,$sqlBindArray);
1367 // See if number of returned items passes the comparison
1368 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1371 // Function to check for existance of data for a patient in the rule_patient_data table
1372 // Parameters:
1373 // $patient_id - pid of selected patient.
1374 // $category - label in category column
1375 // $item - label in item column
1376 // $complete - label in complete column (YES,NO, or blank)
1377 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1378 // $num_items_thres - number of items threshold
1379 // $intervalType - type of interval (ie. year)
1380 // $intervalValue - searched for within this many times of the interval type
1381 // $dateTarget - target date.
1382 // Return: boolean if check passed, otherwise false
1383 function exist_custom_item($patient_id,$category,$item,$complete,$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget) {
1385 // Set the table
1386 $table = 'rule_patient_data';
1388 // Collect the correct column label for patient id in the table
1389 $patient_id_label = collect_database_label('pid',$table);
1391 // Get the interval sql query string
1392 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1394 // search for number of specific items
1395 $sql = sqlStatement("SELECT `result` " .
1396 "FROM `" . add_escape_custom($table) . "` " .
1397 "WHERE `category`=? " .
1398 "AND `item`=? " .
1399 "AND `complete`=? " .
1400 "AND `" . add_escape_custom($patient_id_label) . "`=? " .
1401 $dateSql, array($category,$item,$complete,$patient_id) );
1403 // See if number of returned items passes the comparison
1404 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1407 // Function to check for existance of data for a patient in lifestyle section
1408 // Parameters:
1409 // $patient_id - pid of selected patient.
1410 // $lifestyle - selected label of mysql column of patient history
1411 // $status - specific status of selected lifestyle element
1412 // $dateTarget - target date. blank is current date.
1413 // Return: boolean if check passed, otherwise false
1414 function exist_lifestyle_item($patient_id,$lifestyle,$status,$dateTarget) {
1416 // Set date to current if not set
1417 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1419 // Collect pertinent history data
1420 $history = getHistoryData($patient_id, $lifestyle,'',$dateTarget);
1422 // See if match
1423 $stringFlag = strstr($history[$lifestyle], "|".$status);
1424 if (empty($status)) {
1425 // Only ensuring any data has been entered into the field
1426 $stringFlag = true;
1428 if ( $history[$lifestyle] &&
1429 $history[$lifestyle] != '|0|' &&
1430 $stringFlag ) {
1431 return true;
1433 else {
1434 return false;
1438 // Function to check for lists item of a patient
1439 // Fully customizable and includes diagnoses, medications,
1440 // allergies, and surgeries.
1441 // Parameters:
1442 // $patient_id - pid of selected patient.
1443 // $type - type (medical_problem, allergy, medication, etc)
1444 // $value - value searching for
1445 // $dateTarget - target date. blank is current date.
1446 // Return: boolean if check passed, otherwise false
1447 function exist_lists_item($patient_id,$type,$value,$dateTarget) {
1449 // Set date to current if not set
1450 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1452 // Attempt to explode the value into a code type and code (if applicable)
1453 $value_array = explode("::",$value);
1454 if (count($value_array) == 2) {
1456 // Collect the code type and code
1457 $code_type = $value_array[0];
1458 $code = $value_array[1];
1460 if ($code_type=='CUSTOM') {
1461 // Deal with custom code type first (title column in lists table)
1462 $response = sqlQuery("SELECT * FROM `lists` " .
1463 "WHERE `type`=? " .
1464 "AND `pid`=? " .
1465 "AND `title`=? " .
1466 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1467 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$code,$dateTarget,$dateTarget,$dateTarget) );
1468 if (!empty($response)) return true;
1470 else {
1471 // Deal with the set code types (diagnosis column in lists table)
1472 $response = sqlQuery("SELECT * FROM `lists` " .
1473 "WHERE `type`=? " .
1474 "AND `pid`=? " .
1475 "AND `diagnosis` LIKE ? " .
1476 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1477 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,"%".$code_type.":".$code."%",$dateTarget,$dateTarget,$dateTarget) );
1478 if (!empty($response)) return true;
1481 else { // count($value_array) == 1
1482 // Search the title column in lists table
1483 // Yes, this is essentially the same as the code type listed as CUSTOM above. This provides flexibility and will ensure compatibility.
1484 $response = sqlQuery("SELECT * FROM `lists` " .
1485 "WHERE `type`=? " .
1486 "AND `pid`=? " .
1487 "AND `title`=? ".
1488 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1489 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$value,$dateTarget,$dateTarget,$dateTarget) );
1490 if (!empty($response)) return true;
1493 return false;
1496 // Function to return part of sql query to deal with interval
1497 // Parameters:
1498 // $table - selected mysql table (or EXCEPTION(s))
1499 // $intervalType - type of interval (ie. year)
1500 // $intervalValue - searched for within this many times of the interval type
1501 // $dateTarget - target date.
1502 // Return: string containing pertinent date interval filter for mysql query
1503 function sql_interval_string($table,$intervalType,$intervalValue,$dateTarget) {
1505 $dateSql="";
1507 // Collect the correct column label for date in the table
1508 $date_label = collect_database_label('date',$table);
1510 // Deal with interval
1511 if (!empty($intervalType)) {
1512 switch($intervalType) {
1513 case "year":
1514 $dateSql = "AND (" . add_escape_custom($date_label) .
1515 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1516 "', INTERVAL " . add_escape_custom($intervalValue) .
1517 " YEAR) AND '" . add_escape_custom($dateTarget) . "') ";
1518 break;
1519 case "month":
1520 $dateSql = "AND (" . add_escape_custom($date_label) .
1521 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1522 "', INTERVAL " . add_escape_custom($intervalValue) .
1523 " MONTH) AND '" . add_escape_custom($dateTarget) . "') ";
1524 break;
1525 case "week":
1526 $dateSql = "AND (" . add_escape_custom($date_label) .
1527 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1528 "', INTERVAL " . add_escape_custom($intervalValue) .
1529 " WEEK) AND '" . add_escape_custom($dateTarget) . "') ";
1530 break;
1531 case "day":
1532 $dateSql = "AND (" . add_escape_custom($date_label) .
1533 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1534 "', INTERVAL " . add_escape_custom($intervalValue) .
1535 " DAY) AND '" . add_escape_custom($dateTarget) . "') ";
1536 break;
1537 case "hour":
1538 $dateSql = "AND (" . add_escape_custom($date_label) .
1539 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1540 "', INTERVAL " . add_escape_custom($intervalValue) .
1541 " HOUR) AND '" . add_escape_custom($dateTarget) . "') ";
1542 break;
1543 case "minute":
1544 $dateSql = "AND (" . add_escape_custom($date_label) .
1545 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1546 "', INTERVAL " . add_escape_custom($intervalValue) .
1547 " MINUTE) AND '" . add_escape_custom($dateTarget) . "') ";
1548 break;
1549 case "second":
1550 $dateSql = "AND (" . add_escape_custom($date_label) .
1551 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1552 "', INTERVAL " . add_escape_custom($intervalValue) .
1553 " SECOND) AND '" . add_escape_custom($dateTarget) . "') ";
1554 break;
1555 case "flu_season":
1556 // Flu season to be hard-coded as September thru February
1557 // (Should make this modifiable in the future)
1558 // ($intervalValue is not used)
1559 $dateArray = explode("-",$dateTarget);
1560 $Year = $dateArray[0];
1561 $dateThisYear = $Year . "-09-01";
1562 $dateLastYear = ($Year-1) . "-09-01";
1563 $dateSql =" " .
1564 "AND ((" .
1565 "MONTH('" . add_escape_custom($dateTarget) . "') < 9 " .
1566 "AND " . add_escape_custom($date_label) . " >= '" . $dateLastYear . "' ) " .
1567 "OR (" .
1568 "MONTH('" . add_escape_custom($dateTarget) . "') >= 9 " .
1569 "AND " . add_escape_custom($date_label) . " >= '" . $dateThisYear . "' ))" .
1570 "AND " . add_escape_custom($date_label) . " <= '" . add_escape_custom($dateTarget) . "' ";
1571 break;
1574 else {
1575 $dateSql = "AND " . add_escape_custom($date_label) .
1576 " <= '" . add_escape_custom($dateTarget) . "' ";
1579 // return the sql interval string
1580 return $dateSql;
1583 // Function to collect generic column labels from tables.
1584 // It currently works for date and pid.
1585 // Will need to expand this as algorithm grows.
1586 // Parameters:
1587 // $label - element (pid or date)
1588 // $table - selected mysql table (or EXCEPTION(s))
1589 // Return: string containing official label of selected element
1590 function collect_database_label($label,$table) {
1592 if ($table == 'PROCEDURE-EXCEPTION') {
1593 // return cell to get procedure collection
1594 // special case since reuqires joing of multiple
1595 // tables to get this value
1596 if ($label == "pid") {
1597 $returnedLabel = "procedure_order.patient_id";
1599 else if ($label == "date") {
1600 $returnedLabel = "procedure_report.date_collected";
1602 else {
1603 // unknown label, so return the original label
1604 $returnedLabel = $label;
1607 else if ($table == 'immunizations') {
1608 // return requested label for immunization table
1609 if ($label == "pid") {
1610 $returnedLabel = "patient_id";
1612 else if ($label == "date") {
1613 $returnedLabel = "`administered_date`";
1615 else {
1616 // unknown label, so return the original label
1617 $returnedLabel = $label;
1620 else {
1621 // return requested label for default tables
1622 if ($label == "pid") {
1623 $returnedLabel = "pid";
1625 else if ($label == "date") {
1626 $returnedLabel = "`date`";
1628 else {
1629 // unknown label, so return the original label
1630 $returnedLabel = $label;
1634 return $returnedLabel;
1637 // Simple function to avoid processing of duplicate actions
1638 // Parameters:
1639 // $actions - 2-dimensional array with all current active targets
1640 // $action - array of selected target to test for duplicate
1641 // Return: boolean, true if duplicate, false if not duplicate
1642 function is_duplicate_action($actions,$action) {
1643 foreach ($actions as $row) {
1644 if ($row['category'] == $action['category'] &&
1645 $row['item'] == $action['item'] &&
1646 $row['value'] == $action['value']) {
1647 // Is a duplicate
1648 return true;
1652 // Not a duplicate
1653 return false;
1656 // Calculate the reminder dates.
1657 // Parameters:
1658 // $rule - id(string) of selected rule
1659 // $dateTarget - target date. If blank then will test with current date as target.
1660 // $type - either 'patient_reminder' or 'clinical_reminder'
1661 // For now, will always return an array of 3 dates:
1662 // first date is before the target date (past_due) (default of 1 month)
1663 // second date is the target date (due)
1664 // third date is after the target date (soon_due) (default of 2 weeks)
1665 function calculate_reminder_dates($rule, $dateTarget='',$type) {
1667 // Set date to current if not set
1668 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1670 // Collect the current date settings (to ensure not skip)
1671 $res = resolve_reminder_sql($rule, $type.'_current');
1672 if (!empty($res)) {
1673 $row = $res[0];
1674 if ($row ['method_detail'] == "SKIP") {
1675 $dateTarget = "SKIP";
1679 // Collect the past_due date
1680 $past_due_date == "";
1681 $res = resolve_reminder_sql($rule, $type.'_post');
1682 if (!empty($res)) {
1683 $row = $res[0];
1684 if ($row ['method_detail'] == "week") {
1685 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " week"));
1687 if ($row ['method_detail'] == "month") {
1688 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " month"));
1690 if ($row ['method_detail'] == "hour") {
1691 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
1693 if ($row ['method_detail'] == "SKIP") {
1694 $past_due_date = "SKIP";
1697 else {
1698 // empty settings, so use default of one month
1699 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -1 month"));
1702 // Collect the soon_due date
1703 $soon_due_date == "";
1704 $res = resolve_reminder_sql($rule, $type.'_pre');
1705 if (!empty($res)) {
1706 $row = $res[0];
1707 if ($row ['method_detail'] == "week") {
1708 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " week"));
1710 if ($row ['method_detail'] == "month") {
1711 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " month"));
1713 if ($row ['method_detail'] == "hour") {
1714 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
1716 if ($row ['method_detail'] == "SKIP") {
1717 $soon_due_date = "SKIP";
1720 else {
1721 // empty settings, so use default of one month
1722 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +2 week"));
1725 // Return the array of three dates
1726 return array($soon_due_date,$dateTarget,$past_due_date);
1729 // Adds an action into the reminder array
1730 // Parameters:
1731 // $reminderOldArray - Contains the current array of reminders
1732 // $reminderNew - Array of a new reminder
1733 // Return:
1734 // An array of reminders
1735 function reminder_results_integrate($reminderOldArray, $reminderNew) {
1737 $results = array();
1739 // If reminderArray is empty, then insert new reminder
1740 if (empty($reminderOldArray)) {
1741 array_push($results, $reminderNew);
1742 return $results;
1745 // If duplicate reminder, then replace the old one
1746 $duplicate = false;
1747 foreach ($reminderOldArray as $reminderOld) {
1748 if ( $reminderOld['pid'] == $reminderNew['pid'] &&
1749 $reminderOld['category'] == $reminderNew['category'] &&
1750 $reminderOld['item'] == $reminderNew['item']) {
1751 array_push($results, $reminderNew);
1752 $duplicate = true;
1754 else {
1755 array_push($results, $reminderOld);
1759 // If a new reminder, then insert the new reminder
1760 if (!$duplicate) {
1761 array_push($results, $reminderNew);
1764 return $results;
1767 // Compares number of items with requested comparison operator
1768 // Parameters:
1769 // $comp - Comparison operator(eq,ne,gt,ge,lt,le)
1770 // $thres - Threshold used in comparison
1771 // $num_items - Number of items
1772 // Return:
1773 // Boolean of comparison results
1774 function itemsNumberCompare($comp, $thres, $num_items) {
1776 if ( ($comp == "eq") && ($num_items == $thres) ) {
1777 return true;
1779 else if ( ($comp == "ne") && ($num_items != $thres) && ($num_items > 0) ) {
1780 return true;
1782 else if ( ($comp == "gt") && ($num_items > $thres) ) {
1783 return true;
1785 else if ( ($comp == "ge") && ($num_items >= $thres) ) {
1786 return true;
1788 else if ( ($comp == "lt") && ($num_items < $thres) && ($num_items > 0) ) {
1789 return true;
1791 else if ( ($comp == "le") && ($num_items <= $thres) && ($num_items > 0) ) {
1792 return true;
1794 else {
1795 return false;
1799 // Converts a text comparison operator to sql equivalent
1800 // Parameters:
1801 // $comp - Comparison operator(eq,ne,gt,ge,lt,le)
1802 // Return:
1803 // String containing sql compatible comparison operator
1804 function convertCompSql($comp) {
1806 if ($comp == "eq") {
1807 return "=";
1809 else if ($comp == "ne") {
1810 return "!=";
1812 else if ($comp == "gt") {
1813 return ">";
1815 else if ($comp == "ge") {
1816 return ">=";
1818 else if ($comp == "lt") {
1819 return "<";
1821 else { // ($comp == "le")
1822 return "<=";
1826 // Function to find age in years (with decimal) on the target date
1827 // Parameters:
1828 // $dob - date of birth
1829 // $target - date to calculate age on
1830 // Return: decimal, years(decimal) from dob to target(date)
1831 function convertDobtoAgeYearDecimal($dob,$target) {
1833 // Prepare dob (Y M D)
1834 $dateDOB = explode(" ",$dob);
1836 // Prepare target (Y-M-D H:M:S)
1837 $dateTargetTemp = explode(" ",$target);
1838 $dateTarget = explode("-",$dateTargetTemp[0]);
1840 // Collect differences
1841 $iDiffYear = $dateTarget[0] - $dateDOB[0];
1842 $iDiffMonth = $dateTarget[1] - $dateDOB[1];
1843 $iDiffDay = $dateTarget[2] - $dateDOB[2];
1845 // If birthday has not happen yet for this year, subtract 1.
1846 if ($iDiffMonth < 0 || ($iDiffMonth == 0 && $iDiffDay < 0))
1848 $iDiffYear--;
1851 // Ensure diffYear is not less than 0
1852 if ($iDiffYear < 0) $iDiffYear = 0;
1854 return $iDiffYear;
1857 // Function to find age in months (with decimal) on the target date
1858 // Parameters:
1859 // $dob - date of birth
1860 // $target - date to calculate age on
1861 // Return: decimal, months(decimal) from dob to target(date)
1862 function convertDobtoAgeMonthDecimal($dob,$target) {
1864 // Prepare dob (Y M D)
1865 $dateDOB = explode(" ",$dob);
1867 // Prepare target (Y-M-D H:M:S)
1868 $dateTargetTemp = explode(" ",$target);
1869 $dateTarget = explode("-",$dateTargetTemp[0]);
1871 // Collect differences
1872 $iDiffYear = $dateTarget[0] - $dateDOB[0];
1873 $iDiffMonth = $dateTarget[1] - $dateDOB[1];
1874 $iDiffDay = $dateTarget[2] - $dateDOB[2];
1876 // If birthday has not happen yet for this year, subtract 1.
1877 if ($iDiffMonth < 0 || ($iDiffMonth == 0 && $iDiffDay < 0))
1879 $iDiffYear--;
1882 // Ensure diffYear is not less than 0
1883 if ($iDiffYear < 0) $iDiffYear = 0;
1885 return (12 * $iDiffYear) + $iDiffMonth;
1888 // Function to calculate the percentage
1889 // Parameters:
1890 // $pass_filter - number of patients that pass filter
1891 // $exclude_filter - number of patients that are excluded
1892 // $pass_target - number of patients that pass target
1893 // Return: String of a number formatted into a percentage
1894 function calculate_percentage($pass_filt,$exclude_filt,$pass_targ) {
1895 if ($pass_filt > 0) {
1896 $perc = number_format(($pass_targ/($pass_filt-$exclude_filt))*100) . xl('%');
1898 else {
1899 $perc = "0". xl('%');
1901 return $perc;