CDR engine. Allow procedure codes:
[openemr.git] / library / clinical_rules.php
blobd4e42493a627d0b8d0b88e13cb34a30e1a70f521
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 foreach( $patientData as $rowPatient ) {
356 // Count the total patients
357 $total_patients++;
359 $dateCounter = 1; // for reminder mode to keep track of which date checking
360 foreach ( $target_dates as $dateFocus ) {
362 //Skip if date is set to SKIP
363 if ($dateFocus == "SKIP") {
364 $dateCounter++;
365 continue;
368 //Set date counter and reminder token (applicable for reminders only)
369 if ($dateCounter == 1) {
370 $reminder_due = "soon_due";
372 else if ($dateCounter == 2) {
373 $reminder_due = "due";
375 else { // $dateCounter == 3
376 $reminder_due = "past_due";
379 // First, deal with deceased patients
380 // (for now will simply not pass the filter, but can add a database item
381 // if ever want to create rules for dead people)
382 // Could also place this function at the total_patients level if wanted.
383 // (But then would lose the option of making rules for dead people)
384 // Note using the dateTarget rather than dateFocus
385 if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
386 continue;
389 // Check if pass filter
390 $passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
391 if ($passFilter === "EXCLUDED") {
392 // increment EXCLUDED and pass_filter counters
393 // and set as FALSE for reminder functionality.
394 $pass_filter++;
395 $exclude_filter++;
396 $passFilter = FALSE;
398 if ($passFilter) {
399 // increment pass filter counter
400 $pass_filter++;
402 else {
403 $dateCounter++;
404 continue;
407 // Check if pass target
408 $passTarget = test_targets($rowPatient['pid'],$rowRule['id'],'',$dateFocus);
409 if ($passTarget) {
410 // increment pass target counter
411 $pass_target++;
412 // send to reminder results
413 if ($mode == "reminders-all") {
414 // place the completed actions into the reminder return array
415 $actionArray = resolve_action_sql($rowRule['id'],'1');
416 foreach ($actionArray as $action) {
417 $action_plus = $action;
418 $action_plus['due_status'] = "not_due";
419 $action_plus['pid'] = $rowPatient['pid'];
420 $results = reminder_results_integrate($results, $action_plus);
423 break;
425 else {
426 // send to reminder results
427 if ($mode != "report") {
428 // place the uncompleted actions into the reminder return array
429 $actionArray = resolve_action_sql($rowRule['id'],'1');
430 foreach ($actionArray as $action) {
431 $action_plus = $action;
432 $action_plus['due_status'] = $reminder_due;
433 $action_plus['pid'] = $rowPatient['pid'];
434 $results = reminder_results_integrate($results, $action_plus);
438 $dateCounter++;
442 // Calculate and save the data for the rule
443 $percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
444 if ($mode == "report") {
445 $newRow=array('is_main'=>TRUE,'total_patients'=>$total_patients,'excluded'=>$exclude_filter,'pass_filter'=>$pass_filter,'pass_target'=>$pass_target,'percentage'=>$percentage);
446 $newRow=array_merge($newRow,$rowRule);
447 array_push($results, $newRow);
450 // Find the number of target groups, and go through each one if more than one
451 $targetGroups = returnTargetGroups($rowRule['id']);
452 if (count($targetGroups) > 1) {
453 $firstGroup = true;
454 foreach ($targetGroups as $i) {
456 // skip first group if not in report mode
457 // (this is because first group was already queried above)
458 if ($mode != "report" && $firstGroup) {
459 $firstGroup = false;
460 continue;
463 //Reset the target counter
464 $pass_target = 0;
466 foreach( $patientData as $rowPatient ) {
468 $dateCounter = 1; // for reminder mode to keep track of which date checking
469 foreach ( $target_dates as $dateFocus ) {
471 //Skip if date is set to SKIP
472 if ($dateFocus == "SKIP") {
473 $dateCounter++;
474 continue;
477 //Set date counter and reminder token (applicable for reminders only)
478 if ($dateCounter == 1) {
479 $reminder_due = "soon_due";
481 else if ($dateCounter == 2) {
482 $reminder_due = "due";
484 else { // $dateCounter == 3
485 $reminder_due = "past_due";
488 // First, deal with deceased patients
489 // (for now will simply not pass the filter, but can add a database item
490 // if ever want to create rules for dead people)
491 // Could also place this function at the total_patients level if wanted.
492 // (But then would lose the option of making rules for dead people)
493 // Note using the dateTarget rather than dateFocus
494 if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
495 continue;
498 // Check if pass filter
499 $passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
500 if ($passFilter === "EXCLUDED") {
501 $passFilter = FALSE;
503 if (!$passFilter) {
504 // increment pass filter counter
505 $dateCounter++;
506 continue;
509 //Check if pass target
510 $passTarget = test_targets($rowPatient['pid'],$rowRule['id'],$i,$dateFocus);
511 if ($passTarget) {
512 // increment pass target counter
513 $pass_target++;
514 // send to reminder results
515 if ($mode == "reminders-all") {
516 // place the completed actions into the reminder return array
517 $actionArray = resolve_action_sql($rowRule['id'],$i);
518 foreach ($actionArray as $action) {
519 $action_plus = $action;
520 $action_plus['due_status'] = "not_due";
521 $action_plus['pid'] = $rowPatient['pid'];
522 $results = reminder_results_integrate($results, $action_plus);
525 break;
527 else {
528 // send to reminder results
529 if ($mode != "report") {
530 // place the actions into the reminder return array
531 $actionArray = resolve_action_sql($rowRule['id'],$i);
532 foreach ($actionArray as $action) {
533 $action_plus = $action;
534 $action_plus['due_status'] = $reminder_due;
535 $action_plus['pid'] = $rowPatient['pid'];
536 $results = reminder_results_integrate($results, $action_plus);
540 $dateCounter++;
544 // Calculate and save the data for the rule
545 $percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
547 // Collect action for title (just use the first one, if more than one)
548 $actionArray = resolve_action_sql($rowRule['id'],$i);
549 $action = $actionArray[0];
550 if ($mode == "report") {
551 $newRow=array('is_sub'=>TRUE,'action_category'=>$action['category'],'action_item'=>$action['item'],'total_patients'=>'','excluded'=>'','pass_filter'=>'','pass_target'=>$pass_target,'percentage'=>$percentage);
552 array_push($results, $newRow);
558 // Return the data
559 return $results;
562 // Test filter of a selected rule on a selected patient
563 // Parameters:
564 // $patient_id - pid of selected patient.
565 // $rule - id(string) of selected rule
566 // $dateTarget - target date.
567 // Return:
568 // boolean (if pass filter then TRUE, if excluded then 'EXCLUDED', if not pass filter then FALSE)
569 function test_filter($patient_id,$rule,$dateTarget) {
571 // Set date to current if not set
572 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
574 // Collect patient information
575 $patientData = getPatientData($patient_id, "sex, DATE_FORMAT(DOB,'%Y %m %d') as DOB_TS");
578 // ----------------- INCLUSIONS -----------------
581 // -------- Age Filter (inclusion) ------------
582 // Calculate patient age in years and months
583 $patientAgeYears = convertDobtoAgeYearDecimal($patientData['DOB_TS'],$dateTarget);
584 $patientAgeMonths = convertDobtoAgeMonthDecimal($patientData['DOB_TS'],$dateTarget);
586 // Min age (year) Filter (assume that there in not more than one of each)
587 $filter = resolve_filter_sql($rule,'filt_age_min');
588 if (!empty($filter)) {
589 $row = $filter[0];
590 if ($row ['method_detail'] == "year") {
591 if ( $row['value'] && ($row['value'] > $patientAgeYears) ) {
592 return false;
595 if ($row ['method_detail'] == "month") {
596 if ( $row['value'] && ($row['value'] > $patientAgeMonths) ) {
597 return false;
601 // Max age (year) Filter (assume that there in not more than one of each)
602 $filter = resolve_filter_sql($rule,'filt_age_max');
603 if (!empty($filter)) {
604 $row = $filter[0];
605 if ($row ['method_detail'] == "year") {
606 if ( $row['value'] && ($row['value'] < $patientAgeYears) ) {
607 return false;
610 if ($row ['method_detail'] == "month") {
611 if ( $row['value'] && ($row['value'] < $patientAgeMonths) ) {
612 return false;
617 // -------- Gender Filter (inclusion) ---------
618 // Gender Filter (assume that there in not more than one of each)
619 $filter = resolve_filter_sql($rule,'filt_sex');
620 if (!empty($filter)) {
621 $row = $filter[0];
622 if ( $row['value'] && ($row['value'] != $patientData['sex']) ) {
623 return false;
627 // -------- Database Filter (inclusion) ------
628 // Database Filter
629 $filter = resolve_filter_sql($rule,'filt_database');
630 if ((!empty($filter)) && !database_check($patient_id,$filter,'',$dateTarget)) return false;
632 // -------- Lists Filter (inclusion) ----
633 // Set up lists filter, which is fully customizable and currently includes diagnoses, meds,
634 // surgeries and allergies.
635 $filter = resolve_filter_sql($rule,'filt_lists');
636 if ((!empty($filter)) && !lists_check($patient_id,$filter,$dateTarget)) return false;
639 // ----------------- EXCLUSIONS -----------------
642 // -------- Lists Filter (EXCLUSION) ----
643 // Set up lists EXCLUSION filter, which is fully customizable and currently includes diagnoses, meds,
644 // surgeries and allergies.
645 $filter = resolve_filter_sql($rule,'filt_lists',0);
646 if ((!empty($filter)) && lists_check($patient_id,$filter,$dateTarget)) return "EXCLUDED";
648 // Passed all filters, so return true.
649 return true;
652 // Return an array containing existing group ids for a rule
653 // Parameters:
654 // $rule - id(string) of rule
655 // Return:
656 // array, listing of group ids
657 function returnTargetGroups($rule) {
659 $sql = sqlStatement("SELECT DISTINCT `group_id` FROM `rule_target` " .
660 "WHERE `id`=?", array($rule) );
662 $groups = array();
663 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
664 array_push($groups,$row['group_id']);
666 return $groups;
669 // Test targets of a selected rule on a selected patient
670 // Parameters:
671 // $patient_id - pid of selected patient.
672 // $rule - id(string) of selected rule (if blank, then will ignore grouping)
673 // $group_id - group id of target group
674 // $dateTarget - target date.
675 // Return:
676 // boolean (if target passes then true, otherwise false)
677 function test_targets($patient_id,$rule,$group_id='',$dateTarget) {
679 // -------- Interval Target ----
680 $interval = resolve_target_sql($rule,$group_id,'target_interval');
682 // -------- Database Target ----
683 // Database Target (includes)
684 $target = resolve_target_sql($rule,$group_id,'target_database');
685 if ((!empty($target)) && !database_check($patient_id,$target,$interval,$dateTarget)) return false;
687 // -------- Procedure (labs,imaging,test,procedures,etc) Target ----
688 // Procedure Target (includes)
689 $target = resolve_target_sql($rule,$group_id,'target_proc');
690 if ((!empty($target)) && !procedure_check($patient_id,$target,$interval,$dateTarget)) return false;
692 // -------- Appointment Target ----
693 // Appointment Target (includes) (Specialized functionality for appointment reminders)
694 $target = resolve_target_sql($rule,$group_id,'target_appt');
695 if ((!empty($target)) && appointment_check($patient_id,$dateTarget)) return false;
697 // Passed all target tests, so return true.
698 return true;
701 // Function to return active plans
702 // Parameters:
703 // $type - plan type filter (normal or cqm or blank)
704 // $patient_id - pid of selected patient. (if custom plan does not exist then
705 // will use the default plan)
706 // $configurableOnly - true if only want the configurable (per patient) plans
707 // (ie. ignore cqm plans)
708 // Return: array containing plans
709 function resolve_plans_sql($type='',$patient_id='0',$configurableOnly=FALSE) {
711 if ($configurableOnly) {
712 // Collect all default, configurable (per patient) plans into an array
713 // (ie. ignore the cqm rules)
714 $sql = sqlStatement("SELECT * FROM `clinical_plans` WHERE `pid`=0 AND `cqm_flag` !=1 ORDER BY `id`");
716 else {
717 // Collect all default plans into an array
718 $sql = sqlStatement("SELECT * FROM `clinical_plans` WHERE `pid`=0 ORDER BY `id`");
720 $returnArray= array();
721 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
722 array_push($returnArray,$row);
725 // Now collect the pertinent plans
726 $newReturnArray = array();
728 // Need to select rules (use custom if exist)
729 foreach ($returnArray as $plan) {
730 $customPlan = sqlQuery("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan['id'],$patient_id) );
732 // Decide if use default vs custom plan (preference given to custom plan)
733 if (!empty($customPlan)) {
734 if ($type == "cqm" ) {
735 // For CQM , do not use custom plans (these are to create standard clinic wide reports)
736 $goPlan = $plan;
738 else {
739 // merge the custom plan with the default plan
740 $mergedPlan = array();
741 foreach ($customPlan as $key => $value) {
742 if ($value == NULL && preg_match("/_flag$/",$key)) {
743 // use default setting
744 $mergedPlan[$key] = $plan[$key];
746 else {
747 // use custom setting
748 $mergedPlan[$key] = $value;
751 $goPlan = $mergedPlan;
754 else {
755 $goPlan = $plan;
758 // Use the chosen plan if set
759 if (!empty($type)) {
760 if ($goPlan["${type}_flag"] == 1) {
761 // active, so use the plan
762 array_push($newReturnArray,$goPlan);
765 else {
766 if ($goPlan['normal_flag'] == 1 ||
767 $goPlan['cqm_flag'] == 1) {
768 // active, so use the plan
769 array_push($newReturnArray,$goPlan);
773 $returnArray = $newReturnArray;
775 return $returnArray;
778 // Function to return a specific plan
779 // Parameters:
780 // $plan - id(string) of plan
781 // $patient_id - pid of selected patient. (if set to 0, then will return
782 // the default rule).
783 // Return: array containing a rule
784 function collect_plan($plan,$patient_id='0') {
786 return sqlQuery("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan,$patient_id) );
790 // Function to set a specific plan activity for a specific patient
791 // Parameters:
792 // $plan - id(string) of plan
793 // $type - plan filter (normal,cqm)
794 // $setting - activity of plan (yes,no,default)
795 // $patient_id - pid of selected patient.
796 // Return: nothing
797 function set_plan_activity_patient($plan,$type,$setting,$patient_id) {
799 // Don't allow messing with the default plans here
800 if ($patient_id == "0") {
801 return;
804 // Convert setting
805 if ($setting == "on") {
806 $setting = 1;
808 else if ($setting == "off") {
809 $setting = 0;
811 else { // $setting == "default"
812 $setting = NULL;
815 // Collect patient specific plan, if already exists.
816 $query = "SELECT * FROM `clinical_plans` WHERE `id` = ? AND `pid` = ?";
817 $patient_plan = sqlQuery($query, array($plan,$patient_id) );
819 if (empty($patient_plan)) {
820 // Create a new patient specific plan with flags all set to default
821 $query = "INSERT into `clinical_plans` (`id`, `pid`) VALUES (?,?)";
822 sqlStatement($query, array($plan, $patient_id) );
825 // Update patient specific row
826 $query = "UPDATE `clinical_plans` SET `" . add_escape_custom($type) . "_flag`= ? WHERE id = ? AND pid = ?";
827 sqlStatement($query, array($setting,$plan,$patient_id) );
831 // Function to return active rules
832 // Parameters:
833 // $type - rule filter (active_alert,passive_alert,cqm,amc,patient_reminder)
834 // $patient_id - pid of selected patient. (if custom rule does not exist then
835 // will use the default rule)
836 // $configurableOnly - true if only want the configurable (per patient) rules
837 // (ie. ignore cqm and amc rules)
838 // $plan - collect rules for specific plan
839 // Return: array containing rules
840 function resolve_rules_sql($type='',$patient_id='0',$configurableOnly=FALSE,$plan='') {
842 if ($configurableOnly) {
843 // Collect all default, configurable (per patient) rules into an array
844 // (ie. ignore the cqm and amc rules)
845 $sql = sqlStatement("SELECT * FROM `clinical_rules` WHERE `pid`=0 AND `cqm_flag` !=1 AND `amc_flag` !=1 ORDER BY `id`");
847 else {
848 // Collect all default rules into an array
849 $sql = sqlStatement("SELECT * FROM `clinical_rules` WHERE `pid`=0 ORDER BY `id`");
851 $returnArray= array();
852 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
853 array_push($returnArray,$row);
856 // Now filter rules for plan (if applicable)
857 if (!empty($plan)) {
858 $planReturnArray = array();
859 foreach ($returnArray as $rule) {
860 $standardRule = sqlQuery("SELECT * FROM `clinical_plans_rules` " .
861 "WHERE `plan_id`=? AND `rule_id`=?", array($plan,$rule['id']) );
862 if (!empty($standardRule)) {
863 array_push($planReturnArray,$rule);
866 $returnArray = $planReturnArray;
869 // Now collect the pertinent rules
870 $newReturnArray = array();
872 // Need to select rules (use custom if exist)
873 foreach ($returnArray as $rule) {
874 $customRule = sqlQuery("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule['id'],$patient_id) );
876 // Decide if use default vs custom rule (preference given to custom rule)
877 if (!empty($customRule)) {
878 if ($type == "cqm" || $type == "amc" ) {
879 // For CQM and AMC, do not use custom rules (these are to create standard clinic wide reports)
880 $goRule = $rule;
882 else {
883 // merge the custom rule with the default rule
884 $mergedRule = array();
885 foreach ($customRule as $key => $value) {
886 if ($value == NULL && preg_match("/_flag$/",$key)) {
887 // use default setting
888 $mergedRule[$key] = $rule[$key];
890 else {
891 // use custom setting
892 $mergedRule[$key] = $value;
895 $goRule = $mergedRule;
898 else {
899 $goRule = $rule;
902 // Use the chosen rule if set
903 if (!empty($type)) {
904 if ($goRule["${type}_flag"] == 1) {
905 // active, so use the rule
906 array_push($newReturnArray,$goRule);
909 else {
910 // no filter, so return the rule
911 array_push($newReturnArray,$goRule);
914 $returnArray = $newReturnArray;
916 return $returnArray;
919 // Function to return a specific rule
920 // Parameters:
921 // $rule - id(string) of rule
922 // $patient_id - pid of selected patient. (if set to 0, then will return
923 // the default rule).
924 // Return: array containing a rule
925 function collect_rule($rule,$patient_id='0') {
927 return sqlQuery("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule,$patient_id) );
931 // Function to set a specific rule activity for a specific patient
932 // Parameters:
933 // $rule - id(string) of rule
934 // $type - rule filter (active_alert,passive_alert,cqm,amc,patient_reminder)
935 // $setting - activity of rule (yes,no,default)
936 // $patient_id - pid of selected patient.
937 // Return: nothing
938 function set_rule_activity_patient($rule,$type,$setting,$patient_id) {
940 // Don't allow messing with the default rules here
941 if ($patient_id == "0") {
942 return;
945 // Convert setting
946 if ($setting == "on") {
947 $setting = 1;
949 else if ($setting == "off") {
950 $setting = 0;
952 else { // $setting == "default"
953 $setting = NULL;
956 // Collect patient specific rule, if already exists.
957 $query = "SELECT * FROM `clinical_rules` WHERE `id` = ? AND `pid` = ?";
958 $patient_rule = sqlQuery($query, array($rule,$patient_id) );
960 if (empty($patient_rule)) {
961 // Create a new patient specific rule with flags all set to default
962 $query = "INSERT into `clinical_rules` (`id`, `pid`) VALUES (?,?)";
963 sqlStatement($query, array($rule, $patient_id) );
966 // Update patient specific row
967 $query = "UPDATE `clinical_rules` SET `" . add_escape_custom($type) . "_flag`= ? WHERE id = ? AND pid = ?";
968 sqlStatement($query, array($setting,$rule,$patient_id) );
972 // Function to return applicable reminder dates (relative)
973 // Parameters:
974 // $rule - id(string) of selected rule
975 // $reminder_method - string label of filter type
976 // Return: array containing reminder features
977 function resolve_reminder_sql($rule,$reminder_method) {
978 $sql = sqlStatement("SELECT `method_detail`, `value` FROM `rule_reminder` " .
979 "WHERE `id`=? AND `method`=?", array($rule, $reminder_method) );
981 $returnArray= array();
982 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
983 array_push($returnArray,$row);
985 return $returnArray;
988 // Function to return applicable filters
989 // Parameters:
990 // $rule - id(string) of selected rule
991 // $filter_method - string label of filter type
992 // $include_flag - to allow selection for included or excluded filters
993 // Return: array containing filters
994 function resolve_filter_sql($rule,$filter_method,$include_flag=1) {
995 $sql = sqlStatement("SELECT `method_detail`, `value`, `required_flag` FROM `rule_filter` " .
996 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $filter_method, $include_flag) );
998 $returnArray= array();
999 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1000 array_push($returnArray,$row);
1002 return $returnArray;
1005 // Function to return applicable targets
1006 // Parameters:
1007 // $rule - id(string) of selected rule
1008 // $group_id - group id of target group (if blank, then will ignore grouping)
1009 // $target_method - string label of target type
1010 // $include_flag - to allow selection for included or excluded targets
1011 // Return: array containing targets
1012 function resolve_target_sql($rule,$group_id='',$target_method,$include_flag=1) {
1014 if ($group_id) {
1015 $sql = sqlStatement("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
1016 "WHERE `id`=? AND `group_id`=? AND `method`=? AND `include_flag`=?", array($rule, $group_id, $target_method, $include_flag) );
1018 else {
1019 $sql = sqlStatement("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
1020 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $target_method, $include_flag) );
1023 $returnArray= array();
1024 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1025 array_push($returnArray,$row);
1027 return $returnArray;
1030 // Function to return applicable actions
1031 // Parameters:
1032 // $rule - id(string) of selected rule
1033 // $group_id - group id of target group (if blank, then will ignore grouping)
1034 // Return: array containing actions
1035 function resolve_action_sql($rule,$group_id='') {
1037 if ($group_id) {
1038 $sql = sqlStatement("SELECT b.category, b.item, b.clin_rem_link, b.reminder_message, b.custom_flag " .
1039 "FROM `rule_action` as a " .
1040 "JOIN `rule_action_item` as b " .
1041 "ON a.category = b.category AND a.item = b.item " .
1042 "WHERE a.id=? AND a.group_id=?", array($rule,$group_id) );
1044 else {
1045 $sql = sqlStatement("SELECT b.category, b.item, b.value, b.custom_flag " .
1046 "FROM `rule_action` as a " .
1047 "JOIN `rule_action_item` as b " .
1048 "ON a.category = b.category AND a.item = b.item " .
1049 "WHERE a.id=?", array($rule) );
1052 $returnArray= array();
1053 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1054 array_push($returnArray,$row);
1056 return $returnArray;
1059 // Function to check database filters and targets
1060 // Parameters:
1061 // $patient_id - pid of selected patient.
1062 // $filter - array containing filter/target elements
1063 // $interval - used for the interval elements
1064 // $dateTarget - target date. blank is current date.
1065 // Return: boolean if check passed, otherwise false
1066 function database_check($patient_id,$filter,$interval='',$dateTarget='') {
1067 $isMatch = false; //matching flag
1069 // Set date to current if not set
1070 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1072 // Unpackage interval information
1073 // (Assume only one for now and only pertinent for targets)
1074 $intervalType = '';
1075 $intervalValue = '';
1076 if (!empty($interval)) {
1077 $intervalType = $interval[0]['value'];
1078 $intervalValue = $interval[0]['interval'];
1081 foreach( $filter as $row ) {
1082 // Row description
1083 // [0]=>special modes
1084 $temp_df = explode("::",$row['value']);
1086 if ($temp_df[0] == "CUSTOM") {
1087 // Row description
1088 // [0]=>special modes(CUSTOM) [1]=>category [2]=>item [3]=>complete? [4]=>number of hits comparison [5]=>number of hits
1089 if (exist_custom_item($patient_id, $temp_df[1], $temp_df[2], $temp_df[3], $temp_df[4], $temp_df[5], $intervalType, $intervalValue, $dateTarget)) {
1090 // Record the match
1091 $isMatch = true;
1093 else {
1094 // If this is a required entry then return false
1095 if ($row['required_flag']) return false;
1098 else if ($temp_df[0] == "LIFESTYLE") {
1099 // Row description
1100 // [0]=>special modes(LIFESTYLE) [1]=>column [2]=>status
1101 if (exist_lifestyle_item($patient_id, $temp_df[1], $temp_df[2], $dateTarget)) {
1102 // Record the match
1103 $isMatch = true;
1105 else {
1106 // If this is a required entry then return false
1107 if ($row['required_flag']) return false;
1110 else {
1111 // Default mode
1112 // Row description
1113 // [0]=>special modes(BLANK) [1]=>table [2]=>column [3]=>value comparison [4]=>value [5]=>number of hits comparison [6]=>number of hits
1114 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)) {
1115 // Record the match
1116 $isMatch = true;
1118 else {
1119 // If this is a required entry then return false
1120 if ($row['required_flag']) return false;
1125 // return results of check
1126 return $isMatch;
1129 // Function to check procedure filters and targets
1130 // Parameters:
1131 // $patient_id - pid of selected patient.
1132 // $filter - array containing filter/target elements
1133 // $interval - used for the interval elements
1134 // $dateTarget - target date. blank is current date.
1135 // Return: boolean if check passed, otherwise false
1136 function procedure_check($patient_id,$filter,$interval='',$dateTarget='') {
1137 $isMatch = false; //matching flag
1139 // Set date to current if not set
1140 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1142 // Unpackage interval information
1143 // (Assume only one for now and only pertinent for targets)
1144 $intervalType = '';
1145 $intervalValue = '';
1146 if (!empty($interval)) {
1147 $intervalType = $interval[0]['value'];
1148 $intervalValue = $interval[0]['interval'];
1151 foreach( $filter as $row ) {
1152 // Row description
1153 // [0]=>title [1]=>code [2]=>value comparison [3]=>value [4]=>number of hits comparison [5]=>number of hits
1154 // code description
1155 // <type(ICD9,CPT4)>:<identifier>||<type(ICD9,CPT4)>:<identifier>||<identifier> etc.
1156 $temp_df = explode("::",$row['value']);
1157 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)) {
1158 // Record the match
1159 $isMatch = true;
1161 else {
1162 // If this is a required entry then return false
1163 if ($row['required_flag']) return false;
1167 // return results of check
1168 return $isMatch;
1171 // Function to check for appointment
1172 // Parameters:
1173 // $patient_id - pid of selected patient.
1174 // $dateTarget - target date.
1175 // Return: boolean if appt exist, otherwise false
1176 function appointment_check($patient_id,$dateTarget='') {
1177 $isMatch = false; //matching flag
1179 // Set date to current if not set (although should always be set)
1180 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1181 $dateTargetRound = date('Y-m-d',$dateTarget);
1183 // Set current date
1184 $currentDate = date('Y-m-d H:i:s');
1185 $currentDateRound = date('Y-m-d',$dateCurrent);
1187 // Basically, if the appointment is within the current date to the target date,
1188 // then return true. (will not send reminders on same day as appointment)
1189 $sql = sqlStatement("SELECT openemr_postcalendar_events.pc_eid, " .
1190 "openemr_postcalendar_events.pc_title, " .
1191 "openemr_postcalendar_events.pc_eventDate, " .
1192 "openemr_postcalendar_events.pc_startTime, " .
1193 "openemr_postcalendar_events.pc_endTime " .
1194 "FROM openemr_postcalendar_events " .
1195 "WHERE openemr_postcalendar_events.pc_eventDate > ? " .
1196 "AND openemr_postcalendar_events.pc_eventDate <= ? " .
1197 "AND openemr_postcalendar_events.pc_pid = ?", array($currentDate,$dateTarget,$patient_id) );
1199 // return results of check
1201 // TODO: Figure out how to have multiple appointment and changing appointment reminders.
1202 // Plan to send back array of appt info (eid, time, date, etc.)
1203 // to do this.
1204 if (sqlNumRows($sql) > 0) {
1205 $isMatch = true;
1208 return $isMatch;
1211 // Function to check lists filters and targets
1212 // Customizable and currently includes diagnoses, medications,
1213 // allergies and surgeries.
1214 // Parameters:
1215 // $patient_id - pid of selected patient.
1216 // $filter - array containing lists filter/target elements
1217 // $dateTarget - target date. blank is current date.
1218 // Return: boolean if check passed, otherwise false
1219 function lists_check($patient_id,$filter,$dateTarget) {
1220 $isMatch = false; //matching flag
1222 // Set date to current if not set
1223 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1225 foreach ( $filter as $row ) {
1226 if (exist_lists_item($patient_id, $row['method_detail'], $row['value'], $dateTarget)) {
1227 // Record the match
1228 $isMatch = true;
1230 else {
1231 // If this is a required entry then return false
1232 if ($row['required_flag']) return false;
1236 // return results of check
1237 return $isMatch;
1240 // Function to check for existance of data in database for a patient
1241 // Parameters:
1242 // $patient_id - pid of selected patient.
1243 // $table - selected mysql table
1244 // $column - selected mysql column
1245 // $data_comp - data comparison (eq,ne,gt,ge,lt,le)
1246 // $data - selected data in the mysql database
1247 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1248 // $num_items_thres - number of items threshold
1249 // $intervalType - type of interval (ie. year)
1250 // $intervalValue - searched for within this many times of the interval type
1251 // $dateTarget - target date.
1252 // Return: boolean if check passed, otherwise false
1253 function exist_database_item($patient_id,$table,$column='',$data_comp,$data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
1255 // Set date to current if not set
1256 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1258 // Collect the correct column label for patient id in the table
1259 $patient_id_label = collect_database_label('pid',$table);
1261 // Get the interval sql query string
1262 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1264 // If just checking for existence (ie. data is empty),
1265 // then simply set the comparison operator to ne.
1266 if (empty($data)) {
1267 $data_comp = "ne";
1270 // get the appropriate sql comparison operator
1271 $compSql = convertCompSql($data_comp);
1273 // check for items
1274 if (empty($column)) {
1275 // simple search for any table entries
1276 $sql = sqlStatement("SELECT * " .
1277 "FROM `" . add_escape_custom($table) . "` " .
1278 "WHERE `" . add_escape_custom($patient_id_label) . "`=?", array($patient_id) );
1280 else {
1281 // search for number of specific items
1282 $sql = sqlStatement("SELECT `" . add_escape_custom($column) . "` " .
1283 "FROM `" . add_escape_custom($table) . "` " .
1284 "WHERE `" . add_escape_custom($column) ."`" . $compSql . "? " .
1285 "AND `" . add_escape_custom($patient_id_label) . "`=? " .
1286 $dateSql, array($data,$patient_id) );
1289 // See if number of returned items passes the comparison
1290 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1293 // Function to check for existence of procedure(s) for a patient
1294 // Parameters:
1295 // $patient_id - pid of selected patient.
1296 // $proc_title - procedure title
1297 // $proc_code - procedure identifier code (array of <type(ICD9,CPT4)>:<identifier>||<type(ICD9,CPT4)>:<identifier>||<identifier> etc.)
1298 // $result_comp - results comparison (eq,ne,gt,ge,lt,le)
1299 // $result_data - results data
1300 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1301 // $num_items_thres - number of items threshold
1302 // $intervalType - type of interval (ie. year)
1303 // $intervalValue - searched for within this many times of the interval type
1304 // $dateTarget - target date.
1305 // Return: boolean if check passed, otherwise false
1306 function exist_procedure_item($patient_id,$proc_title,$proc_code,$result_comp,$result_data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
1308 // Set date to current if not set
1309 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1311 // Set the table exception (for looking up pertinent date and pid sql columns)
1312 $table = "PROCEDURE-EXCEPTION";
1314 // Collect the correct column label for patient id in the table
1315 $patient_id_label = collect_database_label('pid',$table);
1317 // Get the interval sql query string
1318 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1320 // If just checking for existence (ie result_data is empty),
1321 // then simply set the comparison operator to ne.
1322 if (empty($result_data)) {
1323 $result_comp = "ne";
1326 // get the appropriate sql comparison operator
1327 $compSql = convertCompSql($result_comp);
1329 // explode the code array
1330 $codes= array();
1331 if (!empty($proc_code)) {
1332 $codes = explode("||",$proc_code);
1334 else {
1335 $codes[0] = '';
1338 // ensure proc_title is at least blank
1339 if (empty($proc_title)) {
1340 $proc_title = '';
1343 // collect specific items (use both title and/or codes) that fulfill request
1344 $sqlBindArray=array();
1345 $sql_query = "SELECT procedure_result.result " .
1346 "FROM `procedure_type`, " .
1347 "`procedure_order`, " .
1348 "`procedure_report`, " .
1349 "`procedure_result` " .
1350 "WHERE procedure_type.procedure_type_id = procedure_order.procedure_type_id " .
1351 "AND procedure_order.procedure_order_id = procedure_report.procedure_order_id " .
1352 "AND procedure_report.procedure_report_id = procedure_result.procedure_report_id " .
1353 "AND ";
1354 foreach ($codes as $tem) {
1355 $sql_query .= "( ( (procedure_type.standard_code = ? AND procedure_type.standard_code != '') " .
1356 "OR (procedure_type.procedure_code = ? AND procedure_type.procedure_code != '') ) OR ";
1357 array_push($sqlBindArray,$tem,$tem);
1359 $sql_query .= "(procedure_type.name = ? AND procedure_type.name != '') ) " .
1360 "AND procedure_result.result " . $compSql . " ? " .
1361 "AND " . add_escape_custom($patient_id_label) . " = ? " . $dateSql;
1362 array_push($sqlBindArray,$proc_title,$result_data,$patient_id);
1363 $sql = sqlStatement($sql_query,$sqlBindArray);
1365 // See if number of returned items passes the comparison
1366 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1369 // Function to check for existance of data for a patient in the rule_patient_data table
1370 // Parameters:
1371 // $patient_id - pid of selected patient.
1372 // $category - label in category column
1373 // $item - label in item column
1374 // $complete - label in complete column (YES,NO, or blank)
1375 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1376 // $num_items_thres - number of items threshold
1377 // $intervalType - type of interval (ie. year)
1378 // $intervalValue - searched for within this many times of the interval type
1379 // $dateTarget - target date.
1380 // Return: boolean if check passed, otherwise false
1381 function exist_custom_item($patient_id,$category,$item,$complete,$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget) {
1383 // Set the table
1384 $table = 'rule_patient_data';
1386 // Collect the correct column label for patient id in the table
1387 $patient_id_label = collect_database_label('pid',$table);
1389 // Get the interval sql query string
1390 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1392 // search for number of specific items
1393 $sql = sqlStatement("SELECT `result` " .
1394 "FROM `" . add_escape_custom($table) . "` " .
1395 "WHERE `category`=? " .
1396 "AND `item`=? " .
1397 "AND `complete`=? " .
1398 "AND `" . add_escape_custom($patient_id_label) . "`=? " .
1399 $dateSql, array($category,$item,$complete,$patient_id) );
1401 // See if number of returned items passes the comparison
1402 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1405 // Function to check for existance of data for a patient in lifestyle section
1406 // Parameters:
1407 // $patient_id - pid of selected patient.
1408 // $lifestyle - selected label of mysql column of patient history
1409 // $status - specific status of selected lifestyle element
1410 // $dateTarget - target date. blank is current date.
1411 // Return: boolean if check passed, otherwise false
1412 function exist_lifestyle_item($patient_id,$lifestyle,$status,$dateTarget) {
1414 // Set date to current if not set
1415 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1417 // Collect pertinent history data
1418 $history = getHistoryData($patient_id, $lifestyle,'',$dateTarget);
1420 // See if match
1421 $stringFlag = strstr($history[$lifestyle], "|".$status);
1422 if (empty($status)) {
1423 // Only ensuring any data has been entered into the field
1424 $stringFlag = true;
1426 if ( $history[$lifestyle] &&
1427 $history[$lifestyle] != '|0|' &&
1428 $stringFlag ) {
1429 return true;
1431 else {
1432 return false;
1436 // Function to check for lists item of a patient
1437 // Fully customizable and includes diagnoses, medications,
1438 // allergies, and surgeries.
1439 // Parameters:
1440 // $patient_id - pid of selected patient.
1441 // $type - type (medical_problem, allergy, medication, etc)
1442 // $value - value searching for
1443 // $dateTarget - target date. blank is current date.
1444 // Return: boolean if check passed, otherwise false
1445 function exist_lists_item($patient_id,$type,$value,$dateTarget) {
1447 // Set date to current if not set
1448 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1450 // Attempt to explode the value into a code type and code (if applicable)
1451 $value_array = explode("::",$value);
1452 if (count($value_array) == 2) {
1454 // Collect the code type and code
1455 $code_type = $value_array[0];
1456 $code = $value_array[1];
1458 if ($code_type=='CUSTOM') {
1459 // Deal with custom code type first (title column in lists table)
1460 $response = sqlQuery("SELECT * FROM `lists` " .
1461 "WHERE `type`=? " .
1462 "AND `pid`=? " .
1463 "AND `title`=? " .
1464 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1465 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$code,$dateTarget,$dateTarget,$dateTarget) );
1466 if (!empty($response)) return true;
1468 else {
1469 // Deal with the set code types (diagnosis column in lists table)
1470 $response = sqlQuery("SELECT * FROM `lists` " .
1471 "WHERE `type`=? " .
1472 "AND `pid`=? " .
1473 "AND `diagnosis` LIKE ? " .
1474 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1475 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,"%".$code_type.":".$code."%",$dateTarget,$dateTarget,$dateTarget) );
1476 if (!empty($response)) return true;
1479 else { // count($value_array) == 1
1480 // Search the title column in lists table
1481 // Yes, this is essentially the same as the code type listed as CUSTOM above. This provides flexibility and will ensure compatibility.
1482 $response = sqlQuery("SELECT * FROM `lists` " .
1483 "WHERE `type`=? " .
1484 "AND `pid`=? " .
1485 "AND `title`=? ".
1486 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1487 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$value,$dateTarget,$dateTarget,$dateTarget) );
1488 if (!empty($response)) return true;
1491 return false;
1494 // Function to return part of sql query to deal with interval
1495 // Parameters:
1496 // $table - selected mysql table (or EXCEPTION(s))
1497 // $intervalType - type of interval (ie. year)
1498 // $intervalValue - searched for within this many times of the interval type
1499 // $dateTarget - target date.
1500 // Return: string containing pertinent date interval filter for mysql query
1501 function sql_interval_string($table,$intervalType,$intervalValue,$dateTarget) {
1503 $dateSql="";
1505 // Collect the correct column label for date in the table
1506 $date_label = collect_database_label('date',$table);
1508 // Deal with interval
1509 if (!empty($intervalType)) {
1510 switch($intervalType) {
1511 case "year":
1512 $dateSql = "AND (" . add_escape_custom($date_label) .
1513 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1514 "', INTERVAL " . add_escape_custom($intervalValue) .
1515 " YEAR) AND '" . add_escape_custom($dateTarget) . "') ";
1516 break;
1517 case "month":
1518 $dateSql = "AND (" . add_escape_custom($date_label) .
1519 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1520 "', INTERVAL " . add_escape_custom($intervalValue) .
1521 " MONTH) AND '" . add_escape_custom($dateTarget) . "') ";
1522 break;
1523 case "week":
1524 $dateSql = "AND (" . add_escape_custom($date_label) .
1525 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1526 "', INTERVAL " . add_escape_custom($intervalValue) .
1527 " WEEK) AND '" . add_escape_custom($dateTarget) . "') ";
1528 break;
1529 case "day":
1530 $dateSql = "AND (" . add_escape_custom($date_label) .
1531 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1532 "', INTERVAL " . add_escape_custom($intervalValue) .
1533 " DAY) AND '" . add_escape_custom($dateTarget) . "') ";
1534 break;
1535 case "hour":
1536 $dateSql = "AND (" . add_escape_custom($date_label) .
1537 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1538 "', INTERVAL " . add_escape_custom($intervalValue) .
1539 " HOUR) AND '" . add_escape_custom($dateTarget) . "') ";
1540 break;
1541 case "minute":
1542 $dateSql = "AND (" . add_escape_custom($date_label) .
1543 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1544 "', INTERVAL " . add_escape_custom($intervalValue) .
1545 " MINUTE) AND '" . add_escape_custom($dateTarget) . "') ";
1546 break;
1547 case "second":
1548 $dateSql = "AND (" . add_escape_custom($date_label) .
1549 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1550 "', INTERVAL " . add_escape_custom($intervalValue) .
1551 " SECOND) AND '" . add_escape_custom($dateTarget) . "') ";
1552 break;
1553 case "flu_season":
1554 // Flu season to be hard-coded as September thru February
1555 // (Should make this modifiable in the future)
1556 // ($intervalValue is not used)
1557 $dateArray = explode("-",$dateTarget);
1558 $Year = $dateArray[0];
1559 $dateThisYear = $Year . "-09-01";
1560 $dateLastYear = ($Year-1) . "-09-01";
1561 $dateSql =" " .
1562 "AND ((" .
1563 "MONTH('" . add_escape_custom($dateTarget) . "') < 9 " .
1564 "AND " . add_escape_custom($date_label) . " >= '" . $dateLastYear . "' ) " .
1565 "OR (" .
1566 "MONTH('" . add_escape_custom($dateTarget) . "') >= 9 " .
1567 "AND " . add_escape_custom($date_label) . " >= '" . $dateThisYear . "' ))" .
1568 "AND " . add_escape_custom($date_label) . " <= '" . add_escape_custom($dateTarget) . "' ";
1569 break;
1572 else {
1573 $dateSql = "AND " . add_escape_custom($date_label) .
1574 " <= '" . add_escape_custom($dateTarget) . "' ";
1577 // return the sql interval string
1578 return $dateSql;
1581 // Function to collect generic column labels from tables.
1582 // It currently works for date and pid.
1583 // Will need to expand this as algorithm grows.
1584 // Parameters:
1585 // $label - element (pid or date)
1586 // $table - selected mysql table (or EXCEPTION(s))
1587 // Return: string containing official label of selected element
1588 function collect_database_label($label,$table) {
1590 if ($table == 'PROCEDURE-EXCEPTION') {
1591 // return cell to get procedure collection
1592 // special case since reuqires joing of multiple
1593 // tables to get this value
1594 if ($label == "pid") {
1595 $returnedLabel = "procedure_order.patient_id";
1597 else if ($label == "date") {
1598 $returnedLabel = "procedure_report.date_collected";
1600 else {
1601 // unknown label, so return the original label
1602 $returnedLabel = $label;
1605 else if ($table == 'immunizations') {
1606 // return requested label for immunization table
1607 if ($label == "pid") {
1608 $returnedLabel = "patient_id";
1610 else if ($label == "date") {
1611 $returnedLabel = "`administered_date`";
1613 else {
1614 // unknown label, so return the original label
1615 $returnedLabel = $label;
1618 else {
1619 // return requested label for default tables
1620 if ($label == "pid") {
1621 $returnedLabel = "pid";
1623 else if ($label == "date") {
1624 $returnedLabel = "`date`";
1626 else {
1627 // unknown label, so return the original label
1628 $returnedLabel = $label;
1632 return $returnedLabel;
1635 // Simple function to avoid processing of duplicate actions
1636 // Parameters:
1637 // $actions - 2-dimensional array with all current active targets
1638 // $action - array of selected target to test for duplicate
1639 // Return: boolean, true if duplicate, false if not duplicate
1640 function is_duplicate_action($actions,$action) {
1641 foreach ($actions as $row) {
1642 if ($row['category'] == $action['category'] &&
1643 $row['item'] == $action['item'] &&
1644 $row['value'] == $action['value']) {
1645 // Is a duplicate
1646 return true;
1650 // Not a duplicate
1651 return false;
1654 // Calculate the reminder dates.
1655 // Parameters:
1656 // $rule - id(string) of selected rule
1657 // $dateTarget - target date. If blank then will test with current date as target.
1658 // $type - either 'patient_reminder' or 'clinical_reminder'
1659 // For now, will always return an array of 3 dates:
1660 // first date is before the target date (past_due) (default of 1 month)
1661 // second date is the target date (due)
1662 // third date is after the target date (soon_due) (default of 2 weeks)
1663 function calculate_reminder_dates($rule, $dateTarget='',$type) {
1665 // Set date to current if not set
1666 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1668 // Collect the current date settings (to ensure not skip)
1669 $res = resolve_reminder_sql($rule, $type.'_current');
1670 if (!empty($res)) {
1671 $row = $res[0];
1672 if ($row ['method_detail'] == "SKIP") {
1673 $dateTarget = "SKIP";
1677 // Collect the past_due date
1678 $past_due_date == "";
1679 $res = resolve_reminder_sql($rule, $type.'_post');
1680 if (!empty($res)) {
1681 $row = $res[0];
1682 if ($row ['method_detail'] == "week") {
1683 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " week"));
1685 if ($row ['method_detail'] == "month") {
1686 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " month"));
1688 if ($row ['method_detail'] == "hour") {
1689 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
1691 if ($row ['method_detail'] == "SKIP") {
1692 $past_due_date = "SKIP";
1695 else {
1696 // empty settings, so use default of one month
1697 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -1 month"));
1700 // Collect the soon_due date
1701 $soon_due_date == "";
1702 $res = resolve_reminder_sql($rule, $type.'_pre');
1703 if (!empty($res)) {
1704 $row = $res[0];
1705 if ($row ['method_detail'] == "week") {
1706 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " week"));
1708 if ($row ['method_detail'] == "month") {
1709 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " month"));
1711 if ($row ['method_detail'] == "hour") {
1712 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
1714 if ($row ['method_detail'] == "SKIP") {
1715 $soon_due_date = "SKIP";
1718 else {
1719 // empty settings, so use default of one month
1720 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +2 week"));
1723 // Return the array of three dates
1724 return array($soon_due_date,$dateTarget,$past_due_date);
1727 // Adds an action into the reminder array
1728 // Parameters:
1729 // $reminderOldArray - Contains the current array of reminders
1730 // $reminderNew - Array of a new reminder
1731 // Return:
1732 // An array of reminders
1733 function reminder_results_integrate($reminderOldArray, $reminderNew) {
1735 $results = array();
1737 // If reminderArray is empty, then insert new reminder
1738 if (empty($reminderOldArray)) {
1739 array_push($results, $reminderNew);
1740 return $results;
1743 // If duplicate reminder, then replace the old one
1744 $duplicate = false;
1745 foreach ($reminderOldArray as $reminderOld) {
1746 if ( $reminderOld['pid'] == $reminderNew['pid'] &&
1747 $reminderOld['category'] == $reminderNew['category'] &&
1748 $reminderOld['item'] == $reminderNew['item']) {
1749 array_push($results, $reminderNew);
1750 $duplicate = true;
1752 else {
1753 array_push($results, $reminderOld);
1757 // If a new reminder, then insert the new reminder
1758 if (!$duplicate) {
1759 array_push($results, $reminderNew);
1762 return $results;
1765 // Compares number of items with requested comparison operator
1766 // Parameters:
1767 // $comp - Comparison operator(eq,ne,gt,ge,lt,le)
1768 // $thres - Threshold used in comparison
1769 // $num_items - Number of items
1770 // Return:
1771 // Boolean of comparison results
1772 function itemsNumberCompare($comp, $thres, $num_items) {
1774 if ( ($comp == "eq") && ($num_items == $thres) ) {
1775 return true;
1777 else if ( ($comp == "ne") && ($num_items != $thres) && ($num_items > 0) ) {
1778 return true;
1780 else if ( ($comp == "gt") && ($num_items > $thres) ) {
1781 return true;
1783 else if ( ($comp == "ge") && ($num_items >= $thres) ) {
1784 return true;
1786 else if ( ($comp == "lt") && ($num_items < $thres) && ($num_items > 0) ) {
1787 return true;
1789 else if ( ($comp == "le") && ($num_items <= $thres) && ($num_items > 0) ) {
1790 return true;
1792 else {
1793 return false;
1797 // Converts a text comparison operator to sql equivalent
1798 // Parameters:
1799 // $comp - Comparison operator(eq,ne,gt,ge,lt,le)
1800 // Return:
1801 // String containing sql compatible comparison operator
1802 function convertCompSql($comp) {
1804 if ($comp == "eq") {
1805 return "=";
1807 else if ($comp == "ne") {
1808 return "!=";
1810 else if ($comp == "gt") {
1811 return ">";
1813 else if ($comp == "ge") {
1814 return ">=";
1816 else if ($comp == "lt") {
1817 return "<";
1819 else { // ($comp == "le")
1820 return "<=";
1824 // Function to find age in years (with decimal) on the target date
1825 // Parameters:
1826 // $dob - date of birth
1827 // $target - date to calculate age on
1828 // Return: decimal, years(decimal) from dob to target(date)
1829 function convertDobtoAgeYearDecimal($dob,$target) {
1831 // Prepare dob (Y M D)
1832 $dateDOB = explode(" ",$dob);
1834 // Prepare target (Y-M-D H:M:S)
1835 $dateTargetTemp = explode(" ",$target);
1836 $dateTarget = explode("-",$dateTargetTemp[0]);
1838 // Collect differences
1839 $iDiffYear = $dateTarget[0] - $dateDOB[0];
1840 $iDiffMonth = $dateTarget[1] - $dateDOB[1];
1841 $iDiffDay = $dateTarget[2] - $dateDOB[2];
1843 // If birthday has not happen yet for this year, subtract 1.
1844 if ($iDiffMonth < 0 || ($iDiffMonth == 0 && $iDiffDay < 0))
1846 $iDiffYear--;
1849 // Ensure diffYear is not less than 0
1850 if ($iDiffYear < 0) $iDiffYear = 0;
1852 return $iDiffYear;
1855 // Function to find age in months (with decimal) on the target date
1856 // Parameters:
1857 // $dob - date of birth
1858 // $target - date to calculate age on
1859 // Return: decimal, months(decimal) from dob to target(date)
1860 function convertDobtoAgeMonthDecimal($dob,$target) {
1862 // Prepare dob (Y M D)
1863 $dateDOB = explode(" ",$dob);
1865 // Prepare target (Y-M-D H:M:S)
1866 $dateTargetTemp = explode(" ",$target);
1867 $dateTarget = explode("-",$dateTargetTemp[0]);
1869 // Collect differences
1870 $iDiffYear = $dateTarget[0] - $dateDOB[0];
1871 $iDiffMonth = $dateTarget[1] - $dateDOB[1];
1872 $iDiffDay = $dateTarget[2] - $dateDOB[2];
1874 // If birthday has not happen yet for this year, subtract 1.
1875 if ($iDiffMonth < 0 || ($iDiffMonth == 0 && $iDiffDay < 0))
1877 $iDiffYear--;
1880 // Ensure diffYear is not less than 0
1881 if ($iDiffYear < 0) $iDiffYear = 0;
1883 return (12 * $iDiffYear) + $iDiffMonth;
1886 // Function to calculate the percentage
1887 // Parameters:
1888 // $pass_filter - number of patients that pass filter
1889 // $exclude_filter - number of patients that are excluded
1890 // $pass_target - number of patients that pass target
1891 // Return: String of a number formatted into a percentage
1892 function calculate_percentage($pass_filt,$exclude_filt,$pass_targ) {
1893 if ($pass_filt > 0) {
1894 $perc = number_format(($pass_targ/($pass_filt-$exclude_filt))*100) . xl('%');
1896 else {
1897 $perc = "0". xl('%');
1899 return $perc;