Fix for show/hide menu link formatting issues in IE, Chrome, Safari.
[openemr.git] / library / clinical_rules.php
blob5dad5fb77c692102553a6ec123e28981bc848ac8
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 // Test the clinic rules of entire clinic and create a report or patient reminders
95 // (can also test on one patient or patients of one provider)
96 // Parameters:
97 // $provider - id of a selected provider. If blank, then will test entire clinic. If 'collate_outer' or
98 // 'collate_inner', then will test each provider in entire clinic; outer will nest plans
99 // inside collated providers, while inner will nest the providers inside the plans (note
100 // inner and outer are only different if organize_mode is set to plans).
101 // $type - rule filter (active_alert,passive_alert,cqm,amc,patient_reminder). If blank then will test all rules.
102 // $dateTarget - target date. If blank then will test with current date as target.
103 // If an array, then is holding two dates ('dateBegin' and 'dateTarget')
104 // $mode - choose either 'report' or 'reminders-all' or 'reminders-due' (required)
105 // $patient_id - pid of patient. If blank then will check all patients.
106 // $plan - test for specific plan only
107 // $organize_mode - Way to organize the results (default, plans)
108 // 'default':
109 // Returns a two-dimensional array of results organized by rules:
110 // reminders-due mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
111 // reminders-all mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
112 // report mode - returns an array of rows for the Clinical Quality Measures (CQM) report
113 // 'plans':
114 // Returns similar to default, but organizes by the active plans
115 // $options - can hold various option (for now, used to hold the manual number of labs for the AMC report)
117 function test_rules_clinic($provider='',$type='',$dateTarget='',$mode='',$patient_id='',$plan='',$organize_mode='default',$options=array()) {
119 // If dateTarget is an array, then organize them.
120 if (is_array($dateTarget)) {
121 $dateArray = $dateTarget;
122 $dateTarget = $dateTarget['dateTarget'];
125 // Set date to current if not set
126 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
128 // Prepare the results array
129 $results = array();
131 // If set the $provider to collate_outer (or collate_inner without plans organize mode),
132 // then run through this function recursively and return results.
133 if (($provider == "collate_outer") || ($provider == "collate_inner" && $organize_mode != 'plans')) {
134 // First, collect an array of all providers
135 $query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
136 $ures = sqlStatement($query);
137 // Second, run through each provider recursively
138 while ($urow = sqlFetchArray($ures)) {
139 $newResults = test_rules_clinic($urow['id'],$type,$dateTarget,$mode,$patient_id,$plan,$organize_mode);
140 if (!empty($newResults)) {
141 $provider_item['is_provider'] = TRUE;
142 $provider_item['prov_lname'] = $urow['lname'];
143 $provider_item['prov_fname'] = $urow['fname'];
144 $provider_item['npi'] = $urow['npi'];
145 $provider_item['federaltaxid'] = $urow['federaltaxid'];
146 array_push($results,$provider_item);
147 $results = array_merge($results,$newResults);
150 // done, so now can return results
151 return $results;
154 // If set organize-mode to plans, then collects active plans and run through this
155 // function recursively and return results.
156 if ($organize_mode == "plans") {
157 // First, collect active plans
158 $plans_resolve = resolve_plans_sql($plan,$patient_id);
159 // Second, run through function recursively
160 foreach ($plans_resolve as $plan_item) {
161 // (if collate_inner, then nest a collation of providers within each plan)
162 if ($provider == "collate_inner") {
163 // First, collect an array of all providers
164 $query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
165 $ures = sqlStatement($query);
166 // Second, run through each provider recursively
167 $provider_results = array();
168 while ($urow = sqlFetchArray($ures)) {
169 $newResults = test_rules_clinic($urow['id'],$type,$dateTarget,$mode,$patient_id,$plan_item['id']);
170 if (!empty($newResults)) {
171 $provider_item['is_provider'] = TRUE;
172 $provider_item['prov_lname'] = $urow['lname'];
173 $provider_item['prov_fname'] = $urow['fname'];
174 $provider_item['npi'] = $urow['npi'];
175 $provider_item['federaltaxid'] = $urow['federaltaxid'];
176 array_push($provider_results,$provider_item);
177 $provider_results = array_merge($provider_results,$newResults);
180 if (!empty($provider_results)) {
181 $plan_item['is_plan'] = TRUE;
182 array_push($results,$plan_item);
183 $results = array_merge($results,$provider_results);
186 else {
187 // (not collate_inner, so do not nest providers within each plan)
188 $newResults = test_rules_clinic($provider,$type,$dateTarget,$mode,$patient_id,$plan_item['id']);
189 if (!empty($newResults)) {
190 $plan_item['is_plan'] = TRUE;
191 array_push($results,$plan_item);
192 $results = array_merge($results,$newResults);
196 // done, so now can return results
197 return $results;
200 // Collect all patient ids
201 $patientData = array();
202 if (!empty($patient_id)) {
203 // only look at the selected patient
204 array_push($patientData,$patient_id);
206 else {
207 if (empty($provider)) {
208 // Look at entire practice
209 $rez = sqlStatement("SELECT `pid` FROM `patient_data`");
210 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
211 $patientData[$iter]=$row;
214 else {
215 // Look at one provider
216 $rez = sqlStatement("SELECT `pid` FROM `patient_data` " .
217 "WHERE providerID=?", array($provider) );
218 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
219 $patientData[$iter]=$row;
223 // Go through each patient(s)
225 // If in report mode, then tabulate for each rule:
226 // Total Patients
227 // Patients that pass the filter
228 // Patients that pass the target
229 // If in reminders mode, then create reminders for each rule:
230 // Reminder that action is due soon
231 // Reminder that action is due
232 // Reminder that action is post-due
234 //Collect applicable rules
235 if ($mode != "report") {
236 // Use per patient custom rules (if exist)
237 $rules = resolve_rules_sql($type,$patient_id,FALSE,$plan);
239 else { // $mode = "report"
240 // Only use default rules (do not use patient custom rules)
241 $rules = resolve_rules_sql($type,$patient_id,FALSE,$plan);
244 foreach( $rules as $rowRule ) {
246 // If using cqm or amc type, then use the hard-coded rules set.
247 // Note these rules are only used in report mode.
248 if ($rowRule['cqm_flag'] || $rowRule['amc_flag']) {
250 require_once( dirname(__FILE__)."/classes/rulesets/ReportManager.php");
251 $manager = new ReportManager();
252 if ($rowRule['amc_flag']) {
253 // Send array of dates ('dateBegin' and 'dateTarget')
254 $tempResults = $manager->runReport( $rowRule, $patientData, $dateArray, $options );
256 else {
257 // Send target date
258 $tempResults = $manager->runReport( $rowRule, $patientData, $dateTarget );
260 if (!empty($tempResults)) {
261 foreach ($tempResults as $tempResult) {
262 array_push($results,$tempResult);
266 // Go on to the next rule
267 continue;
270 // If in reminder mode then need to collect the measurement dates
271 // from rule_reminder table
272 $target_dates = array();
273 if ($mode != "report") {
274 // Calculate the dates to check for
275 if ($type == "patient_reminder") {
276 $reminder_interval_type = "patient_reminder";
278 else { // $type == "passive_alert" or $type == "active_alert"
279 $reminder_interval_type = "clinical_reminder";
281 $target_dates = calculate_reminder_dates($rowRule['id'], $dateTarget, $reminder_interval_type);
283 else { // $mode == "report"
284 // Only use the target date in the report
285 $target_dates[0] = $dateTarget;
288 //Reset the counters
289 $total_patients = 0;
290 $pass_filter = 0;
291 $exclude_filter = 0;
292 $pass_target = 0;
294 foreach( $patientData as $rowPatient ) {
296 // Count the total patients
297 $total_patients++;
299 $dateCounter = 1; // for reminder mode to keep track of which date checking
300 foreach ( $target_dates as $dateFocus ) {
302 //Skip if date is set to SKIP
303 if ($dateFocus == "SKIP") {
304 $dateCounter++;
305 continue;
308 //Set date counter and reminder token (applicable for reminders only)
309 if ($dateCounter == 1) {
310 $reminder_due = "soon_due";
312 else if ($dateCounter == 2) {
313 $reminder_due = "due";
315 else { // $dateCounter == 3
316 $reminder_due = "past_due";
319 // First, deal with deceased patients
320 // (for now will simply not pass the filter, but can add a database item
321 // if ever want to create rules for dead people)
322 // Could also place this function at the total_patients level if wanted.
323 // (But then would lose the option of making rules for dead people)
324 // Note using the dateTarget rather than dateFocus
325 if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
326 continue;
329 // Check if pass filter
330 $passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
331 if ($passFilter === "EXCLUDED") {
332 // increment EXCLUDED and pass_filter counters
333 // and set as FALSE for reminder functionality.
334 $pass_filter++;
335 $exclude_filter++;
336 $passFilter = FALSE;
338 if ($passFilter) {
339 // increment pass filter counter
340 $pass_filter++;
342 else {
343 $dateCounter++;
344 continue;
347 // Check if pass target
348 $passTarget = test_targets($rowPatient['pid'],$rowRule['id'],'',$dateFocus);
349 if ($passTarget) {
350 // increment pass target counter
351 $pass_target++;
352 // send to reminder results
353 if ($mode == "reminders-all") {
354 // place the completed actions into the reminder return array
355 $actionArray = resolve_action_sql($rowRule['id'],'1');
356 foreach ($actionArray as $action) {
357 $action_plus = $action;
358 $action_plus['due_status'] = "not_due";
359 $action_plus['pid'] = $rowPatient['pid'];
360 $results = reminder_results_integrate($results, $action_plus);
363 break;
365 else {
366 // send to reminder results
367 if ($mode != "report") {
368 // place the uncompleted actions into the reminder return array
369 $actionArray = resolve_action_sql($rowRule['id'],'1');
370 foreach ($actionArray as $action) {
371 $action_plus = $action;
372 $action_plus['due_status'] = $reminder_due;
373 $action_plus['pid'] = $rowPatient['pid'];
374 $results = reminder_results_integrate($results, $action_plus);
378 $dateCounter++;
382 // Calculate and save the data for the rule
383 $percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
384 if ($mode == "report") {
385 $newRow=array('is_main'=>TRUE,'total_patients'=>$total_patients,'excluded'=>$exclude_filter,'pass_filter'=>$pass_filter,'pass_target'=>$pass_target,'percentage'=>$percentage);
386 $newRow=array_merge($newRow,$rowRule);
387 array_push($results, $newRow);
390 // Find the number of target groups, and go through each one if more than one
391 $targetGroups = returnTargetGroups($rowRule['id']);
392 if (count($targetGroups) > 1) {
393 $firstGroup = true;
394 foreach ($targetGroups as $i) {
396 // skip first group if not in report mode
397 // (this is because first group was already queried above)
398 if ($mode != "report" && $firstGroup) {
399 $firstGroup = false;
400 continue;
403 //Reset the target counter
404 $pass_target = 0;
406 foreach( $patientData as $rowPatient ) {
408 $dateCounter = 1; // for reminder mode to keep track of which date checking
409 foreach ( $target_dates as $dateFocus ) {
411 //Skip if date is set to SKIP
412 if ($dateFocus == "SKIP") {
413 $dateCounter++;
414 continue;
417 //Set date counter and reminder token (applicable for reminders only)
418 if ($dateCounter == 1) {
419 $reminder_due = "soon_due";
421 else if ($dateCounter == 2) {
422 $reminder_due = "due";
424 else { // $dateCounter == 3
425 $reminder_due = "past_due";
428 // First, deal with deceased patients
429 // (for now will simply not pass the filter, but can add a database item
430 // if ever want to create rules for dead people)
431 // Could also place this function at the total_patients level if wanted.
432 // (But then would lose the option of making rules for dead people)
433 // Note using the dateTarget rather than dateFocus
434 if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
435 continue;
438 //Check if pass target
439 $passTarget = test_targets($rowPatient['pid'],$rowRule['id'],$i,$dateFocus);
440 if ($passTarget) {
441 // increment pass target counter
442 $pass_target++;
443 // send to reminder results
444 if ($mode == "reminders-all") {
445 // place the completed actions into the reminder return array
446 $actionArray = resolve_action_sql($rowRule['id'],'1');
447 foreach ($actionArray as $action) {
448 $action_plus = $action;
449 $action_plus['due_status'] = "not_due";
450 $action_plus['pid'] = $rowPatient['pid'];
451 $results = reminder_results_integrate($results, $action_plus);
454 break;
456 else {
457 // send to reminder results
458 if ($mode != "report") {
459 // place the actions into the reminder return array
460 $actionArray = resolve_action_sql($rowRule['id'],$i);
461 foreach ($actionArray as $action) {
462 $action_plus = $action;
463 $action_plus['due_status'] = $reminder_due;
464 $action_plus['pid'] = $rowPatient['pid'];
465 $results = reminder_results_integrate($results, $action_plus);
469 $dateCounter++;
473 // Calculate and save the data for the rule
474 $percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
476 // Collect action for title (just use the first one, if more than one)
477 $actionArray = resolve_action_sql($rowRule['id'],$i);
478 $action = $actionArray[0];
479 if ($mode == "report") {
480 $newRow=array('is_sub'=>TRUE,'action_category'=>$action['category'],'action_item'=>$action['item'],'total_patients'=>'','excluded'=>'','pass_filter'=>'','pass_target'=>$pass_target,'percentage'=>$percentage);
481 array_push($results, $newRow);
487 // Return the data
488 return $results;
491 // Test filter of a selected rule on a selected patient
492 // Parameters:
493 // $patient_id - pid of selected patient.
494 // $rule - id(string) of selected rule
495 // $dateTarget - target date.
496 // Return:
497 // boolean (if pass filter then TRUE, if excluded then 'EXCLUDED', if not pass filter then FALSE)
498 function test_filter($patient_id,$rule,$dateTarget) {
500 // Set date to current if not set
501 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
503 // Collect patient information
504 $patientData = getPatientData($patient_id, "sex, DATE_FORMAT(DOB,'%Y %m %d') as DOB_TS");
507 // ----------------- INCLUSIONS -----------------
510 // -------- Age Filter (inclusion) ------------
511 // Calculate patient age in years and months
512 $patientAgeYears = convertDobtoAgeYearDecimal($patientData['DOB_TS'],$dateTarget);
513 $patientAgeMonths = convertDobtoAgeMonthDecimal($patientData['DOB_TS'],$dateTarget);
515 // Min age (year) Filter (assume that there in not more than one of each)
516 $filter = resolve_filter_sql($rule,'filt_age_min');
517 if (!empty($filter)) {
518 $row = $filter[0];
519 if ($row ['method_detail'] == "year") {
520 if ( $row['value'] && ($row['value'] > $patientAgeYears) ) {
521 return false;
524 if ($row ['method_detail'] == "month") {
525 if ( $row['value'] && ($row['value'] > $patientAgeMonths) ) {
526 return false;
530 // Max age (year) Filter (assume that there in not more than one of each)
531 $filter = resolve_filter_sql($rule,'filt_age_max');
532 if (!empty($filter)) {
533 $row = $filter[0];
534 if ($row ['method_detail'] == "year") {
535 if ( $row['value'] && ($row['value'] < $patientAgeYears) ) {
536 return false;
539 if ($row ['method_detail'] == "month") {
540 if ( $row['value'] && ($row['value'] < $patientAgeMonths) ) {
541 return false;
546 // -------- Gender Filter (inclusion) ---------
547 // Gender Filter (assume that there in not more than one of each)
548 $filter = resolve_filter_sql($rule,'filt_sex');
549 if (!empty($filter)) {
550 $row = $filter[0];
551 if ( $row['value'] && ($row['value'] != $patientData['sex']) ) {
552 return false;
556 // -------- Database Filter (inclusion) ------
557 // Database Filter
558 $filter = resolve_filter_sql($rule,'filt_database');
559 if ((!empty($filter)) && !database_check($patient_id,$filter,'',$dateTarget)) return false;
561 // -------- Lists Filter (inclusion) ----
562 // Set up lists filter, which is fully customizable and currently includes diagnoses, meds,
563 // surgeries and allergies.
564 $filter = resolve_filter_sql($rule,'filt_lists');
565 if ((!empty($filter)) && !lists_check($patient_id,$filter,$dateTarget)) return false;
568 // ----------------- EXCLUSIONS -----------------
571 // -------- Lists Filter (EXCLUSION) ----
572 // Set up lists EXCLUSION filter, which is fully customizable and currently includes diagnoses, meds,
573 // surgeries and allergies.
574 $filter = resolve_filter_sql($rule,'filt_lists',0);
575 if ((!empty($filter)) && lists_check($patient_id,$filter,$dateTarget)) return "EXCLUDED";
577 // Passed all filters, so return true.
578 return true;
581 // Return an array containing existing group ids for a rule
582 // Parameters:
583 // $rule - id(string) of rule
584 // Return:
585 // array, listing of group ids
586 function returnTargetGroups($rule) {
588 $sql = sqlStatement("SELECT DISTINCT `group_id` FROM `rule_target` " .
589 "WHERE `id`=?", array($rule) );
591 $groups = array();
592 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
593 array_push($groups,$row['group_id']);
595 return $groups;
598 // Test targets of a selected rule on a selected patient
599 // Parameters:
600 // $patient_id - pid of selected patient.
601 // $rule - id(string) of selected rule (if blank, then will ignore grouping)
602 // $group_id - group id of target group
603 // $dateTarget - target date.
604 // Return:
605 // boolean (if target passes then true, otherwise false)
606 function test_targets($patient_id,$rule,$group_id='',$dateTarget) {
608 // -------- Interval Target ----
609 $interval = resolve_target_sql($rule,$group_id,'target_interval');
611 // -------- Database Target ----
612 // Database Target (includes)
613 $target = resolve_target_sql($rule,$group_id,'target_database');
614 if ((!empty($target)) && !database_check($patient_id,$target,$interval,$dateTarget)) return false;
616 // -------- Procedure (labs,imaging,test,procedures,etc) Target ----
617 // Procedure Target (includes)
618 $target = resolve_target_sql($rule,$group_id,'target_proc');
619 if ((!empty($target)) && !procedure_check($patient_id,$target,$interval,$dateTarget)) return false;
621 // -------- Appointment Target ----
622 // Appointment Target (includes) (Specialized functionality for appointment reminders)
623 $target = resolve_target_sql($rule,$group_id,'target_appt');
624 if ((!empty($target)) && appointment_check($patient_id,$dateTarget)) return false;
626 // Passed all target tests, so return true.
627 return true;
630 // Function to return active plans
631 // Parameters:
632 // $type - plan type filter (normal or cqm or blank)
633 // $patient_id - pid of selected patient. (if custom plan does not exist then
634 // will use the default plan)
635 // $configurableOnly - true if only want the configurable (per patient) plans
636 // (ie. ignore cqm plans)
637 // Return: array containing plans
638 function resolve_plans_sql($type='',$patient_id='0',$configurableOnly=FALSE) {
640 if ($configurableOnly) {
641 // Collect all default, configurable (per patient) plans into an array
642 // (ie. ignore the cqm rules)
643 $sql = sqlStatement("SELECT * FROM `clinical_plans` WHERE `pid`=0 AND `cqm_flag` !=1 ORDER BY `id`");
645 else {
646 // Collect all default plans into an array
647 $sql = sqlStatement("SELECT * FROM `clinical_plans` WHERE `pid`=0 ORDER BY `id`");
649 $returnArray= array();
650 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
651 array_push($returnArray,$row);
654 // Now collect the pertinent plans
655 $newReturnArray = array();
657 // Need to select rules (use custom if exist)
658 foreach ($returnArray as $plan) {
659 $customPlan = sqlQuery("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan['id'],$patient_id) );
661 // Decide if use default vs custom plan (preference given to custom plan)
662 if (!empty($customPlan)) {
663 if ($type == "cqm" ) {
664 // For CQM , do not use custom plans (these are to create standard clinic wide reports)
665 $goPlan = $plan;
667 else {
668 // merge the custom plan with the default plan
669 $mergedPlan = array();
670 foreach ($customPlan as $key => $value) {
671 if ($value == NULL && preg_match("/_flag$/",$key)) {
672 // use default setting
673 $mergedPlan[$key] = $plan[$key];
675 else {
676 // use custom setting
677 $mergedPlan[$key] = $value;
680 $goPlan = $mergedPlan;
683 else {
684 $goPlan = $plan;
687 // Use the chosen plan if set
688 if (!empty($type)) {
689 if ($goPlan["${type}_flag"] == 1) {
690 // active, so use the plan
691 array_push($newReturnArray,$goPlan);
694 else {
695 if ($goPlan['normal_flag'] == 1 ||
696 $goPlan['cqm_flag'] == 1) {
697 // active, so use the plan
698 array_push($newReturnArray,$goPlan);
702 $returnArray = $newReturnArray;
704 return $returnArray;
707 // Function to return a specific plan
708 // Parameters:
709 // $plan - id(string) of plan
710 // $patient_id - pid of selected patient. (if set to 0, then will return
711 // the default rule).
712 // Return: array containing a rule
713 function collect_plan($plan,$patient_id='0') {
715 return sqlQuery("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan,$patient_id) );
719 // Function to set a specific plan activity for a specific patient
720 // Parameters:
721 // $plan - id(string) of plan
722 // $type - plan filter (normal,cqm)
723 // $setting - activity of plan (yes,no,default)
724 // $patient_id - pid of selected patient.
725 // Return: nothing
726 function set_plan_activity_patient($plan,$type,$setting,$patient_id) {
728 // Don't allow messing with the default plans here
729 if ($patient_id == "0") {
730 return;
733 // Convert setting
734 if ($setting == "on") {
735 $setting = 1;
737 else if ($setting == "off") {
738 $setting = 0;
740 else { // $setting == "default"
741 $setting = NULL;
744 // Collect patient specific plan, if already exists.
745 $query = "SELECT * FROM `clinical_plans` WHERE `id` = ? AND `pid` = ?";
746 $patient_plan = sqlQuery($query, array($plan,$patient_id) );
748 if (empty($patient_plan)) {
749 // Create a new patient specific plan with flags all set to default
750 $query = "INSERT into `clinical_plans` (`id`, `pid`) VALUES (?,?)";
751 sqlStatement($query, array($plan, $patient_id) );
754 // Update patient specific row
755 $query = "UPDATE `clinical_plans` SET `" . add_escape_custom($type) . "_flag`= ? WHERE id = ? AND pid = ?";
756 sqlStatement($query, array($setting,$plan,$patient_id) );
760 // Function to return active rules
761 // Parameters:
762 // $type - rule filter (active_alert,passive_alert,cqm,amc,patient_reminder)
763 // $patient_id - pid of selected patient. (if custom rule does not exist then
764 // will use the default rule)
765 // $configurableOnly - true if only want the configurable (per patient) rules
766 // (ie. ignore cqm and amc rules)
767 // $plan - collect rules for specific plan
768 // Return: array containing rules
769 function resolve_rules_sql($type='',$patient_id='0',$configurableOnly=FALSE,$plan='') {
771 if ($configurableOnly) {
772 // Collect all default, configurable (per patient) rules into an array
773 // (ie. ignore the cqm and amc rules)
774 $sql = sqlStatement("SELECT * FROM `clinical_rules` WHERE `pid`=0 AND `cqm_flag` !=1 AND `amc_flag` !=1 ORDER BY `id`");
776 else {
777 // Collect all default rules into an array
778 $sql = sqlStatement("SELECT * FROM `clinical_rules` WHERE `pid`=0 ORDER BY `id`");
780 $returnArray= array();
781 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
782 array_push($returnArray,$row);
785 // Now filter rules for plan (if applicable)
786 if (!empty($plan)) {
787 $planReturnArray = array();
788 foreach ($returnArray as $rule) {
789 $standardRule = sqlQuery("SELECT * FROM `clinical_plans_rules` " .
790 "WHERE `plan_id`=? AND `rule_id`=?", array($plan,$rule['id']) );
791 if (!empty($standardRule)) {
792 array_push($planReturnArray,$rule);
795 $returnArray = $planReturnArray;
798 // Now collect the pertinent rules
799 $newReturnArray = array();
801 // Need to select rules (use custom if exist)
802 foreach ($returnArray as $rule) {
803 $customRule = sqlQuery("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule['id'],$patient_id) );
805 // Decide if use default vs custom rule (preference given to custom rule)
806 if (!empty($customRule)) {
807 if ($type == "cqm" || $type == "amc" ) {
808 // For CQM and AMC, do not use custom rules (these are to create standard clinic wide reports)
809 $goRule = $rule;
811 else {
812 // merge the custom rule with the default rule
813 $mergedRule = array();
814 foreach ($customRule as $key => $value) {
815 if ($value == NULL && preg_match("/_flag$/",$key)) {
816 // use default setting
817 $mergedRule[$key] = $rule[$key];
819 else {
820 // use custom setting
821 $mergedRule[$key] = $value;
824 $goRule = $mergedRule;
827 else {
828 $goRule = $rule;
831 // Use the chosen rule if set
832 if (!empty($type)) {
833 if ($goRule["${type}_flag"] == 1) {
834 // active, so use the rule
835 array_push($newReturnArray,$goRule);
838 else {
839 // no filter, so return the rule
840 array_push($newReturnArray,$goRule);
843 $returnArray = $newReturnArray;
845 return $returnArray;
848 // Function to return a specific rule
849 // Parameters:
850 // $rule - id(string) of rule
851 // $patient_id - pid of selected patient. (if set to 0, then will return
852 // the default rule).
853 // Return: array containing a rule
854 function collect_rule($rule,$patient_id='0') {
856 return sqlQuery("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule,$patient_id) );
860 // Function to set a specific rule activity for a specific patient
861 // Parameters:
862 // $rule - id(string) of rule
863 // $type - rule filter (active_alert,passive_alert,cqm,amc,patient_reminder)
864 // $setting - activity of rule (yes,no,default)
865 // $patient_id - pid of selected patient.
866 // Return: nothing
867 function set_rule_activity_patient($rule,$type,$setting,$patient_id) {
869 // Don't allow messing with the default rules here
870 if ($patient_id == "0") {
871 return;
874 // Convert setting
875 if ($setting == "on") {
876 $setting = 1;
878 else if ($setting == "off") {
879 $setting = 0;
881 else { // $setting == "default"
882 $setting = NULL;
885 // Collect patient specific rule, if already exists.
886 $query = "SELECT * FROM `clinical_rules` WHERE `id` = ? AND `pid` = ?";
887 $patient_rule = sqlQuery($query, array($rule,$patient_id) );
889 if (empty($patient_rule)) {
890 // Create a new patient specific rule with flags all set to default
891 $query = "INSERT into `clinical_rules` (`id`, `pid`) VALUES (?,?)";
892 sqlStatement($query, array($rule, $patient_id) );
895 // Update patient specific row
896 $query = "UPDATE `clinical_rules` SET `" . add_escape_custom($type) . "_flag`= ? WHERE id = ? AND pid = ?";
897 sqlStatement($query, array($setting,$rule,$patient_id) );
901 // Function to return applicable reminder dates (relative)
902 // Parameters:
903 // $rule - id(string) of selected rule
904 // $reminder_method - string label of filter type
905 // Return: array containing reminder features
906 function resolve_reminder_sql($rule,$reminder_method) {
907 $sql = sqlStatement("SELECT `method_detail`, `value` FROM `rule_reminder` " .
908 "WHERE `id`=? AND `method`=?", array($rule, $reminder_method) );
910 $returnArray= array();
911 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
912 array_push($returnArray,$row);
914 return $returnArray;
917 // Function to return applicable filters
918 // Parameters:
919 // $rule - id(string) of selected rule
920 // $filter_method - string label of filter type
921 // $include_flag - to allow selection for included or excluded filters
922 // Return: array containing filters
923 function resolve_filter_sql($rule,$filter_method,$include_flag=1) {
924 $sql = sqlStatement("SELECT `method_detail`, `value`, `required_flag` FROM `rule_filter` " .
925 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $filter_method, $include_flag) );
927 $returnArray= array();
928 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
929 array_push($returnArray,$row);
931 return $returnArray;
934 // Function to return applicable targets
935 // Parameters:
936 // $rule - id(string) of selected rule
937 // $group_id - group id of target group (if blank, then will ignore grouping)
938 // $target_method - string label of target type
939 // $include_flag - to allow selection for included or excluded targets
940 // Return: array containing targets
941 function resolve_target_sql($rule,$group_id='',$target_method,$include_flag=1) {
943 if ($group_id) {
944 $sql = sqlStatement("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
945 "WHERE `id`=? AND `group_id`=? AND `method`=? AND `include_flag`=?", array($rule, $group_id, $target_method, $include_flag) );
947 else {
948 $sql = sqlStatement("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
949 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $target_method, $include_flag) );
952 $returnArray= array();
953 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
954 array_push($returnArray,$row);
956 return $returnArray;
959 // Function to return applicable actions
960 // Parameters:
961 // $rule - id(string) of selected rule
962 // $group_id - group id of target group (if blank, then will ignore grouping)
963 // Return: array containing actions
964 function resolve_action_sql($rule,$group_id='') {
966 if ($group_id) {
967 $sql = sqlStatement("SELECT b.category, b.item, b.clin_rem_link, b.reminder_message, b.custom_flag " .
968 "FROM `rule_action` as a " .
969 "JOIN `rule_action_item` as b " .
970 "ON a.category = b.category AND a.item = b.item " .
971 "WHERE a.id=? AND a.group_id=?", array($rule,$group_id) );
973 else {
974 $sql = sqlStatement("SELECT b.category, b.item, b.value, b.custom_flag " .
975 "FROM `rule_action` as a " .
976 "JOIN `rule_action_item` as b " .
977 "ON a.category = b.category AND a.item = b.item " .
978 "WHERE a.id=?", array($rule) );
981 $returnArray= array();
982 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
983 array_push($returnArray,$row);
985 return $returnArray;
988 // Function to check database filters and targets
989 // Parameters:
990 // $patient_id - pid of selected patient.
991 // $filter - array containing filter/target elements
992 // $interval - used for the interval elements
993 // $dateTarget - target date. blank is current date.
994 // Return: boolean if check passed, otherwise false
995 function database_check($patient_id,$filter,$interval='',$dateTarget='') {
996 $isMatch = false; //matching flag
998 // Set date to current if not set
999 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1001 // Unpackage interval information
1002 // (Assume only one for now and only pertinent for targets)
1003 $intervalType = '';
1004 $intervalValue = '';
1005 if (!empty($interval)) {
1006 $intervalType = $interval[0]['value'];
1007 $intervalValue = $interval[0]['interval'];
1010 foreach( $filter as $row ) {
1011 // Row description
1012 // [0]=>special modes
1013 $temp_df = explode("::",$row['value']);
1015 if ($temp_df[0] == "CUSTOM") {
1016 // Row description
1017 // [0]=>special modes(CUSTOM) [1]=>category [2]=>item [3]=>complete? [4]=>number of hits comparison [5]=>number of hits
1018 if (exist_custom_item($patient_id, $temp_df[1], $temp_df[2], $temp_df[3], $temp_df[4], $temp_df[5], $intervalType, $intervalValue, $dateTarget)) {
1019 // Record the match
1020 $isMatch = true;
1022 else {
1023 // If this is a required entry then return false
1024 if ($row['required_flag']) return false;
1027 else if ($temp_df[0] == "LIFESTYLE") {
1028 // Row description
1029 // [0]=>special modes(LIFESTYLE) [1]=>column [2]=>status
1030 if (exist_lifestyle_item($patient_id, $temp_df[1], $temp_df[2], $dateTarget)) {
1031 // Record the match
1032 $isMatch = true;
1034 else {
1035 // If this is a required entry then return false
1036 if ($row['required_flag']) return false;
1039 else {
1040 // Default mode
1041 // Row description
1042 // [0]=>special modes(BLANK) [1]=>table [2]=>column [3]=>value comparison [4]=>value [5]=>number of hits comparison [6]=>number of hits
1043 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)) {
1044 // Record the match
1045 $isMatch = true;
1047 else {
1048 // If this is a required entry then return false
1049 if ($row['required_flag']) return false;
1054 // return results of check
1055 return $isMatch;
1058 // Function to check procedure filters and targets
1059 // Parameters:
1060 // $patient_id - pid of selected patient.
1061 // $filter - array containing filter/target elements
1062 // $interval - used for the interval elements
1063 // $dateTarget - target date. blank is current date.
1064 // Return: boolean if check passed, otherwise false
1065 function procedure_check($patient_id,$filter,$interval='',$dateTarget='') {
1066 $isMatch = false; //matching flag
1068 // Set date to current if not set
1069 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1071 // Unpackage interval information
1072 // (Assume only one for now and only pertinent for targets)
1073 $intervalType = '';
1074 $intervalValue = '';
1075 if (!empty($interval)) {
1076 $intervalType = $interval[0]['value'];
1077 $intervalValue = $interval[0]['interval'];
1080 foreach( $filter as $row ) {
1081 // Row description
1082 // [0]=>title [1]=>code [2]=>value comparison [3]=>value [4]=>number of hits comparison [5]=>number of hits
1083 // code description
1084 // <type(ICD9,CPT)>:<identifier>; etc.
1085 $temp_df = explode("::",$row['value']);
1086 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)) {
1087 // Record the match
1088 $isMatch = true;
1090 else {
1091 // If this is a required entry then return false
1092 if ($row['required_flag']) return false;
1096 // return results of check
1097 return $isMatch;
1100 // Function to check for appointment
1101 // Parameters:
1102 // $patient_id - pid of selected patient.
1103 // $dateTarget - target date.
1104 // Return: boolean if appt exist, otherwise false
1105 function appointment_check($patient_id,$dateTarget='') {
1106 $isMatch = false; //matching flag
1108 // Set date to current if not set (although should always be set)
1109 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1110 $dateTargetRound = date('Y-m-d',$dateTarget);
1112 // Set current date
1113 $currentDate = date('Y-m-d H:i:s');
1114 $currentDateRound = date('Y-m-d',$dateCurrent);
1116 // Basically, if the appointment is within the current date to the target date,
1117 // then return true. (will not send reminders on same day as appointment)
1118 $sql = sqlStatement("SELECT openemr_postcalendar_events.pc_eid, " .
1119 "openemr_postcalendar_events.pc_title, " .
1120 "openemr_postcalendar_events.pc_eventDate, " .
1121 "openemr_postcalendar_events.pc_startTime, " .
1122 "openemr_postcalendar_events.pc_endTime " .
1123 "FROM openemr_postcalendar_events " .
1124 "WHERE openemr_postcalendar_events.pc_eventDate > ? " .
1125 "AND openemr_postcalendar_events.pc_eventDate <= ? " .
1126 "AND openemr_postcalendar_events.pc_pid = ?", array($currentDate,$dateTarget,$patient_id) );
1128 // return results of check
1130 // TODO: Figure out how to have multiple appointment and changing appointment reminders.
1131 // Plan to send back array of appt info (eid, time, date, etc.)
1132 // to do this.
1133 if (sqlNumRows($sql) > 0) {
1134 $isMatch = true;
1137 return $isMatch;
1140 // Function to check lists filters and targets
1141 // Customizable and currently includes diagnoses, medications,
1142 // allergies and surgeries.
1143 // Parameters:
1144 // $patient_id - pid of selected patient.
1145 // $filter - array containing lists filter/target elements
1146 // $dateTarget - target date. blank is current date.
1147 // Return: boolean if check passed, otherwise false
1148 function lists_check($patient_id,$filter,$dateTarget) {
1149 $isMatch = false; //matching flag
1151 // Set date to current if not set
1152 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1154 foreach ( $filter as $row ) {
1155 if (exist_lists_item($patient_id, $row['method_detail'], $row['value'], $dateTarget)) {
1156 // Record the match
1157 $isMatch = true;
1159 else {
1160 // If this is a required entry then return false
1161 if ($row['required_flag']) return false;
1165 // return results of check
1166 return $isMatch;
1169 // Function to check for existance of data in database for a patient
1170 // Parameters:
1171 // $patient_id - pid of selected patient.
1172 // $table - selected mysql table
1173 // $column - selected mysql column
1174 // $data_comp - data comparison (eq,ne,gt,ge,lt,le)
1175 // $data - selected data in the mysql database
1176 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1177 // $num_items_thres - number of items threshold
1178 // $intervalType - type of interval (ie. year)
1179 // $intervalValue - searched for within this many times of the interval type
1180 // $dateTarget - target date.
1181 // Return: boolean if check passed, otherwise false
1182 function exist_database_item($patient_id,$table,$column='',$data_comp,$data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
1184 // Set date to current if not set
1185 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1187 // Collect the correct column label for patient id in the table
1188 $patient_id_label = collect_database_label('pid',$table);
1190 // Get the interval sql query string
1191 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1193 // If just checking for existence (ie. data is empty),
1194 // then simply set the comparison operator to ne.
1195 if (empty($data)) {
1196 $data_comp = "ne";
1199 // get the appropriate sql comparison operator
1200 $compSql = convertCompSql($data_comp);
1202 // check for items
1203 if (empty($column)) {
1204 // simple search for any table entries
1205 $sql = sqlStatement("SELECT * " .
1206 "FROM `" . add_escape_custom($table) . "` " .
1207 "WHERE `" . add_escape_custom($patient_id_label) . "`=?", array($patient_id) );
1209 else {
1210 // search for number of specific items
1211 $sql = sqlStatement("SELECT `" . add_escape_custom($column) . "` " .
1212 "FROM `" . add_escape_custom($table) . "` " .
1213 "WHERE `" . add_escape_custom($column) ."`" . $compSql . "? " .
1214 "AND `" . add_escape_custom($patient_id_label) . "`=? " .
1215 $dateSql, array($data,$patient_id) );
1218 // See if number of returned items passes the comparison
1219 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1222 // Function to check for existence of procedure(s) for a patient
1223 // Parameters:
1224 // $patient_id - pid of selected patient.
1225 // $proc_title - procedure title
1226 // $proc_code - procedure identifier code (array)
1227 // $result_comp - results comparison (eq,ne,gt,ge,lt,le)
1228 // $result_data - results data
1229 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1230 // $num_items_thres - number of items threshold
1231 // $intervalType - type of interval (ie. year)
1232 // $intervalValue - searched for within this many times of the interval type
1233 // $dateTarget - target date.
1234 // Return: boolean if check passed, otherwise false
1235 function exist_procedure_item($patient_id,$proc_title,$proc_code,$result_comp,$result_data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
1237 // Set date to current if not set
1238 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1240 // Set the table exception (for looking up pertinent date and pid sql columns)
1241 $table = "PROCEDURE-EXCEPTION";
1243 // Collect the correct column label for patient id in the table
1244 $patient_id_label = collect_database_label('pid',$table);
1246 // Get the interval sql query string
1247 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1250 // TODO
1251 // Figure out a way to use the identifiers codes
1252 // TODO
1255 // If just checking for existence (ie result_data is empty),
1256 // then simply set the comparison operator to ne.
1257 if (empty($result_data)) {
1258 $result_comp = "ne";
1261 // get the appropriate sql comparison operator
1262 $compSql = convertCompSql($result_comp);
1264 // collect specific items that fulfill request
1265 $sql = sqlStatement("SELECT procedure_result.result " .
1266 "FROM `procedure_type`, " .
1267 "`procedure_order`, " .
1268 "`procedure_report`, " .
1269 "`procedure_result` " .
1270 "WHERE procedure_type.procedure_type_id = procedure_order.procedure_type_id " .
1271 "AND procedure_order.procedure_order_id = procedure_report.procedure_order_id " .
1272 "AND procedure_report.procedure_report_id = procedure_result.procedure_report_id " .
1273 "AND procedure_type.name = ? " .
1274 "AND procedure_result.result " . $compSql . " ? " .
1275 "AND " . add_escape_custom($patient_id_label) . " = ? " .
1276 $dateSql, array($proc_title,$result_data,$patient_id) );
1278 // See if number of returned items passes the comparison
1279 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1282 // Function to check for existance of data for a patient in the rule_patient_data table
1283 // Parameters:
1284 // $patient_id - pid of selected patient.
1285 // $category - label in category column
1286 // $item - label in item column
1287 // $complete - label in complete column (YES,NO, or blank)
1288 // $num_items_comp - number items comparison (eq,ne,gt,ge,lt,le)
1289 // $num_items_thres - number of items threshold
1290 // $intervalType - type of interval (ie. year)
1291 // $intervalValue - searched for within this many times of the interval type
1292 // $dateTarget - target date.
1293 // Return: boolean if check passed, otherwise false
1294 function exist_custom_item($patient_id,$category,$item,$complete,$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget) {
1296 // Set the table
1297 $table = 'rule_patient_data';
1299 // Collect the correct column label for patient id in the table
1300 $patient_id_label = collect_database_label('pid',$table);
1302 // Get the interval sql query string
1303 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1305 // search for number of specific items
1306 $sql = sqlStatement("SELECT `result` " .
1307 "FROM `" . add_escape_custom($table) . "` " .
1308 "WHERE `category`=? " .
1309 "AND `item`=? " .
1310 "AND `complete`=? " .
1311 "AND `" . add_escape_custom($patient_id_label) . "`=? " .
1312 $dateSql, array($category,$item,$complete,$patient_id) );
1314 // See if number of returned items passes the comparison
1315 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1318 // Function to check for existance of data for a patient in lifestyle section
1319 // Parameters:
1320 // $patient_id - pid of selected patient.
1321 // $lifestyle - selected label of mysql column of patient history
1322 // $status - specific status of selected lifestyle element
1323 // $dateTarget - target date. blank is current date.
1324 // Return: boolean if check passed, otherwise false
1325 function exist_lifestyle_item($patient_id,$lifestyle,$status,$dateTarget) {
1327 // Set date to current if not set
1328 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1330 // Collect pertinent history data
1331 $history = getHistoryData($patient_id, $lifestyle,'',$dateTarget);
1333 // See if match
1334 $stringFlag = strstr($history[$lifestyle], "|".$status);
1335 if (empty($status)) {
1336 // Only ensuring any data has been entered into the field
1337 $stringFlag = true;
1339 if ( $history[$lifestyle] &&
1340 $history[$lifestyle] != '|0|' &&
1341 $stringFlag ) {
1342 return true;
1344 else {
1345 return false;
1349 // Function to check for lists item of a patient
1350 // Fully customizable and includes diagnoses, medications,
1351 // allergies, and surgeries.
1352 // Parameters:
1353 // $patient_id - pid of selected patient.
1354 // $type - type (medical_problem, allergy, medication, etc)
1355 // $value - value searching for
1356 // $dateTarget - target date. blank is current date.
1357 // Return: boolean if check passed, otherwise false
1358 function exist_lists_item($patient_id,$type,$value,$dateTarget) {
1360 // Set date to current if not set
1361 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1363 // Attempt to explode the value into a code type and code (if applicable)
1364 $value_array = explode("::",$value);
1365 if (count($value_array) == 2) {
1367 // Collect the code type and code
1368 $code_type = $value_array[0];
1369 $code = $value_array[1];
1371 if ($code_type=='CUSTOM') {
1372 // Deal with custom code type first (title column in lists table)
1373 $response = sqlQuery("SELECT * FROM `lists` " .
1374 "WHERE `type`=? " .
1375 "AND `pid`=? " .
1376 "AND `title`=? " .
1377 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1378 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$code,$dateTarget,$dateTarget,$dateTarget) );
1379 if (!empty($response)) return true;
1381 else {
1382 // Deal with the set code types (diagnosis column in lists table)
1383 $response = sqlQuery("SELECT * FROM `lists` " .
1384 "WHERE `type`=? " .
1385 "AND `pid`=? " .
1386 "AND `diagnosis` LIKE ? " .
1387 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1388 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,"%".$code_type.":".$code."%",$dateTarget,$dateTarget,$dateTarget) );
1389 if (!empty($response)) return true;
1392 else { // count($value_array) == 1
1393 // Search the title column in lists table
1394 // Yes, this is essentially the same as the code type listed as CUSTOM above. This provides flexibility and will ensure compatibility.
1395 $response = sqlQuery("SELECT * FROM `lists` " .
1396 "WHERE `type`=? " .
1397 "AND `pid`=? " .
1398 "AND `title`=? ".
1399 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
1400 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$value,$dateTarget,$dateTarget,$dateTarget) );
1401 if (!empty($response)) return true;
1404 return false;
1407 // Function to return part of sql query to deal with interval
1408 // Parameters:
1409 // $table - selected mysql table (or EXCEPTION(s))
1410 // $intervalType - type of interval (ie. year)
1411 // $intervalValue - searched for within this many times of the interval type
1412 // $dateTarget - target date.
1413 // Return: string containing pertinent date interval filter for mysql query
1414 function sql_interval_string($table,$intervalType,$intervalValue,$dateTarget) {
1416 $dateSql="";
1418 // Collect the correct column label for date in the table
1419 $date_label = collect_database_label('date',$table);
1421 // Deal with interval
1422 if (!empty($intervalType)) {
1423 switch($intervalType) {
1424 case "year":
1425 $dateSql = "AND (" . add_escape_custom($date_label) .
1426 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1427 "', INTERVAL " . add_escape_custom($intervalValue) .
1428 " YEAR) AND '" . add_escape_custom($dateTarget) . "') ";
1429 break;
1430 case "month":
1431 $dateSql = "AND (" . add_escape_custom($date_label) .
1432 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1433 "', INTERVAL " . add_escape_custom($intervalValue) .
1434 " MONTH) AND '" . add_escape_custom($dateTarget) . "') ";
1435 break;
1436 case "week":
1437 $dateSql = "AND (" . add_escape_custom($date_label) .
1438 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1439 "', INTERVAL " . add_escape_custom($intervalValue) .
1440 " WEEK) AND '" . add_escape_custom($dateTarget) . "') ";
1441 break;
1442 case "day":
1443 $dateSql = "AND (" . add_escape_custom($date_label) .
1444 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1445 "', INTERVAL " . add_escape_custom($intervalValue) .
1446 " DAY) AND '" . add_escape_custom($dateTarget) . "') ";
1447 break;
1448 case "hour":
1449 $dateSql = "AND (" . add_escape_custom($date_label) .
1450 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1451 "', INTERVAL " . add_escape_custom($intervalValue) .
1452 " HOUR) AND '" . add_escape_custom($dateTarget) . "') ";
1453 break;
1454 case "minute":
1455 $dateSql = "AND (" . add_escape_custom($date_label) .
1456 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1457 "', INTERVAL " . add_escape_custom($intervalValue) .
1458 " MINUTE) AND '" . add_escape_custom($dateTarget) . "') ";
1459 break;
1460 case "second":
1461 $dateSql = "AND (" . add_escape_custom($date_label) .
1462 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
1463 "', INTERVAL " . add_escape_custom($intervalValue) .
1464 " SECOND) AND '" . add_escape_custom($dateTarget) . "') ";
1465 break;
1466 case "flu_season":
1467 // Flu season to be hard-coded as September thru February
1468 // (Should make this modifiable in the future)
1469 // ($intervalValue is not used)
1470 $dateArray = explode("-",$dateTarget);
1471 $Year = $dateArray[0];
1472 $dateThisYear = $Year . "-09-01";
1473 $dateLastYear = ($Year-1) . "-09-01";
1474 $dateSql =" " .
1475 "AND ((" .
1476 "MONTH('" . add_escape_custom($dateTarget) . "') < 9 " .
1477 "AND " . add_escape_custom($date_label) . " >= '" . $dateLastYear . "' ) " .
1478 "OR (" .
1479 "MONTH('" . add_escape_custom($dateTarget) . "') >= 9 " .
1480 "AND " . add_escape_custom($date_label) . " >= '" . $dateThisYear . "' ))" .
1481 "AND " . add_escape_custom($date_label) . " <= '" . add_escape_custom($dateTarget) . "' ";
1482 break;
1485 else {
1486 $dateSql = "AND " . add_escape_custom($date_label) .
1487 " <= '" . add_escape_custom($dateTarget) . "' ";
1490 // return the sql interval string
1491 return $dateSql;
1494 // Function to collect generic column labels from tables.
1495 // It currently works for date and pid.
1496 // Will need to expand this as algorithm grows.
1497 // Parameters:
1498 // $label - element (pid or date)
1499 // $table - selected mysql table (or EXCEPTION(s))
1500 // Return: string containing official label of selected element
1501 function collect_database_label($label,$table) {
1503 if ($table == 'PROCEDURE-EXCEPTION') {
1504 // return cell to get procedure collection
1505 // special case since reuqires joing of multiple
1506 // tables to get this value
1507 if ($label == "pid") {
1508 $returnedLabel = "procedure_order.patient_id";
1510 else if ($label == "date") {
1511 $returnedLabel = "procedure_report.date_collected";
1513 else {
1514 // unknown label, so return the original label
1515 $returnedLabel = $label;
1518 else if ($table == 'immunizations') {
1519 // return requested label for immunization table
1520 if ($label == "pid") {
1521 $returnedLabel = "patient_id";
1523 else if ($label == "date") {
1524 $returnedLabel = "`administered_date`";
1526 else {
1527 // unknown label, so return the original label
1528 $returnedLabel = $label;
1531 else {
1532 // return requested label for default tables
1533 if ($label == "pid") {
1534 $returnedLabel = "pid";
1536 else if ($label == "date") {
1537 $returnedLabel = "`date`";
1539 else {
1540 // unknown label, so return the original label
1541 $returnedLabel = $label;
1545 return $returnedLabel;
1548 // Simple function to avoid processing of duplicate actions
1549 // Parameters:
1550 // $actions - 2-dimensional array with all current active targets
1551 // $action - array of selected target to test for duplicate
1552 // Return: boolean, true if duplicate, false if not duplicate
1553 function is_duplicate_action($actions,$action) {
1554 foreach ($actions as $row) {
1555 if ($row['category'] == $action['category'] &&
1556 $row['item'] == $action['item'] &&
1557 $row['value'] == $action['value']) {
1558 // Is a duplicate
1559 return true;
1563 // Not a duplicate
1564 return false;
1567 // Calculate the reminder dates.
1568 // Parameters:
1569 // $rule - id(string) of selected rule
1570 // $dateTarget - target date. If blank then will test with current date as target.
1571 // $type - either 'patient_reminder' or 'clinical_reminder'
1572 // For now, will always return an array of 3 dates:
1573 // first date is before the target date (past_due) (default of 1 month)
1574 // second date is the target date (due)
1575 // third date is after the target date (soon_due) (default of 2 weeks)
1576 function calculate_reminder_dates($rule, $dateTarget='',$type) {
1578 // Set date to current if not set
1579 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1581 // Collect the current date settings (to ensure not skip)
1582 $res = resolve_reminder_sql($rule, $type.'_current');
1583 if (!empty($res)) {
1584 $row = $res[0];
1585 if ($row ['method_detail'] == "SKIP") {
1586 $dateTarget = "SKIP";
1590 // Collect the past_due date
1591 $past_due_date == "";
1592 $res = resolve_reminder_sql($rule, $type.'_post');
1593 if (!empty($res)) {
1594 $row = $res[0];
1595 if ($row ['method_detail'] == "week") {
1596 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " week"));
1598 if ($row ['method_detail'] == "month") {
1599 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " month"));
1601 if ($row ['method_detail'] == "hour") {
1602 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
1604 if ($row ['method_detail'] == "SKIP") {
1605 $past_due_date = "SKIP";
1608 else {
1609 // empty settings, so use default of one month
1610 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -1 month"));
1613 // Collect the soon_due date
1614 $soon_due_date == "";
1615 $res = resolve_reminder_sql($rule, $type.'_pre');
1616 if (!empty($res)) {
1617 $row = $res[0];
1618 if ($row ['method_detail'] == "week") {
1619 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " week"));
1621 if ($row ['method_detail'] == "month") {
1622 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " month"));
1624 if ($row ['method_detail'] == "hour") {
1625 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
1627 if ($row ['method_detail'] == "SKIP") {
1628 $soon_due_date = "SKIP";
1631 else {
1632 // empty settings, so use default of one month
1633 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +2 week"));
1636 // Return the array of three dates
1637 return array($soon_due_date,$dateTarget,$past_due_date);
1640 // Adds an action into the reminder array
1641 // Parameters:
1642 // $reminderOldArray - Contains the current array of reminders
1643 // $reminderNew - Array of a new reminder
1644 // Return:
1645 // An array of reminders
1646 function reminder_results_integrate($reminderOldArray, $reminderNew) {
1648 $results = array();
1650 // If reminderArray is empty, then insert new reminder
1651 if (empty($reminderOldArray)) {
1652 array_push($results, $reminderNew);
1653 return $results;
1656 // If duplicate reminder, then replace the old one
1657 $duplicate = false;
1658 foreach ($reminderOldArray as $reminderOld) {
1659 if ( $reminderOld['pid'] == $reminderNew['pid'] &&
1660 $reminderOld['category'] == $reminderNew['category'] &&
1661 $reminderOld['item'] == $reminderNew['item']) {
1662 array_push($results, $reminderNew);
1663 $duplicate = true;
1665 else {
1666 array_push($results, $reminderOld);
1670 // If a new reminder, then insert the new reminder
1671 if (!$duplicate) {
1672 array_push($results, $reminderNew);
1675 return $results;
1678 // Compares number of items with requested comparison operator
1679 // Parameters:
1680 // $comp - Comparison operator(eq,ne,gt,ge,lt,le)
1681 // $thres - Threshold used in comparison
1682 // $num_items - Number of items
1683 // Return:
1684 // Boolean of comparison results
1685 function itemsNumberCompare($comp, $thres, $num_items) {
1687 if ( ($comp == "eq") && ($num_items == $thres) ) {
1688 return true;
1690 else if ( ($comp == "ne") && ($num_items != $thres) && ($num_items > 0) ) {
1691 return true;
1693 else if ( ($comp == "gt") && ($num_items > $thres) ) {
1694 return true;
1696 else if ( ($comp == "ge") && ($num_items >= $thres) ) {
1697 return true;
1699 else if ( ($comp == "lt") && ($num_items < $thres) && ($num_items > 0) ) {
1700 return true;
1702 else if ( ($comp == "le") && ($num_items <= $thres) && ($num_items > 0) ) {
1703 return true;
1705 else {
1706 return false;
1710 // Converts a text comparison operator to sql equivalent
1711 // Parameters:
1712 // $comp - Comparison operator(eq,ne,gt,ge,lt,le)
1713 // Return:
1714 // String containing sql compatible comparison operator
1715 function convertCompSql($comp) {
1717 if ($comp == "eq") {
1718 return "=";
1720 else if ($comp == "ne") {
1721 return "!=";
1723 else if ($comp == "gt") {
1724 return ">";
1726 else if ($comp == "ge") {
1727 return ">=";
1729 else if ($comp == "lt") {
1730 return "<";
1732 else { // ($comp == "le")
1733 return "<=";
1737 // Function to find age in years (with decimal) on the target date
1738 // Parameters:
1739 // $dob - date of birth
1740 // $target - date to calculate age on
1741 // Return: decimal, years(decimal) from dob to target(date)
1742 function convertDobtoAgeYearDecimal($dob,$target) {
1744 // Prepare dob (Y M D)
1745 $dateDOB = explode(" ",$dob);
1747 // Prepare target (Y-M-D H:M:S)
1748 $dateTargetTemp = explode(" ",$target);
1749 $dateTarget = explode("-",$dateTargetTemp[0]);
1751 // Collect differences
1752 $iDiffYear = $dateTarget[0] - $dateDOB[0];
1753 $iDiffMonth = $dateTarget[1] - $dateDOB[1];
1754 $iDiffDay = $dateTarget[2] - $dateDOB[2];
1756 // If birthday has not happen yet for this year, subtract 1.
1757 if ($iDiffMonth < 0 || ($iDiffMonth == 0 && $iDiffDay < 0))
1759 $iDiffYear--;
1762 // Ensure diffYear is not less than 0
1763 if ($iDiffYear < 0) $iDiffYear = 0;
1765 return $iDiffYear;
1768 // Function to find age in months (with decimal) on the target date
1769 // Parameters:
1770 // $dob - date of birth
1771 // $target - date to calculate age on
1772 // Return: decimal, months(decimal) from dob to target(date)
1773 function convertDobtoAgeMonthDecimal($dob,$target) {
1775 // Prepare dob (Y M D)
1776 $dateDOB = explode(" ",$dob);
1778 // Prepare target (Y-M-D H:M:S)
1779 $dateTargetTemp = explode(" ",$target);
1780 $dateTarget = explode("-",$dateTargetTemp[0]);
1782 // Collect differences
1783 $iDiffYear = $dateTarget[0] - $dateDOB[0];
1784 $iDiffMonth = $dateTarget[1] - $dateDOB[1];
1785 $iDiffDay = $dateTarget[2] - $dateDOB[2];
1787 // If birthday has not happen yet for this year, subtract 1.
1788 if ($iDiffMonth < 0 || ($iDiffMonth == 0 && $iDiffDay < 0))
1790 $iDiffYear--;
1793 // Ensure diffYear is not less than 0
1794 if ($iDiffYear < 0) $iDiffYear = 0;
1796 return (12 * $iDiffYear) + $iDiffMonth;
1799 // Function to calculate the percentage
1800 // Parameters:
1801 // $pass_filter - number of patients that pass filter
1802 // $exclude_filter - number of patients that are excluded
1803 // $pass_target - number of patients that pass target
1804 // Return: String of a number formatted into a percentage
1805 function calculate_percentage($pass_filt,$exclude_filt,$pass_targ) {
1806 if ($pass_filt > 0) {
1807 $perc = number_format(($pass_targ/($pass_filt-$exclude_filt))*100) . xl('%');
1809 else {
1810 $perc = "0". xl('%');
1812 return $perc;