Tabs setup bug fix, take 2.
[openemr.git] / library / clinical_rules.php
blobd3844eef2a2cf10d1511ab4fedc5213a82f66130
1 <?php
2 /**
3 * Clinical Decision Rules(CDR) engine functions.
5 * These functions should not ever attempt to write to
6 * session variables, because the session_write_close() function
7 * is typically called before utilizing these functions.
9 * Copyright (C) 2010-2012 Brady Miller <brady@sparmy.com>
10 * Copyright (C) 2011 Medical Information Integration, LLC
11 * Copyright (C) 2011 Ensofttek, LLC
13 * LICENSE: This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
24 * @package OpenEMR
25 * @author Brady Miller <brady@sparmy.com>
26 * @author Medical Information Integration, LLC
27 * @author Ensofttek, LLC
28 * @link http://www.open-emr.org
31 require_once(dirname(__FILE__) . "/patient.inc");
32 require_once(dirname(__FILE__) . "/forms.inc");
33 require_once(dirname(__FILE__) . "/formdata.inc.php");
34 require_once(dirname(__FILE__) . "/options.inc.php");
35 require_once(dirname(__FILE__) . "/report_database.inc");
37 /**
38 * Return listing of CDR reminders in log.
40 * @param string $begin_date begin date (optional)
41 * @param string $end_date end date (optional)
42 * @return sqlret sql return query
44 function listingCDRReminderLog($begin_date='',$end_date='') {
46 if (empty($end_date)) {
47 $end_date=date('Y-m-d H:i:s');
50 $sqlArray = array();
51 $sql = "SELECT `date`, `pid`, `uid`, `category`, `value`, `new_value` FROM `clinical_rules_log` WHERE `date` <= ?";
52 array_push($sqlArray,$end_date);
53 if (!empty($begin_date)) {
54 $sql .= " AND `date` >= ?";
55 array_push($sqlArray,$begin_date);
57 $sql .= " ORDER BY `date` DESC";
59 return sqlStatement($sql,$sqlArray);
63 /**
64 * Display the clinical summary widget.
66 * @param integer $patient_id pid of selected patient
67 * @param string $mode choose either 'reminders-all' or 'reminders-due' (required)
68 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
69 * @param string $organize_mode Way to organize the results (default or plans)
70 * @param string $user If a user is set, then will only show rules that user has permission to see.
72 function clinical_summary_widget($patient_id,$mode,$dateTarget='',$organize_mode='default',$user='') {
74 // Set date to current if not set
75 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
77 // Collect active actions
78 $actions = test_rules_clinic('','passive_alert',$dateTarget,$mode,$patient_id,'',$organize_mode, array(),'primary',NULL,NULL,$user);
80 // Display the actions
81 $current_targets = array();
82 foreach ($actions as $action) {
84 // Deal with plan names first
85 if (isset($action['is_plan']) && $action['is_plan']) {
86 echo "<br><b>";
87 echo htmlspecialchars( xl("Plan"), ENT_NOQUOTES) . ": ";
88 echo generate_display_field(array('data_type'=>'1','list_id'=>'clinical_plans'),$action['id']);
89 echo "</b><br>";
90 continue;
93 // Collect the Rule Title, Rule Developer, Rule Funding Source, and Rule Release and show it when hover over the item.
94 $tooltip = '';
95 if (!empty($action['rule_id'])) {
96 $rule_title = getListItemTitle("clinical_rules",$action['rule_id']);
97 $ruleData = sqlQuery("SELECT `developer`, `funding_source`, `release_version`, `web_reference` " .
98 "FROM `clinical_rules` " .
99 "WHERE `id`=? AND `pid`=0", array($action['rule_id']) );
100 $developer = $ruleData['developer'];
101 $funding_source = $ruleData['funding_source'];
102 $release = $ruleData['release_version'];
103 $web_reference = $ruleData['web_reference'];
104 if (!empty($rule_title)) {
105 $tooltip = xla('Rule Title') . ": " . attr($rule_title) . "&#013;";
107 if (!empty($developer)) {
108 $tooltip .= xla('Rule Developer') . ": " . attr($developer) . "&#013;";
110 if (!empty($funding_source)) {
111 $tooltip .= xla('Rule Funding Source') . ": " . attr($funding_source) . "&#013;";
113 if (!empty($release)) {
114 $tooltip .= xla('Rule Release') . ": " . attr($release);
116 if ( (!empty($tooltip)) || (!empty($web_reference)) ) {
117 if (!empty($web_reference)) {
118 $tooltip = "<a href='".attr($web_reference)."' target='_blank' style='white-space: pre-line;' title='".$tooltip."'>?</a>";
120 else {
121 $tooltip = "<span style='white-space: pre-line;' title='".$tooltip."'>?</span>";
126 if ($action['custom_flag']) {
127 // Start link for reminders that use the custom rules input screen
128 $url = "../rules/patient_data.php?category=".htmlspecialchars( $action['category'], ENT_QUOTES);
129 $url .= "&item=".htmlspecialchars( $action['item'], ENT_QUOTES);
130 echo "<a href='".$url."' class='iframe medium_modal' onclick='top.restoreSession()'>";
132 else if ($action['clin_rem_link']) {
133 // Start link for reminders that use the custom rules input screen
134 $pieces_url = parse_url($action['clin_rem_link']);
135 $url_prefix = $pieces_url['scheme'];
136 if($url_prefix == 'https' || $url_prefix == 'http'){
137 echo "<a href='" . $action['clin_rem_link'] .
138 "' class='iframe medium_modal' onclick='top.restoreSession()'>";
139 }else{
140 echo "<a href='../../../" . $action['clin_rem_link'] .
141 "' class='iframe medium_modal' onclick='top.restoreSession()'>";
144 else {
145 // continue since no link is needed
148 // Display Reminder Details
149 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$action['category']) .
150 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$action['item']);
152 if ($action['custom_flag'] || $action['clin_rem_link']) {
153 // End link for reminders that use an html link
154 echo "</a>";
157 // Display due status
158 if ($action['due_status']) {
159 // Color code the status (red for past due, purple for due, green for not due and black for soon due)
160 if ($action['due_status'] == "past_due") {
161 echo "&nbsp;&nbsp;(<span style='color:red'>";
163 else if ($action['due_status'] == "due") {
164 echo "&nbsp;&nbsp;(<span style='color:purple'>";
166 else if ($action['due_status'] == "not_due") {
167 echo "&nbsp;&nbsp;(<span style='color:green'>";
169 else {
170 echo "&nbsp;&nbsp;(<span>";
172 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$action['due_status']) . "</span>)";
175 // Display the tooltip
176 if (!empty($tooltip)) {
177 echo "&nbsp;".$tooltip."<br>";
179 else {
180 echo "<br>";
183 // Add the target(and rule id and room for future elements as needed) to the $current_targets array.
184 // Only when $mode is reminders-due
185 if ($mode == "reminders-due" && $GLOBALS['enable_alert_log']) {
186 $target_temp = $action['category'].":".$action['item'];
187 $current_targets[$target_temp] = array('rule_id'=>$action['rule_id'],'due_status'=>$action['due_status']);
191 // Compare the current with most recent action log (this function will also log the current actions)
192 // Only when $mode is reminders-due
193 if ($mode == "reminders-due" && $GLOBALS['enable_alert_log'] ) {
194 $new_targets = compare_log_alerts($patient_id,$current_targets,'clinical_reminder_widget',$_SESSION['authId']);
195 if (!empty($new_targets) && $GLOBALS['enable_cdr_new_crp']) {
196 // If there are new action(s), then throw a popup (if the enable_cdr_new_crp global is turned on)
197 // Note I am taking advantage of a slight hack in order to run javascript within code that
198 // is being passed via an ajax call by using a dummy image.
199 echo '<img src="../../pic/empty.gif" onload="alert(\''.xls('New Due Clinical Reminders').'\n\n';
200 foreach ($new_targets as $key => $value) {
201 $category_item = explode(":",$key);
202 $category = $category_item[0];
203 $item = $category_item[1];
204 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$category) .
205 ': ' . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$item). '\n';
207 echo '\n' . '('. xls('See the Clinical Reminders widget for more details'). ')';
208 echo '\');this.parentNode.removeChild(this);" />';
214 * Display the active screen reminder.
216 * @param integer $patient_id pid of selected patient
217 * @param string $mode choose either 'reminders-all' or 'reminders-due' (required)
218 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
219 * @param string $organize_mode Way to organize the results (default or plans)
220 * @param string $user If a user is set, then will only show rules that user has permission to see
221 * @param string $test Set to true when only checking if there are alerts (skips the logging then)
222 * @return string html display output.
224 function active_alert_summary($patient_id,$mode,$dateTarget='',$organize_mode='default',$user='',$test=FALSE) {
226 // Set date to current if not set
227 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
229 // Collect active actions
230 $actions = test_rules_clinic('','active_alert',$dateTarget,$mode,$patient_id,'',$organize_mode, array(),'primary',NULL,NULL,$user);
232 if (empty($actions)) {
233 return false;
236 $returnOutput = "";
237 $current_targets = array();
239 // Display the actions
240 foreach ($actions as $action) {
242 // Deal with plan names first
243 if ($action['is_plan']) {
244 $returnOutput .= "<br><b>";
245 $returnOutput .= htmlspecialchars( xl("Plan"), ENT_NOQUOTES) . ": ";
246 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'clinical_plans'),$action['id']);
247 $returnOutput .= "</b><br>";
248 continue;
251 // Display Reminder Details
252 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$action['category']) .
253 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$action['item']);
255 // Display due status
256 if ($action['due_status']) {
257 // Color code the status (red for past due, purple for due, green for not due and black for soon due)
258 if ($action['due_status'] == "past_due") {
259 $returnOutput .= "&nbsp;&nbsp;(<span style='color:red'>";
261 else if ($action['due_status'] == "due") {
262 $returnOutput .= "&nbsp;&nbsp;(<span style='color:purple'>";
264 else if ($action['due_status'] == "not_due") {
265 $returnOutput .= "&nbsp;&nbsp;(<span style='color:green'>";
267 else {
268 $returnOutput .= "&nbsp;&nbsp;(<span>";
270 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$action['due_status']) . "</span>)<br>";
272 else {
273 $returnOutput .= "<br>";
276 // Add the target(and rule id and room for future elements as needed) to the $current_targets array.
277 // Only when $mode is reminders-due and $test is FALSE
278 if (($mode == "reminders-due") && ($test === FALSE) && ($GLOBALS['enable_alert_log'])) {
279 $target_temp = $action['category'].":".$action['item'];
280 $current_targets[$target_temp] = array('rule_id'=>$action['rule_id'],'due_status'=>$action['due_status']);
284 // Compare the current with most recent action log (this function will also log the current actions)
285 // Only when $mode is reminders-due and $test is FALSE
286 if (($mode == "reminders-due") && ($test === FALSE) && ($GLOBALS['enable_alert_log'])) {
287 $new_targets = compare_log_alerts($patient_id,$current_targets,'active_reminder_popup',$_SESSION['authId']);
288 if (!empty($new_targets)) {
289 $returnOutput .="<br>" . xlt('New Items (see above for details)') . ":<br>";
290 foreach ($new_targets as $key => $value) {
291 $category_item = explode(":",$key);
292 $category = $category_item[0];
293 $item = $category_item[1];
294 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$category) .
295 ': ' . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$item). '<br>';
300 return $returnOutput;
304 * Process and return allergy conflicts (when a active medication or presciption is on allergy list).
306 * @param integer $patient_id pid of selected patient
307 * @param string $mode either 'all' or 'new' (required)
308 * @param string $user If a user is set, then will only show rules that user has permission to see
309 * @param string $test Set to true when only checking if there are alerts (skips the logging then)
310 * @return array/boolean Array of allergy alerts or FALSE is empty.
312 function allergy_conflict($patient_id,$mode,$user,$test=FALSE) {
314 // Collect allergies
315 $res_allergies = sqlStatement("SELECT `title` FROM `lists` WHERE `type`='allergy' " .
316 "AND `activity`=1 " .
317 "AND ( `enddate` IS NULL OR `enddate`='' OR `enddate` > NOW() ) " .
318 "AND `pid`=?", array($patient_id));
319 $allergies = array();
320 for($iter=0; $row=sqlFetchArray($res_allergies); $iter++) {
321 $allergies[$iter]=$row['title'];
324 // Build sql element of IN for below queries
325 $sqlParam = array();
326 $sqlIN = '';
327 $firstFlag = TRUE;
328 foreach ($allergies as $allergy) {
329 array_push($sqlParam,$allergy);
330 if ($firstFlag) {
331 $sqlIN .= "?";
332 $firstFlag = FALSE;
334 else {
335 $sqlIN .= ",?";
339 // Check if allergies conflict with medications or prescriptions
340 $conflicts_unique = array();
341 if (!empty($sqlParam)) {
342 $conflicts = array();
343 array_push($sqlParam,$patient_id);
344 $res_meds = sqlStatement("SELECT `title` FROM `lists` WHERE `type`='medication' " .
345 "AND `activity`=1 " .
346 "AND ( `enddate` IS NULL OR `enddate`='' OR `enddate` > NOW() ) " .
347 "AND `title` IN (" . $sqlIN . ") AND `pid`=?", $sqlParam);
348 while ($urow = sqlFetchArray($res_meds)) {
349 array_push($conflicts, $urow['title']);
351 $res_rx = sqlStatement("SELECT `drug` FROM `prescriptions` WHERE `active`=1 " .
352 "AND `drug` IN (" . $sqlIN . ") AND `patient_id`=?", $sqlParam);
353 while ($urow = sqlFetchArray($res_rx)) {
354 array_push($conflicts, $urow['drug']);
356 if (!empty($conflicts)) {
357 $conflicts_unique = array_unique($conflicts);
361 // If there are conflicts, $test is FALSE, and alert logging is on, then run through compare_log_alerts
362 $new_conflicts = array();
363 if ( (!empty($conflicts_unique)) && $GLOBALS['enable_alert_log'] && ($test===FALSE) ) {
364 $new_conflicts = compare_log_alerts($patient_id,$conflicts_unique,'allergy_alert',$_SESSION['authId'],$mode);
367 if ($mode == 'all') {
368 if (!empty($conflicts_unique)) {
369 return $conflicts_unique;
371 else {
372 return FALSE;
375 else { // $mode = 'new'
376 if (!empty($new_conflicts)) {
377 return $new_conflicts;
379 else {
380 return FALSE;
386 * Compare current alerts with prior (in order to find new actions)
387 * Also functions to log the actions.
389 * @param integer $patient_id pid of selected patient
390 * @param array $current_targets array of targets
391 * @param string $category clinical_reminder_widget, active_reminder_popup, or allergy_alert
392 * @param integer $userid user id of user.
393 * @param string $log_trigger if 'all', then always log. If 'new', then only trigger log when a new item noted.
394 * @return array array with targets with associated rule.
396 function compare_log_alerts($patient_id,$current_targets,$category='clinical_reminder_widget',$userid='',$log_trigger='all') {
398 if (empty($userid)) {
399 $userid = $_SESSION['authId'];
402 if (empty($current_targets)) {
403 $current_targets = array();
406 // Collect most recent action_log
407 $prior_targets_sql = sqlQuery("SELECT `value` FROM `clinical_rules_log` " .
408 "WHERE `category` = ? AND `pid` = ? AND `uid` = ? " .
409 "ORDER BY `id` DESC LIMIT 1", array($category,$patient_id,$userid) );
410 $prior_targets = array();
411 if (!empty($prior_targets_sql['value'])) {
412 $prior_targets = json_decode($prior_targets_sql['value'], true);
415 // Compare the current with most recent log
416 if ( ($category == 'clinical_reminder_widget') || ($category == 'active_reminder_popup') ) {
417 //using fancy structure to store multiple elements
418 $new_targets = array_diff_key($current_targets,$prior_targets);
420 else { // $category == 'allergy_alert'
421 //using simple array
422 $new_targets = array_diff($current_targets,$prior_targets);
425 // Store current action_log and the new items
426 // If $log_trigger=='all'
427 // or If $log_trigger=='new' and there are new items
428 if ( ($log_trigger=='all') || (($log_trigger=='new') && (!empty($new_targets))) ) {
429 $current_targets_json = json_encode($current_targets);
430 $new_targets_json = '';
431 if (!empty($new_targets)) {
432 $new_targets_json = json_encode($new_targets);
434 sqlInsert("INSERT INTO `clinical_rules_log` " .
435 "(`date`,`pid`,`uid`,`category`,`value`,`new_value`) " .
436 "VALUES (NOW(),?,?,?,?,?)", array($patient_id,$userid,$category,$current_targets_json,$new_targets_json) );
439 // Return new actions (if there are any)
440 return $new_targets;
444 * Process clinic rules via a batching method to improve performance and decrease memory overhead.
446 * Test the clinic rules of entire clinic and create a report or patient reminders (can also test
447 * on one patient or patients of one provider). The structure of the returned results is dependent on the
448 * $organize_mode and $mode parameters.
449 * <pre>The results are dependent on the $organize_mode parameter settings
450 * 'default' organize_mode:
451 * Returns a two-dimensional array of results organized by rules (dependent on the following $mode settings):
452 * 'reminders-due' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
453 * 'reminders-all' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
454 * 'report' mode - returns an array of rows for the Clinical Quality Measures (CQM) report
455 * 'plans' organize_mode:
456 * Returns similar to default, but organizes by the active plans
457 * </pre>
459 * @param integer $provider id of a selected provider. If blank, then will test entire clinic. If 'collate_outer' or 'collate_inner', then will test each provider in entire clinic; outer will nest plans inside collated providers, while inner will nest the providers inside the plans (note inner and outer are only different if organize_mode is set to plans).
460 * @param string $type rule filter (active_alert,passive_alert,cqm,cqm_2011,cqm_2014,amc,amc_2011,amc_2014,patient_reminder). If blank then will test all rules.
461 * @param string/array $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target. If an array, then is holding two dates ('dateBegin' and 'dateTarget').
462 * @param string $mode choose either 'report' or 'reminders-all' or 'reminders-due' (required)
463 * @param string $plan test for specific plan only
464 * @param string $organize_mode Way to organize the results (default, plans). See above for organization structure of the results.
465 * @param array $options can hold various option (for now, used to hold the manual number of labs for the AMC report)
466 * @param string $pat_prov_rel How to choose patients that are related to a chosen provider. 'primary' selects patients that the provider is set as primary provider. 'encounter' selectes patients that the provider has seen. This parameter is only applicable if the $provider parameter is set to a provider or collation setting.
467 * @param integer $batchSize number of patients to batch (default is 100; plan to optimize this default setting in the future)
468 * @param integer $report_id id of report in database (if already bookmarked)
469 * @return array See above for organization structure of the results.
471 function test_rules_clinic_batch_method($provider='',$type='',$dateTarget='',$mode='',$plan='',$organize_mode='default',$options=array(),$pat_prov_rel='primary',$batchSize='',$report_id=NULL) {
473 // Default to a batchsize, if empty
474 if (empty($batchSize)) {
475 $batchSize=100;
478 // Collect total number of pertinent patients (to calculate batching parameters)
479 $totalNumPatients = buildPatientArray('',$provider,$pat_prov_rel,NULL,NULL,TRUE);
481 // Cycle through the batches and collect/combine results
482 if (($totalNumPatients%$batchSize) > 0) {
483 // not perfectly divisible
484 $totalNumberBatches = floor($totalNumPatients/$batchSize) + 1;
486 else {
487 // perfectly divisible
488 $totalNumberBatches = floor($totalNumPatients/$batchSize);
491 // Fix things in the $options array(). This now stores the number of labs to be used in the denominator in the AMC report.
492 // The problem with this variable is that is is added in every batch. So need to fix it by dividing this number by the number
493 // of planned batches(note the fixed array will go into the test_rules_clinic function, however the original will be used
494 // in the report storing/tracking engine.
495 $options_modified=$options;
496 if (!empty($options_modified['labs_manual'])) {
497 $options_modified['labs_manual'] = $options_modified['labs_manual'] / $totalNumberBatches;
500 // Prepare the database to track/store results
501 $fields = array('provider'=>$provider,'mode'=>$mode,'plan'=>$plan,'organize_mode'=>$organize_mode,'pat_prov_rel'=>$pat_prov_rel);
502 if (is_array($dateTarget)) {
503 $fields = array_merge($fields,array(date_target=>$dateTarget['dateTarget']));
504 $fields = array_merge($fields,array(date_begin=>$dateTarget['dateBegin']));
506 else {
507 if (empty($dateTarget)) {
508 $fields = array_merge($fields,array(date_target=>date("Y-m-d H:i:s")));
510 else {
511 $fields = array_merge($fields,array(date_target=>$dateTarget));
514 if (!empty($options)) {
515 foreach ($options as $key => $value) {
516 $fields = array_merge($fields, array($key=>$value));
519 $report_id = beginReportDatabase($type,$fields,$report_id);
520 setTotalItemsReportDatabase($report_id,$totalNumPatients);
522 // Set ability to itemize report if this feature is turned on
523 if ( ( ($type == "active_alert" || $type == "passive_alert") && ($GLOBALS['report_itemizing_standard']) ) ||
524 ( ($type == "cqm" || $type == "cqm_2011" || $type == "cqm_2014") && ($GLOBALS['report_itemizing_cqm']) ) ||
525 ( ($type == "amc" || $type == "amc_2011" || $type == "amc_2014" || $type == "amc_2014_stage1" || $type == "amc_2014_stage2") && ($GLOBALS['report_itemizing_amc']) ) ) {
526 $GLOBALS['report_itemizing_temp_flag_and_id'] = $report_id;
528 else {
529 $GLOBALS['report_itemizing_temp_flag_and_id'] = 0;
532 for ($i=0;$i<$totalNumberBatches;$i++) {
534 // If itemization is turned on, then reset the rule id iterator
535 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
536 $GLOBALS['report_itemized_test_id_iterator'] = 1;
539 $dataSheet_batch = test_rules_clinic($provider,$type,$dateTarget,$mode,'',$plan,$organize_mode,$options_modified,$pat_prov_rel,(($batchSize*$i)+1),$batchSize);
540 if ($i == 0) {
541 // For first cycle, simply copy it to dataSheet
542 $dataSheet = $dataSheet_batch;
544 else {
545 //debug
546 //error_log("CDR: ".print_r($dataSheet,TRUE),0);
547 //error_log("CDR: ".($batchSize*$i)." records",0);
549 // Integrate batch results into main dataSheet
550 foreach ($dataSheet_batch as $key => $row) {
551 if (!$row['is_sub']) {
552 //skip this stuff for the sub entries (and use previous main entry in percentage calculation)
553 $total_patients = $dataSheet[$key]['total_patients'] + $row['total_patients'];
554 $dataSheet[$key]['total_patients'] = $total_patients;
555 $excluded = $dataSheet[$key]['excluded'] + $row['excluded'];
556 $dataSheet[$key]['excluded'] = $excluded;
557 $pass_filter = $dataSheet[$key]['pass_filter'] + $row['pass_filter'];
558 $dataSheet[$key]['pass_filter'] = $pass_filter;
560 $pass_target = $dataSheet[$key]['pass_target'] + $row['pass_target'];
561 $dataSheet[$key]['pass_target'] = $pass_target;
562 $dataSheet[$key]['percentage'] = calculate_percentage($pass_filter,$excluded,$pass_target);
565 //Update database to track results
566 updateReportDatabase($report_id,$total_patients);
569 // Record results in database and send to screen, if applicable.
570 finishReportDatabase($report_id,json_encode($dataSheet));
571 return $dataSheet;
575 * Process clinic rules.
577 * Test the clinic rules of entire clinic and create a report or patient reminders (can also test
578 * on one patient or patients of one provider). The structure of the returned results is dependent on the
579 * $organize_mode and $mode parameters.
580 * <pre>The results are dependent on the $organize_mode parameter settings
581 * 'default' organize_mode:
582 * Returns a two-dimensional array of results organized by rules (dependent on the following $mode settings):
583 * 'reminders-due' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
584 * 'reminders-all' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
585 * 'report' mode - returns an array of rows for the Clinical Quality Measures (CQM) report
586 * 'plans' organize_mode:
587 * Returns similar to default, but organizes by the active plans
588 * </pre>
590 * @param integer $provider id of a selected provider. If blank, then will test entire clinic. If 'collate_outer' or 'collate_inner', then will test each provider in entire clinic; outer will nest plans inside collated providers, while inner will nest the providers inside the plans (note inner and outer are only different if organize_mode is set to plans).
591 * @param string $type rule filter (active_alert,passive_alert,cqm,cqm_2011,cqm_2104,amc,amc_2011,amc_2014,patient_reminder). If blank then will test all rules.
592 * @param string/array $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target. If an array, then is holding two dates ('dateBegin' and 'dateTarget').
593 * @param string $mode choose either 'report' or 'reminders-all' or 'reminders-due' (required)
594 * @param integer $patient_id pid of patient. If blank then will check all patients.
595 * @param string $plan test for specific plan only
596 * @param string $organize_mode Way to organize the results (default, plans). See above for organization structure of the results.
597 * @param array $options can hold various option (for now, used to hold the manual number of labs for the AMC report)
598 * @param string $pat_prov_rel How to choose patients that are related to a chosen provider. 'primary' selects patients that the provider is set as primary provider. 'encounter' selectes patients that the provider has seen. This parameter is only applicable if the $provider parameter is set to a provider or collation setting.
599 * @param integer $start applicable patient to start at (when batching process)
600 * @param integer $batchSize number of patients to batch (when batching process)
601 * @param string $user If a user is set, then will only show rules that user has permission to see(only applicable for per patient and not when do reports).
602 * @return array See above for organization structure of the results.
604 function test_rules_clinic($provider='',$type='',$dateTarget='',$mode='',$patient_id='',$plan='',$organize_mode='default',$options=array(),$pat_prov_rel='primary',$start=NULL,$batchSize=NULL,$user='') {
606 // If dateTarget is an array, then organize them.
607 if (is_array($dateTarget)) {
608 $dateArray = $dateTarget;
609 $dateTarget = $dateTarget['dateTarget'];
612 // Set date to current if not set
613 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
615 // Prepare the results array
616 $results = array();
618 // If set the $provider to collate_outer (or collate_inner without plans organize mode),
619 // then run through this function recursively and return results.
620 if (($provider == "collate_outer") || ($provider == "collate_inner" && $organize_mode != 'plans')) {
621 // First, collect an array of all providers
622 $query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
623 $ures = sqlStatementCdrEngine($query);
624 // Second, run through each provider recursively
625 while ($urow = sqlFetchArray($ures)) {
626 $newResults = test_rules_clinic($urow['id'],$type,$dateTarget,$mode,$patient_id,$plan,$organize_mode,$options,$pat_prov_rel,$start,$batchSize,$user);
627 if (!empty($newResults)) {
628 $provider_item['is_provider'] = TRUE;
629 $provider_item['prov_lname'] = $urow['lname'];
630 $provider_item['prov_fname'] = $urow['fname'];
631 $provider_item['npi'] = $urow['npi'];
632 $provider_item['federaltaxid'] = $urow['federaltaxid'];
633 array_push($results,$provider_item);
634 $results = array_merge($results,$newResults);
637 // done, so now can return results
638 return $results;
641 // If set organize-mode to plans, then collects active plans and run through this
642 // function recursively and return results.
643 if ($organize_mode == "plans") {
644 // First, collect active plans
645 $plans_resolve = resolve_plans_sql($plan,$patient_id);
646 // Second, run through function recursively
647 foreach ($plans_resolve as $plan_item) {
648 // (if collate_inner, then nest a collation of providers within each plan)
649 if ($provider == "collate_inner") {
650 // First, collect an array of all providers
651 $query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
652 $ures = sqlStatementCdrEngine($query);
653 // Second, run through each provider recursively
654 $provider_results = array();
655 while ($urow = sqlFetchArray($ures)) {
656 $newResults = test_rules_clinic($urow['id'],$type,$dateTarget,$mode,$patient_id,$plan_item['id'],'default',$options,$pat_prov_rel,$start,$batchSize,$user);
657 if (!empty($newResults)) {
658 $provider_item['is_provider'] = TRUE;
659 $provider_item['prov_lname'] = $urow['lname'];
660 $provider_item['prov_fname'] = $urow['fname'];
661 $provider_item['npi'] = $urow['npi'];
662 $provider_item['federaltaxid'] = $urow['federaltaxid'];
663 array_push($provider_results,$provider_item);
664 $provider_results = array_merge($provider_results,$newResults);
667 if (!empty($provider_results)) {
668 $plan_item['is_plan'] = TRUE;
669 array_push($results,$plan_item);
670 $results = array_merge($results,$provider_results);
673 else {
674 // (not collate_inner, so do not nest providers within each plan)
675 $newResults = test_rules_clinic($provider,$type,$dateTarget,$mode,$patient_id,$plan_item['id'],'default',$options,$pat_prov_rel,$start,$batchSize,$user);
676 if (!empty($newResults)) {
677 $plan_item['is_plan'] = TRUE;
678 array_push($results,$plan_item);
679 $results = array_merge($results,$newResults);
683 // done, so now can return results
684 return $results;
687 // Collect applicable patient pids
688 $patientData = array();
689 $patientData = buildPatientArray($patient_id,$provider,$pat_prov_rel,$start,$batchSize);
691 // Go through each patient(s)
693 // If in report mode, then tabulate for each rule:
694 // Total Patients
695 // Patients that pass the filter
696 // Patients that pass the target
697 // If in reminders mode, then create reminders for each rule:
698 // Reminder that action is due soon
699 // Reminder that action is due
700 // Reminder that action is post-due
702 //Collect applicable rules
703 // Note that due to a limitation in the this function, the patient_id is explicitly
704 // for grouping items when not being done in real-time or for official reporting.
705 // So for cases such as patient reminders on a clinic scale, the calling function
706 // will actually need rather than pass in a explicit patient_id for each patient in
707 // a separate call to this function.
708 if ($mode != "report") {
709 // Use per patient custom rules (if exist)
710 // Note as discussed above, this only works for single patient instances.
711 $rules = resolve_rules_sql($type,$patient_id,FALSE,$plan,$user);
713 else { // $mode = "report"
714 // Only use default rules (do not use patient custom rules)
715 $rules = resolve_rules_sql($type,$patient_id,FALSE,$plan,$user);
718 foreach( $rules as $rowRule ) {
720 // If using cqm or amc type, then use the hard-coded rules set.
721 // Note these rules are only used in report mode.
722 if ($rowRule['cqm_flag'] || $rowRule['amc_flag']) {
724 require_once( dirname(__FILE__)."/classes/rulesets/ReportManager.php");
725 $manager = new ReportManager();
726 if ($rowRule['amc_flag']) {
727 // Send array of dates ('dateBegin' and 'dateTarget')
728 $tempResults = $manager->runReport( $rowRule, $patientData, $dateArray, $options );
730 else {
731 // Send target date
732 $tempResults = $manager->runReport( $rowRule, $patientData, $dateTarget );
734 if (!empty($tempResults)) {
735 foreach ($tempResults as $tempResult) {
736 array_push($results,$tempResult);
740 // Go on to the next rule
741 continue;
744 // If in reminder mode then need to collect the measurement dates
745 // from rule_reminder table
746 $target_dates = array();
747 if ($mode != "report") {
748 // Calculate the dates to check for
749 if ($type == "patient_reminder") {
750 $reminder_interval_type = "patient_reminder";
752 else { // $type == "passive_alert" or $type == "active_alert"
753 $reminder_interval_type = "clinical_reminder";
755 $target_dates = calculate_reminder_dates($rowRule['id'], $dateTarget, $reminder_interval_type);
757 else { // $mode == "report"
758 // Only use the target date in the report
759 $target_dates[0] = $dateTarget;
762 //Reset the counters
763 $total_patients = 0;
764 $pass_filter = 0;
765 $exclude_filter = 0;
766 $pass_target = 0;
768 // Find the number of target groups
769 $targetGroups = returnTargetGroups($rowRule['id']);
771 if ( (count($targetGroups) == 1) || ($mode == "report") ) {
773 // If report itemization is turned on, then iterate the rule id iterator
774 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
775 $GLOBALS['report_itemized_test_id_iterator']++;
778 //skip this section if not report and more than one target group
779 foreach( $patientData as $rowPatient ) {
781 // First, deal with deceased patients
782 // (for now will simply skip the patient)
783 // If want to support rules for deceased patients then will need to migrate this below
784 // in target_dates foreach(guessing won't ever need to do this, though).
785 // Note using the dateTarget rather than dateFocus
786 if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
787 continue;
790 // Count the total patients
791 $total_patients++;
793 $dateCounter = 1; // for reminder mode to keep track of which date checking
794 // If report itemization is turned on, reset flag.
795 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
796 $temp_track_pass = 1;
798 foreach ( $target_dates as $dateFocus ) {
800 //Skip if date is set to SKIP
801 if ($dateFocus == "SKIP") {
802 $dateCounter++;
803 continue;
806 //Set date counter and reminder token (applicable for reminders only)
807 if ($dateCounter == 1) {
808 $reminder_due = "soon_due";
810 else if ($dateCounter == 2) {
811 $reminder_due = "due";
813 else { // $dateCounter == 3
814 $reminder_due = "past_due";
817 // Check if pass filter
818 $passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
819 if ($passFilter === "EXCLUDED") {
820 // increment EXCLUDED and pass_filter counters
821 // and set as FALSE for reminder functionality.
822 $pass_filter++;
823 $exclude_filter++;
824 $passFilter = FALSE;
826 if ($passFilter) {
827 // increment pass filter counter
828 $pass_filter++;
829 // If report itemization is turned on, trigger flag.
830 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
831 $temp_track_pass = 0;
834 else {
835 $dateCounter++;
836 continue;
839 // Check if pass target
840 $passTarget = test_targets($rowPatient['pid'],$rowRule['id'],'',$dateFocus);
841 if ($passTarget) {
842 // increment pass target counter
843 $pass_target++;
844 // If report itemization is turned on, then record the "passed" item and set the flag
845 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
846 insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 1, $rowPatient['pid']);
847 $temp_track_pass = 1;
849 // send to reminder results
850 if ($mode == "reminders-all") {
851 // place the completed actions into the reminder return array
852 $actionArray = resolve_action_sql($rowRule['id'],'1');
853 foreach ($actionArray as $action) {
854 $action_plus = $action;
855 $action_plus['due_status'] = "not_due";
856 $action_plus['pid'] = $rowPatient['pid'];
857 $action_plus['rule_id'] = $rowRule['id'];
858 $results = reminder_results_integrate($results, $action_plus);
861 break;
863 else {
864 // send to reminder results
865 if ($mode != "report") {
866 // place the uncompleted actions into the reminder return array
867 $actionArray = resolve_action_sql($rowRule['id'],'1');
868 foreach ($actionArray as $action) {
869 $action_plus = $action;
870 $action_plus['due_status'] = $reminder_due;
871 $action_plus['pid'] = $rowPatient['pid'];
872 $action_plus['rule_id'] = $rowRule['id'];
873 $results = reminder_results_integrate($results, $action_plus);
877 $dateCounter++;
879 // If report itemization is turned on, then record the "failed" item if it did not pass
880 if ($GLOBALS['report_itemizing_temp_flag_and_id'] && !($temp_track_pass)) {
881 insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 0, $rowPatient['pid']);
886 // Calculate and save the data for the rule
887 $percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
888 if ($mode == "report") {
889 $newRow=array('is_main'=>TRUE,'total_patients'=>$total_patients,'excluded'=>$exclude_filter,'pass_filter'=>$pass_filter,'pass_target'=>$pass_target,'percentage'=>$percentage);
890 $newRow=array_merge($newRow,$rowRule);
892 // If itemization is turned on, then record the itemized_test_id
893 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
894 $newRow=array_merge($newRow,array('itemized_test_id'=>$GLOBALS['report_itemized_test_id_iterator']));
897 array_push($results, $newRow);
900 // Now run through the target groups if more than one
901 if (count($targetGroups) > 1) {
902 foreach ($targetGroups as $i) {
904 // If report itemization is turned on, then iterate the rule id iterator
905 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
906 $GLOBALS['report_itemized_test_id_iterator']++;
909 //Reset the target counter
910 $pass_target = 0;
912 foreach( $patientData as $rowPatient ) {
914 // First, deal with deceased patients
915 // (for now will simply skip the patient)
916 // If want to support rules for deceased patients then will need to migrate this below
917 // in target_dates foreach(guessing won't ever need to do this, though).
918 // Note using the dateTarget rather than dateFocus
919 if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
920 continue;
923 $dateCounter = 1; // for reminder mode to keep track of which date checking
924 // If report itemization is turned on, reset flag.
925 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
926 $temp_track_pass = 1;
928 foreach ( $target_dates as $dateFocus ) {
930 //Skip if date is set to SKIP
931 if ($dateFocus == "SKIP") {
932 $dateCounter++;
933 continue;
936 //Set date counter and reminder token (applicable for reminders only)
937 if ($dateCounter == 1) {
938 $reminder_due = "soon_due";
940 else if ($dateCounter == 2) {
941 $reminder_due = "due";
943 else { // $dateCounter == 3
944 $reminder_due = "past_due";
947 // Check if pass filter
948 $passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
949 if ($passFilter === "EXCLUDED") {
950 $passFilter = FALSE;
952 if (!$passFilter) {
953 $dateCounter++;
954 continue;
956 else {
957 // If report itemization is turned on, trigger flag.
958 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
959 $temp_track_pass = 0;
963 //Check if pass target
964 $passTarget = test_targets($rowPatient['pid'],$rowRule['id'],$i,$dateFocus);
965 if ($passTarget) {
966 // increment pass target counter
967 $pass_target++;
968 // If report itemization is turned on, then record the "passed" item and set the flag
969 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
970 insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 1, $rowPatient['pid']);
971 $temp_track_pass = 1;
973 // send to reminder results
974 if ($mode == "reminders-all") {
975 // place the completed actions into the reminder return array
976 $actionArray = resolve_action_sql($rowRule['id'],$i);
977 foreach ($actionArray as $action) {
978 $action_plus = $action;
979 $action_plus['due_status'] = "not_due";
980 $action_plus['pid'] = $rowPatient['pid'];
981 $action_plus['rule_id'] = $rowRule['id'];
982 $results = reminder_results_integrate($results, $action_plus);
985 break;
987 else {
988 // send to reminder results
989 if ($mode != "report") {
990 // place the actions into the reminder return array
991 $actionArray = resolve_action_sql($rowRule['id'],$i);
992 foreach ($actionArray as $action) {
993 $action_plus = $action;
994 $action_plus['due_status'] = $reminder_due;
995 $action_plus['pid'] = $rowPatient['pid'];
996 $action_plus['rule_id'] = $rowRule['id'];
997 $results = reminder_results_integrate($results, $action_plus);
1001 $dateCounter++;
1003 // If report itemization is turned on, then record the "failed" item if it did not pass
1004 if ($GLOBALS['report_itemizing_temp_flag_and_id'] && !($temp_track_pass)) {
1005 insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 0, $rowPatient['pid']);
1009 // Calculate and save the data for the rule
1010 $percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
1012 // Collect action for title (just use the first one, if more than one)
1013 $actionArray = resolve_action_sql($rowRule['id'],$i);
1014 $action = $actionArray[0];
1015 if ($mode == "report") {
1016 $newRow=array('is_sub'=>TRUE,'action_category'=>$action['category'],'action_item'=>$action['item'],'total_patients'=>'','excluded'=>'','pass_filter'=>'','pass_target'=>$pass_target,'percentage'=>$percentage);
1018 // If itemization is turned on, then record the itemized_test_id
1019 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
1020 $newRow=array_merge($newRow,array('itemized_test_id'=>$GLOBALS['report_itemized_test_id_iterator']));
1023 array_push($results, $newRow);
1029 // Return the data
1030 return $results;
1034 * Process patient array that is to be tested.
1036 * @param integer $provider id of a selected provider. If blank, then will test entire clinic.
1037 * @param integer $patient_id pid of patient. If blank then will check all patients.
1038 * @param string $pat_prov_rel How to choose patients that are related to a chosen provider. 'primary' selects patients that the provider is set as primary provider. 'encounter' selectes patients that the provider has seen. This parameter is only applicable if the $provider parameter is set to a provider or collation setting.
1039 * @param integer $start applicable patient to start at (when batching process)
1040 * @param integer $batchSize number of patients to batch (when batching process)
1041 * @param boolean $onlyCount If true, then will just return the total number of applicable records (ignores batching parameters)
1042 * @return array/integer Array of patient pid values or number total pertinent patients (if $onlyCount is TRUE)
1044 function buildPatientArray($patient_id='',$provider='',$pat_prov_rel='primary',$start=NULL,$batchSize=NULL,$onlyCount=FALSE) {
1046 if (!empty($patient_id)) {
1047 // only look at the selected patient
1048 if ($onlyCount) {
1049 $patientNumber = 1;
1051 else {
1052 $patientData[0]['pid'] = $patient_id;
1055 else {
1056 if (empty($provider)) {
1057 // Look at entire practice
1058 if ($start == NULL || $batchSize == NULL || $onlyCount) {
1059 $rez = sqlStatementCdrEngine("SELECT `pid` FROM `patient_data` ORDER BY `pid`");
1060 if ($onlyCount) {
1061 $patientNumber = sqlNumRows($rez);
1064 else {
1065 // batching
1066 $rez = sqlStatementCdrEngine("SELECT `pid` FROM `patient_data` ORDER BY `pid` LIMIT ?,?", array(($start-1),$batchSize));
1069 else {
1070 // Look at an individual physician
1071 if( $pat_prov_rel == 'encounter' ){
1072 // Choose patients that are related to specific physician by an encounter
1073 if ($start == NULL || $batchSize == NULL || $onlyCount) {
1074 $rez = sqlStatementCdrEngine("SELECT DISTINCT `pid` FROM `form_encounter` ".
1075 " WHERE `provider_id`=? OR `supervisor_id`=? ORDER BY `pid`", array($provider,$provider));
1076 if ($onlyCount) {
1077 $patientNumber = sqlNumRows($rez);
1080 else {
1081 //batching
1082 $rez = sqlStatementCdrEngine("SELECT DISTINCT `pid` FROM `form_encounter` ".
1083 " WHERE `provider_id`=? OR `supervisor_id`=? ORDER BY `pid` LIMIT ?,?", array($provider,$provider,($start-1),$batchSize));
1086 else { //$pat_prov_rel == 'primary'
1087 // Choose patients that are assigned to the specific physician (primary physician in patient demographics)
1088 if ($start == NULL || $batchSize == NULL || $onlyCount) {
1089 $rez = sqlStatementCdrEngine("SELECT `pid` FROM `patient_data` " .
1090 "WHERE `providerID`=? ORDER BY `pid`", array($provider) );
1091 if ($onlyCount) {
1092 $patientNumber = sqlNumRows($rez);
1095 else {
1096 $rez = sqlStatementCdrEngine("SELECT `pid` FROM `patient_data` " .
1097 "WHERE `providerID`=? ORDER BY `pid` LIMIT ?,?", array($provider,($start-1),$batchSize) );
1101 // convert the sql query results into an array if returning the array
1102 if(!$onlyCount) {
1103 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
1104 $patientData[$iter]=$row;
1109 if ($onlyCount) {
1110 // return the number of applicable patients
1111 return $patientNumber;
1113 else {
1114 // return array of patient pids
1115 return $patientData;
1120 * Test filter of a selected rule on a selected patient
1122 * @param integer $patient_id pid of selected patient.
1123 * @param string $rule id(string) of selected rule
1124 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
1125 * @return boolean/string if pass filter then TRUE; if excluded then 'EXCLUDED'; if not pass filter then FALSE
1127 function test_filter($patient_id,$rule,$dateTarget) {
1129 // Set date to current if not set
1130 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1132 // Collect patient information
1133 $patientData = getPatientData($patient_id, "sex, DATE_FORMAT(DOB,'%Y %m %d') as DOB_TS");
1136 // ----------------- INCLUSIONS -----------------
1139 // -------- Age Filter (inclusion) ------------
1140 // Calculate patient age in years and months
1141 $patientAgeYears = convertDobtoAgeYearDecimal($patientData['DOB_TS'],$dateTarget);
1142 $patientAgeMonths = convertDobtoAgeMonthDecimal($patientData['DOB_TS'],$dateTarget);
1144 // Min age (year) Filter (assume that there in not more than one of each)
1145 $filter = resolve_filter_sql($rule,'filt_age_min');
1146 if (!empty($filter)) {
1147 $row = $filter[0];
1148 if ($row ['method_detail'] == "year") {
1149 if ( $row['value'] && ($row['value'] > $patientAgeYears) ) {
1150 return false;
1153 if ($row ['method_detail'] == "month") {
1154 if ( $row['value'] && ($row['value'] > $patientAgeMonths) ) {
1155 return false;
1159 // Max age (year) Filter (assume that there in not more than one of each)
1160 $filter = resolve_filter_sql($rule,'filt_age_max');
1161 if (!empty($filter)) {
1162 $row = $filter[0];
1163 if ($row ['method_detail'] == "year") {
1164 if ( $row['value'] && ($row['value'] < $patientAgeYears) ) {
1165 return false;
1168 if ($row ['method_detail'] == "month") {
1169 if ( $row['value'] && ($row['value'] < $patientAgeMonths) ) {
1170 return false;
1175 // -------- Gender Filter (inclusion) ---------
1176 // Gender Filter (assume that there in not more than one of each)
1177 $filter = resolve_filter_sql($rule,'filt_sex');
1178 if (!empty($filter)) {
1179 $row = $filter[0];
1180 if ( $row['value'] && ($row['value'] != $patientData['sex']) ) {
1181 return false;
1185 // -------- Database Filter (inclusion) ------
1186 // Database Filter
1187 $filter = resolve_filter_sql($rule,'filt_database');
1188 if ((!empty($filter)) && !database_check($patient_id,$filter,'',$dateTarget)) return false;
1190 // -------- Lists Filter (inclusion) ----
1191 // Set up lists filter, which is fully customizable and currently includes diagnoses, meds,
1192 // surgeries and allergies.
1193 $filter = resolve_filter_sql($rule,'filt_lists');
1194 if ((!empty($filter)) && !lists_check($patient_id,$filter,$dateTarget)) return false;
1196 // -------- Procedure (labs,imaging,test,procedures,etc) Filter (inlcusion) ----
1197 // Procedure Target (includes) (may need to include an interval in the future)
1198 $filter = resolve_filter_sql($rule,'filt_proc');
1199 if ((!empty($filter)) && !procedure_check($patient_id,$filter,'',$dateTarget)) return false;
1202 // ----------------- EXCLUSIONS -----------------
1205 // -------- Lists Filter (EXCLUSION) ----
1206 // Set up lists EXCLUSION filter, which is fully customizable and currently includes diagnoses, meds,
1207 // surgeries and allergies.
1208 $filter = resolve_filter_sql($rule,'filt_lists',0);
1209 if ((!empty($filter)) && lists_check($patient_id,$filter,$dateTarget)) return "EXCLUDED";
1211 // Passed all filters, so return true.
1212 return true;
1216 * Return an array containing existing group ids for a rule
1218 * @param string $rule id(string) of rule
1219 * @return array listing of group ids
1221 function returnTargetGroups($rule) {
1223 $sql = sqlStatementCdrEngine("SELECT DISTINCT `group_id` FROM `rule_target` " .
1224 "WHERE `id`=?", array($rule) );
1226 $groups = array();
1227 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1228 array_push($groups,$row['group_id']);
1230 return $groups;
1234 * Test targets of a selected rule on a selected patient
1236 * @param integer $patient_id pid of selected patient.
1237 * @param string $rule id(string) of selected rule (if blank, then will ignore grouping)
1238 * @param integer $group_id group id of target group
1239 * @param string $dateTarget target date (format Y-m-d H:i:s).
1240 * @return boolean if target passes then true, otherwise false
1242 function test_targets($patient_id,$rule,$group_id='',$dateTarget) {
1244 // -------- Interval Target ----
1245 $interval = resolve_target_sql($rule,$group_id,'target_interval');
1247 // -------- Database Target ----
1248 // Database Target (includes)
1249 $target = resolve_target_sql($rule,$group_id,'target_database');
1250 if ((!empty($target)) && !database_check($patient_id,$target,$interval,$dateTarget)) return false;
1252 // -------- Procedure (labs,imaging,test,procedures,etc) Target ----
1253 // Procedure Target (includes)
1254 $target = resolve_target_sql($rule,$group_id,'target_proc');
1255 if ((!empty($target)) && !procedure_check($patient_id,$target,$interval,$dateTarget)) return false;
1257 // -------- Appointment Target ----
1258 // Appointment Target (includes) (Specialized functionality for appointment reminders)
1259 $target = resolve_target_sql($rule,$group_id,'target_appt');
1260 if ((!empty($target)) && appointment_check($patient_id,$dateTarget)) return false;
1262 // Passed all target tests, so return true.
1263 return true;
1267 * Function to return active plans
1269 * @param string $type plan type filter (normal or cqm or blank)
1270 * @param integer $patient_id pid of selected patient. (if custom plan does not exist then will use the default plan)
1271 * @param boolean $configurableOnly true if only want the configurable (per patient) plans (ie. ignore cqm plans)
1272 * @return array active plans
1274 function resolve_plans_sql($type='',$patient_id='0',$configurableOnly=FALSE) {
1276 if ($configurableOnly) {
1277 // Collect all default, configurable (per patient) plans into an array
1278 // (ie. ignore the cqm rules)
1279 $sql = sqlStatementCdrEngine("SELECT * FROM `clinical_plans` WHERE `pid`=0 AND `cqm_flag` !=1 ORDER BY `id`");
1281 else {
1282 // Collect all default plans into an array
1283 $sql = sqlStatementCdrEngine("SELECT * FROM `clinical_plans` WHERE `pid`=0 ORDER BY `id`");
1285 $returnArray= array();
1286 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1287 array_push($returnArray,$row);
1290 // Now collect the pertinent plans
1291 $newReturnArray = array();
1293 // Need to select rules (use custom if exist)
1294 foreach ($returnArray as $plan) {
1295 $customPlan = sqlQueryCdrEngine("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan['id'],$patient_id) );
1297 // Decide if use default vs custom plan (preference given to custom plan)
1298 if (!empty($customPlan)) {
1299 if ($type == "cqm" ) {
1300 // For CQM , do not use custom plans (these are to create standard clinic wide reports)
1301 $goPlan = $plan;
1303 else {
1304 // merge the custom plan with the default plan
1305 $mergedPlan = array();
1306 foreach ($customPlan as $key => $value) {
1307 if ($value == NULL && preg_match("/_flag$/",$key)) {
1308 // use default setting
1309 $mergedPlan[$key] = $plan[$key];
1311 else {
1312 // use custom setting
1313 $mergedPlan[$key] = $value;
1316 $goPlan = $mergedPlan;
1319 else {
1320 $goPlan = $plan;
1323 // Use the chosen plan if set
1324 if (!empty($type)) {
1325 if ($goPlan["${type}_flag"] == 1) {
1326 // active, so use the plan
1327 array_push($newReturnArray,$goPlan);
1330 else {
1331 if ($goPlan['normal_flag'] == 1 ||
1332 $goPlan['cqm_flag'] == 1) {
1333 // active, so use the plan
1334 array_push($newReturnArray,$goPlan);
1338 $returnArray = $newReturnArray;
1340 return $returnArray;
1345 * Function to return a specific plan
1347 * @param string $plan id(string) of plan
1348 * @param integer $patient_id pid of selected patient. (if set to 0, then will return the default rule).
1349 * @return array a plan
1351 function collect_plan($plan,$patient_id='0') {
1353 return sqlQueryCdrEngine("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan,$patient_id) );
1358 * Function to set a specific plan activity for a specific patient
1360 * @param string $plan id(string) of plan
1361 * @param string $type plan filter (normal,cqm)
1362 * @param string $setting activity of plan (yes,no,default)
1363 * @param integer $patient_id pid of selected patient.
1365 function set_plan_activity_patient($plan,$type,$setting,$patient_id) {
1367 // Don't allow messing with the default plans here
1368 if ($patient_id == "0") {
1369 return;
1372 // Convert setting
1373 if ($setting == "on") {
1374 $setting = 1;
1376 else if ($setting == "off") {
1377 $setting = 0;
1379 else { // $setting == "default"
1380 $setting = NULL;
1383 // Collect patient specific plan, if already exists.
1384 $query = "SELECT * FROM `clinical_plans` WHERE `id` = ? AND `pid` = ?";
1385 $patient_plan = sqlQueryCdrEngine($query, array($plan,$patient_id) );
1387 if (empty($patient_plan)) {
1388 // Create a new patient specific plan with flags all set to default
1389 $query = "INSERT into `clinical_plans` (`id`, `pid`) VALUES (?,?)";
1390 sqlStatementCdrEngine($query, array($plan, $patient_id) );
1393 // Update patient specific row
1394 $query = "UPDATE `clinical_plans` SET `" . escape_sql_column_name($type."_flag",array("clinical_plans")) . "`= ? WHERE id = ? AND pid = ?";
1395 sqlStatementCdrEngine($query, array($setting,$plan,$patient_id) );
1400 * Function to return active rules
1402 * @param string $type rule filter (active_alert,passive_alert,cqm,cqm_2011,cqm_2014,amc_2011,amc_2014,patient_reminder)
1403 * @param integer $patient_id pid of selected patient. (if custom rule does not exist then will use the default rule)
1404 * @param boolean $configurableOnly true if only want the configurable (per patient) rules (ie. ignore cqm and amc rules)
1405 * @param string $plan collect rules for specific plan
1406 * @param string $user If a user is set, then will only show rules that user has permission to see
1407 * @return array rules
1409 function resolve_rules_sql($type='',$patient_id='0',$configurableOnly=FALSE,$plan='',$user='') {
1411 if ($configurableOnly) {
1412 // Collect all default, configurable (per patient) rules into an array
1413 // (ie. ignore the cqm and amc rules)
1414 $sql = sqlStatementCdrEngine("SELECT * FROM `clinical_rules` WHERE `pid`=0 AND `cqm_flag` !=1 AND `amc_flag` !=1 ORDER BY `id`");
1416 else {
1417 // Collect all default rules into an array
1418 $sql = sqlStatementCdrEngine("SELECT * FROM `clinical_rules` WHERE `pid`=0 ORDER BY `id`");
1420 $returnArray= array();
1421 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1422 array_push($returnArray,$row);
1425 // Now filter rules for plan (if applicable)
1426 if (!empty($plan)) {
1427 $planReturnArray = array();
1428 foreach ($returnArray as $rule) {
1429 $standardRule = sqlQueryCdrEngine("SELECT * FROM `clinical_plans_rules` " .
1430 "WHERE `plan_id`=? AND `rule_id`=?", array($plan,$rule['id']) );
1431 if (!empty($standardRule)) {
1432 array_push($planReturnArray,$rule);
1435 $returnArray = $planReturnArray;
1438 // Now collect the pertinent rules
1439 $newReturnArray = array();
1441 // Need to select rules (use custom if exist)
1442 foreach ($returnArray as $rule) {
1444 // If user is set, then check if user has access to the rule
1445 if (!empty($user)) {
1446 $access_control = explode(':',$rule['access_control']);
1447 if ( !empty($access_control[0]) && !empty($access_control[1]) ) {
1448 // Section and ACO filters are not empty, so do the test for access.
1449 if (!acl_check($access_control[0],$access_control[1],$user)) {
1450 // User does not have access to this rule, so skip the rule.
1451 continue;
1454 else {
1455 // Section or ACO filters are empty, so use default patients:med aco
1456 if (!acl_check('patients','med',$user)) {
1457 // User does not have access to this rule, so skip the rule.
1458 continue;
1463 $customRule = sqlQueryCdrEngine("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule['id'],$patient_id) );
1465 // Decide if use default vs custom rule (preference given to custom rule)
1466 if (!empty($customRule)) {
1467 if ($type == "cqm" || $type == "amc" ) {
1468 // For CQM and AMC, do not use custom rules (these are to create standard clinic wide reports)
1469 $goRule = $rule;
1471 else {
1472 // merge the custom rule with the default rule
1473 $mergedRule = array();
1474 foreach ($customRule as $key => $value) {
1475 if ($value == NULL && preg_match("/_flag$/",$key)) {
1476 // use default setting
1477 $mergedRule[$key] = $rule[$key];
1479 else {
1480 // use custom setting
1481 $mergedRule[$key] = $value;
1484 $goRule = $mergedRule;
1487 else {
1488 $goRule = $rule;
1491 // Use the chosen rule if set
1492 if (!empty($type)) {
1493 if ($goRule["${type}_flag"] == 1) {
1494 // active, so use the rule
1495 array_push($newReturnArray,$goRule);
1498 else {
1499 // no filter, so return the rule
1500 array_push($newReturnArray,$goRule);
1503 $returnArray = $newReturnArray;
1505 return $returnArray;
1509 * Function to return a specific rule
1511 * @param string $rule id(string) of rule
1512 * @param integer $patient_id pid of selected patient. (if set to 0, then will return the default rule).
1513 * @return array rule
1515 function collect_rule($rule,$patient_id='0') {
1517 return sqlQueryCdrEngine("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule,$patient_id) );
1522 * Function to set a specific rule activity for a specific patient
1524 * @param string $rule id(string) of rule
1525 * @param string $type rule filter (active_alert,passive_alert,cqm,amc,patient_reminder)
1526 * @param string $setting activity of rule (yes,no,default)
1527 * @param integer $patient_id pid of selected patient.
1529 function set_rule_activity_patient($rule,$type,$setting,$patient_id) {
1531 // Don't allow messing with the default rules here
1532 if ($patient_id == "0") {
1533 return;
1536 // Convert setting
1537 if ($setting == "on") {
1538 $setting = 1;
1540 else if ($setting == "off") {
1541 $setting = 0;
1543 else { // $setting == "default"
1544 $setting = NULL;
1547 //Collect main rule to allow setting of the access_control
1548 $original_query = "SELECT * FROM `clinical_rules` WHERE `id` = ? AND `pid` = 0";
1549 $patient_rule_original = sqlQueryCdrEngine($original_query, array($rule) );
1551 // Collect patient specific rule, if already exists.
1552 $query = "SELECT * FROM `clinical_rules` WHERE `id` = ? AND `pid` = ?";
1553 $patient_rule = sqlQueryCdrEngine($query, array($rule,$patient_id) );
1555 if (empty($patient_rule)) {
1556 // Create a new patient specific rule with flags all set to default
1557 $query = "INSERT into `clinical_rules` (`id`, `pid`, `access_control`) VALUES (?,?,?)";
1558 sqlStatementCdrEngine($query, array($rule, $patient_id, $patient_rule_original['access_control']) );
1561 // Update patient specific row
1562 $query = "UPDATE `clinical_rules` SET `" . add_escape_custom($type) . "_flag`= ?, `access_control` = ? WHERE id = ? AND pid = ?";
1563 sqlStatementCdrEngine($query, array($setting,$patient_rule_original['access_control'],$rule,$patient_id) );
1568 * Function to return applicable reminder dates (relative)
1570 * @param string $rule id(string) of selected rule
1571 * @param string $reminder_method string label of filter type
1572 * @return array reminder features
1574 function resolve_reminder_sql($rule,$reminder_method) {
1575 $sql = sqlStatementCdrEngine("SELECT `method_detail`, `value` FROM `rule_reminder` " .
1576 "WHERE `id`=? AND `method`=?", array($rule, $reminder_method) );
1578 $returnArray= array();
1579 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1580 array_push($returnArray,$row);
1582 return $returnArray;
1586 * Function to return applicable filters
1588 * @param string $rule id(string) of selected rule
1589 * @param string $filter_method string label of filter type
1590 * @param string $include_flag to allow selection for included or excluded filters
1591 * @return array filters
1593 function resolve_filter_sql($rule,$filter_method,$include_flag=1) {
1594 $sql = sqlStatementCdrEngine("SELECT `method_detail`, `value`, `required_flag` FROM `rule_filter` " .
1595 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $filter_method, $include_flag) );
1597 $returnArray= array();
1598 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1599 array_push($returnArray,$row);
1601 return $returnArray;
1605 * Function to return applicable targets
1607 * @param string $rule id(string) of selected rule
1608 * @param integer $group_id group id of target group (if blank, then will ignore grouping)
1609 * @param string $target_method string label of target type
1610 * @param string $include_flag to allow selection for included or excluded targets
1611 * @return array targets
1613 function resolve_target_sql($rule,$group_id='',$target_method,$include_flag=1) {
1615 if ($group_id) {
1616 $sql = sqlStatementCdrEngine("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
1617 "WHERE `id`=? AND `group_id`=? AND `method`=? AND `include_flag`=?", array($rule, $group_id, $target_method, $include_flag) );
1619 else {
1620 $sql = sqlStatementCdrEngine("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
1621 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $target_method, $include_flag) );
1624 $returnArray= array();
1625 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1626 array_push($returnArray,$row);
1628 return $returnArray;
1632 * Function to return applicable actions
1634 * @param string $rule id(string) of selected rule
1635 * @param integer $group_id group id of target group (if blank, then will ignore grouping)
1636 * @return array actions
1638 function resolve_action_sql($rule,$group_id='') {
1640 if ($group_id) {
1641 $sql = sqlStatementCdrEngine("SELECT b.category, b.item, b.clin_rem_link, b.reminder_message, b.custom_flag " .
1642 "FROM `rule_action` as a " .
1643 "JOIN `rule_action_item` as b " .
1644 "ON a.category = b.category AND a.item = b.item " .
1645 "WHERE a.id=? AND a.group_id=?", array($rule,$group_id) );
1647 else {
1648 $sql = sqlStatementCdrEngine("SELECT b.category, b.item, b.value, b.custom_flag " .
1649 "FROM `rule_action` as a " .
1650 "JOIN `rule_action_item` as b " .
1651 "ON a.category = b.category AND a.item = b.item " .
1652 "WHERE a.id=?", array($rule) );
1655 $returnArray= array();
1656 for($iter=0; $row=sqlFetchArray($sql); $iter++) {
1657 array_push($returnArray,$row);
1659 return $returnArray;
1663 * Function to check database filters and targets
1665 * @param string $patient_id pid of selected patient.
1666 * @param array $filter array containing filter/target elements
1667 * @param array $interval array containing interval elements
1668 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
1669 * @return boolean true if check passed, otherwise false
1671 function database_check($patient_id,$filter,$interval='',$dateTarget='') {
1672 $isMatch = false; //matching flag
1674 // Set date to current if not set
1675 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1677 // Unpackage interval information
1678 // (Assume only one for now and only pertinent for targets)
1679 $intervalType = '';
1680 $intervalValue = '';
1681 if (!empty($interval)) {
1682 $intervalType = $interval[0]['value'];
1683 $intervalValue = $interval[0]['interval'];
1685 $cond_loop = 0;
1686 foreach( $filter as $row ) {
1688 // Row description
1689 // [0]=>special modes
1690 $temp_df = explode("::",$row['value']);
1692 if ($temp_df[0] == "CUSTOM") {
1693 // Row description
1694 // [0]=>special modes(CUSTOM) [1]=>category [2]=>item [3]=>complete? [4]=>number of hits comparison [5]=>number of hits
1695 if (exist_custom_item($patient_id, $temp_df[1], $temp_df[2], $temp_df[3], $temp_df[4], $temp_df[5], $intervalType, $intervalValue, $dateTarget)) {
1696 // Record the match
1697 $isMatch = true;
1699 else {
1700 // If this is a required entry then return false
1701 if ($row['required_flag']) return false;
1704 else if ($temp_df[0] == "LIFESTYLE") {
1705 // Row description
1706 // [0]=>special modes(LIFESTYLE) [1]=>column [2]=>status
1707 if (exist_lifestyle_item($patient_id, $temp_df[1], $temp_df[2], $dateTarget)) {
1708 // Record the match
1709 $isMatch = true;
1711 else {
1712 // If this is a required entry then return false
1713 if ($row['required_flag']) return false;
1716 else {
1717 // Default mode
1718 // Row description
1719 // [0]=>special modes(BLANK) [1]=>table [2]=>column [3]=>value comparison [4]=>value [5]=>number of hits comparison [6]=>number of hits
1720 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)) {
1721 // Record the match
1722 if($cond_loop > 0) // For multiple condition check
1723 $isMatch = $isMatch && true;
1724 else
1725 $isMatch = true;
1727 else {
1728 // If this is a required entry then return false
1729 if ($row['required_flag']) return false;
1732 $cond_loop++;
1735 // return results of check
1736 return $isMatch;
1740 * Function to check procedure filters and targets
1742 * @param string $patient_id pid of selected patient.
1743 * @param array $filter array containing filter/target elements
1744 * @param array $interval array containing interval elements
1745 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
1746 * @return boolean true if check passed, otherwise false
1748 function procedure_check($patient_id,$filter,$interval='',$dateTarget='') {
1749 $isMatch = false; //matching flag
1751 // Set date to current if not set
1752 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1754 // Unpackage interval information
1755 // (Assume only one for now and only pertinent for targets)
1756 $intervalType = '';
1757 $intervalValue = '';
1758 if (!empty($interval)) {
1759 $intervalType = $interval[0]['value'];
1760 $intervalValue = $interval[0]['interval'];
1763 foreach( $filter as $row ) {
1764 // Row description
1765 // [0]=>title [1]=>code [2]=>value comparison [3]=>value [4]=>number of hits comparison [5]=>number of hits
1766 // code description
1767 // <type(ICD9,CPT4)>:<identifier>||<type(ICD9,CPT4)>:<identifier>||<identifier> etc.
1768 $temp_df = explode("::",$row['value']);
1769 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)) {
1770 // Record the match
1771 $isMatch = true;
1773 else {
1774 // If this is a required entry then return false
1775 if ($row['required_flag']) return false;
1779 // return results of check
1780 return $isMatch;
1784 * Function to check for appointment
1786 * @todo Complete this to allow appointment reminders.
1787 * @param string $patient_id pid of selected patient.
1788 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
1789 * @return boolean true if appt exist, otherwise false
1791 function appointment_check($patient_id,$dateTarget='') {
1792 $isMatch = false; //matching flag
1794 // Set date to current if not set (although should always be set)
1795 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1796 $dateTargetRound = date('Y-m-d',$dateTarget);
1798 // Set current date
1799 $currentDate = date('Y-m-d H:i:s');
1800 $currentDateRound = date('Y-m-d',$dateCurrent);
1802 // Basically, if the appointment is within the current date to the target date,
1803 // then return true. (will not send reminders on same day as appointment)
1804 $sql = sqlStatementCdrEngine("SELECT openemr_postcalendar_events.pc_eid, " .
1805 "openemr_postcalendar_events.pc_title, " .
1806 "openemr_postcalendar_events.pc_eventDate, " .
1807 "openemr_postcalendar_events.pc_startTime, " .
1808 "openemr_postcalendar_events.pc_endTime " .
1809 "FROM openemr_postcalendar_events " .
1810 "WHERE openemr_postcalendar_events.pc_eventDate > ? " .
1811 "AND openemr_postcalendar_events.pc_eventDate <= ? " .
1812 "AND openemr_postcalendar_events.pc_pid = ?", array($currentDate,$dateTarget,$patient_id) );
1814 // return results of check
1816 // TODO: Figure out how to have multiple appointment and changing appointment reminders.
1817 // Plan to send back array of appt info (eid, time, date, etc.)
1818 // to do this.
1819 if (sqlNumRows($sql) > 0) {
1820 $isMatch = true;
1823 return $isMatch;
1827 * Function to check lists filters and targets. Customizable and currently includes diagnoses, medications, allergies and surgeries.
1829 * @param string $patient_id pid of selected patient.
1830 * @param array $filter array containing lists filter/target elements
1831 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
1832 * @return boolean true if check passed, otherwise false
1834 function lists_check($patient_id,$filter,$dateTarget) {
1835 $isMatch = false; //matching flag
1837 // Set date to current if not set
1838 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1840 foreach ( $filter as $row ) {
1841 if (exist_lists_item($patient_id, $row['method_detail'], $row['value'], $dateTarget)) {
1842 // Record the match
1843 $isMatch = true;
1845 else {
1846 // If this is a required entry then return false
1847 if ($row['required_flag']) return false;
1851 // return results of check
1852 return $isMatch;
1856 * Function to check for existance of data in database for a patient
1858 * @param string $patient_id pid of selected patient.
1859 * @param string $table selected mysql table
1860 * @param string $column selected mysql column
1861 * @param string $data_comp data comparison (eq,ne,gt,ge,lt,le)
1862 * @param string $data selected data in the mysql database
1863 * @param string $num_items_comp number items comparison (eq,ne,gt,ge,lt,le)
1864 * @param integer $num_items_thres number of items threshold
1865 * @param string $intervalType type of interval (ie. year)
1866 * @param integer $intervalValue searched for within this many times of the interval type
1867 * @param string $dateTarget target date(format Y-m-d H:i:s).
1868 * @return boolean true if check passed, otherwise false
1870 function exist_database_item($patient_id,$table,$column='',$data_comp,$data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
1872 // Set date to current if not set
1873 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1875 // Collect the correct column label for patient id in the table
1876 $patient_id_label = collect_database_label('pid',$table);
1878 // Get the interval sql query string
1879 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1881 // If just checking for existence (ie. data is empty),
1882 // then simply set the comparison operator to ne.
1883 if (empty($data)) {
1884 $data_comp = "ne";
1887 // get the appropriate sql comparison operator
1888 $compSql = convertCompSql($data_comp);
1890 // custom issues per table can be placed here
1891 $customSQL = '';
1892 if ($table == 'immunizations') {
1893 $customSQL = " AND `added_erroneously` = '0' ";
1896 //adding table list for where condition
1897 $whereTables = '';
1898 if($table == 'procedure_result'){
1899 $whereTables = ", procedure_order_code, " .
1900 "procedure_order, " .
1901 "procedure_report " ;
1902 $customSQL = " AND procedure_order.procedure_order_id = procedure_order_code.procedure_order_id AND " .
1903 "procedure_report.procedure_order_id = procedure_order.procedure_order_id AND " .
1904 "procedure_report.procedure_order_seq = procedure_order_code.procedure_order_seq AND " .
1905 "procedure_result.procedure_report_id = procedure_report.procedure_report_id ";
1908 // check for items
1909 if (empty($column)) {
1910 // simple search for any table entries
1911 $sql = sqlStatementCdrEngine("SELECT * " .
1912 "FROM `" . add_escape_custom($table) . "` " .
1913 " ". $whereTables. " ".
1914 "WHERE " . add_escape_custom($patient_id_label) . "=? " . $customSQL, array($patient_id) );
1916 else {
1917 // search for number of specific items
1918 $sql = sqlStatementCdrEngine("SELECT `" . add_escape_custom($column) . "` " .
1919 "FROM `" . add_escape_custom($table) . "` " .
1920 " ". $whereTables. " ".
1921 "WHERE `" . add_escape_custom($column) ."`" . $compSql . "? " .
1922 "AND " . add_escape_custom($patient_id_label) . "=? " . $customSQL .
1923 $dateSql, array($data,$patient_id) );
1926 // See if number of returned items passes the comparison
1927 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1931 * Function to check for existence of procedure(s) for a patient
1933 * @param string $patient_id pid of selected patient.
1934 * @param string $proc_title procedure title
1935 * @param string $proc_code procedure identifier code (array of <type(ICD9,CPT4)>:<identifier>||<type(ICD9,CPT4)>:<identifier>||<identifier> etc.)
1936 * @param string $results_comp results comparison (eq,ne,gt,ge,lt,le)
1937 * @param string $result_data results data
1938 * @param string $num_items_comp number items comparison (eq,ne,gt,ge,lt,le)
1939 * @param integer $num_items_thres number of items threshold
1940 * @param string $intervalType type of interval (ie. year)
1941 * @param integer $intervalValue searched for within this many times of the interval type
1942 * @param string $dateTarget target date(format Y-m-d H:i:s).
1943 * @return boolean true if check passed, otherwise false
1945 function exist_procedure_item($patient_id,$proc_title,$proc_code,$result_comp,$result_data='',$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget='') {
1947 // Set date to current if not set
1948 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1950 // Set the table exception (for looking up pertinent date and pid sql columns)
1951 $table = "PROCEDURE-EXCEPTION";
1953 // Collect the correct column label for patient id in the table
1954 $patient_id_label = collect_database_label('pid',$table);
1956 // Get the interval sql query string
1957 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
1959 // If just checking for existence (ie result_data is empty),
1960 // then simply set the comparison operator to ne.
1961 if (empty($result_data)) {
1962 $result_comp = "ne";
1965 // get the appropriate sql comparison operator
1966 $compSql = convertCompSql($result_comp);
1968 // explode the code array
1969 $codes= array();
1970 if (!empty($proc_code)) {
1971 $codes = explode("||",$proc_code);
1973 else {
1974 $codes[0] = '';
1977 // ensure proc_title is at least blank
1978 if (empty($proc_title)) {
1979 $proc_title = '';
1982 // collect specific items (use both title and/or codes) that fulfill request
1983 $sqlBindArray=array();
1984 $sql_query = "SELECT procedure_result.result FROM " .
1985 "procedure_order_code, " .
1986 "procedure_order, " .
1987 "procedure_type, " .
1988 "procedure_report, " .
1989 "procedure_result " .
1990 "WHERE " .
1991 "procedure_order_code.procedure_code = procedure_type.procedure_code AND " .
1992 "procedure_order.procedure_order_id = procedure_order_code.procedure_order_id AND " .
1993 "procedure_order.lab_id = procedure_type.lab_id AND " .
1994 "procedure_report.procedure_order_id = procedure_order.procedure_order_id AND " .
1995 "procedure_report.procedure_order_seq = procedure_order_code.procedure_order_seq AND " .
1996 "procedure_result.procedure_report_id = procedure_report.procedure_report_id AND " .
1997 "procedure_type.procedure_type = 'ord' AND ";
1998 foreach ($codes as $tem) {
1999 $sql_query .= "( ( (procedure_type.standard_code = ? AND procedure_type.standard_code != '') " .
2000 "OR (procedure_type.procedure_code = ? AND procedure_type.procedure_code != '') ) OR ";
2001 array_push($sqlBindArray,$tem,$tem);
2003 $sql_query .= "(procedure_type.name = ? AND procedure_type.name != '') ) " .
2004 "AND procedure_result.result " . $compSql . " ? " .
2005 "AND " . add_escape_custom($patient_id_label) . " = ? " . $dateSql;
2006 array_push($sqlBindArray,$proc_title,$result_data,$patient_id);
2008 $sql = sqlStatementCdrEngine($sql_query,$sqlBindArray);
2010 // See if number of returned items passes the comparison
2011 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
2015 * Function to check for existance of data for a patient in the rule_patient_data table
2017 * @param string $patient_id pid of selected patient.
2018 * @param string $category label in category column
2019 * @param string $item label in item column
2020 * @param string $complete label in complete column (YES,NO, or blank)
2021 * @param string $num_items_comp number items comparison (eq,ne,gt,ge,lt,le)
2022 * @param integer $num_items_thres number of items threshold
2023 * @param string $intervalType type of interval (ie. year)
2024 * @param integer $intervalValue searched for within this many times of the interval type
2025 * @param string $dateTarget target date(format Y-m-d H:i:s).
2026 * @return boolean true if check passed, otherwise false
2028 function exist_custom_item($patient_id,$category,$item,$complete,$num_items_comp,$num_items_thres,$intervalType='',$intervalValue='',$dateTarget) {
2030 // Set the table
2031 $table = 'rule_patient_data';
2033 // Collect the correct column label for patient id in the table
2034 $patient_id_label = collect_database_label('pid',$table);
2036 // Get the interval sql query string
2037 $dateSql = sql_interval_string($table,$intervalType,$intervalValue,$dateTarget);
2039 // search for number of specific items
2040 $sql = sqlStatementCdrEngine("SELECT `result` " .
2041 "FROM `" . add_escape_custom($table) . "` " .
2042 "WHERE `category`=? " .
2043 "AND `item`=? " .
2044 "AND `complete`=? " .
2045 "AND `" . add_escape_custom($patient_id_label) . "`=? " .
2046 $dateSql, array($category,$item,$complete,$patient_id) );
2048 // See if number of returned items passes the comparison
2049 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
2053 * Function to check for existance of data for a patient in lifestyle section
2055 * @param string $patient_id pid of selected patient.
2056 * @param string $lifestyle selected label of mysql column of patient history
2057 * @param string $status specific status of selected lifestyle element
2058 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
2059 * @return boolean true if check passed, otherwise false
2061 function exist_lifestyle_item($patient_id,$lifestyle,$status,$dateTarget) {
2063 // Set date to current if not set
2064 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
2066 // Collect pertinent history data
2067 $history = getHistoryData($patient_id, $lifestyle,'',$dateTarget);
2069 // See if match
2070 $stringFlag = strstr($history[$lifestyle], "|".$status);
2071 if (empty($status)) {
2072 // Only ensuring any data has been entered into the field
2073 $stringFlag = true;
2075 if ( $history[$lifestyle] &&
2076 $history[$lifestyle] != '|0|' &&
2077 $stringFlag ) {
2078 return true;
2080 else {
2081 return false;
2086 * Function to check for lists item of a patient. Fully customizable and includes diagnoses, medications,
2087 * allergies, and surgeries.
2089 * @param string $patient_id pid of selected patient.
2090 * @param string $type type (medical_problem, allergy, medication, etc)
2091 * @param string $value value searching for
2092 * @param string $dateTarget target date(format Y-m-d H:i:s).
2093 * @return boolean true if check passed, otherwise false
2095 function exist_lists_item($patient_id,$type,$value,$dateTarget) {
2097 // Set date to current if not set
2098 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
2100 // Attempt to explode the value into a code type and code (if applicable)
2101 $value_array = explode("::",$value);
2102 if (count($value_array) == 2) {
2104 // Collect the code type and code
2105 $code_type = $value_array[0];
2106 $code = $value_array[1];
2108 if ($code_type=='CUSTOM') {
2109 // Deal with custom code type first (title column in lists table)
2110 $response = sqlQueryCdrEngine("SELECT * FROM `lists` " .
2111 "WHERE `type`=? " .
2112 "AND `pid`=? " .
2113 "AND `title`=? " .
2114 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
2115 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$code,$dateTarget,$dateTarget,$dateTarget) );
2116 if (!empty($response)) return true;
2118 else {
2119 // Deal with the set code types (diagnosis column in lists table)
2120 $response = sqlQueryCdrEngine("SELECT * FROM `lists` " .
2121 "WHERE `type`=? " .
2122 "AND `pid`=? " .
2123 "AND `diagnosis` LIKE ? " .
2124 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
2125 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,"%".$code_type.":".$code."%",$dateTarget,$dateTarget,$dateTarget) );
2126 if (!empty($response)) return true;
2129 else { // count($value_array) == 1
2130 // Search the title column in lists table
2131 // Yes, this is essentially the same as the code type listed as CUSTOM above. This provides flexibility and will ensure compatibility.
2132 $response = sqlQueryCdrEngine("SELECT * FROM `lists` " .
2133 "WHERE `type`=? " .
2134 "AND `pid`=? " .
2135 "AND `title`=? ".
2136 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
2137 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$value,$dateTarget,$dateTarget,$dateTarget) );
2138 if (!empty($response)) return true;
2140 if($type == 'medication'){ // Special case needed for medication as it need to be looked into current medications (prescriptions table) from ccda import
2141 $response = sqlQueryCdrEngine("SELECT * FROM `prescriptions` where `patient_id` = ? and `drug` = ? and `date_added` <= ?", array($patient_id,$value,$dateTarget));
2142 if(!empty($response)) return true;
2146 return false;
2150 * Function to return part of sql query to deal with interval
2152 * @param string $table selected mysql table (or EXCEPTION(s))
2153 * @param string $intervalType type of interval (ie. year)
2154 * @param string $intervalValue searched for within this many times of the interval type
2155 * @param string $dateTarget target date(format Y-m-d H:i:s).
2156 * @return string contains pertinent date interval filter for mysql query
2158 function sql_interval_string($table,$intervalType,$intervalValue,$dateTarget) {
2160 $dateSql="";
2162 // Collect the correct column label for date in the table
2163 $date_label = collect_database_label('date',$table);
2165 // Deal with interval
2166 if (!empty($intervalType)) {
2167 switch($intervalType) {
2168 case "year":
2169 $dateSql = "AND (" . add_escape_custom($date_label) .
2170 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2171 "', INTERVAL " . add_escape_custom($intervalValue) .
2172 " YEAR) AND '" . add_escape_custom($dateTarget) . "') ";
2173 break;
2174 case "month":
2175 $dateSql = "AND (" . add_escape_custom($date_label) .
2176 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2177 "', INTERVAL " . add_escape_custom($intervalValue) .
2178 " MONTH) AND '" . add_escape_custom($dateTarget) . "') ";
2179 break;
2180 case "week":
2181 $dateSql = "AND (" . add_escape_custom($date_label) .
2182 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2183 "', INTERVAL " . add_escape_custom($intervalValue) .
2184 " WEEK) AND '" . add_escape_custom($dateTarget) . "') ";
2185 break;
2186 case "day":
2187 $dateSql = "AND (" . add_escape_custom($date_label) .
2188 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2189 "', INTERVAL " . add_escape_custom($intervalValue) .
2190 " DAY) AND '" . add_escape_custom($dateTarget) . "') ";
2191 break;
2192 case "hour":
2193 $dateSql = "AND (" . add_escape_custom($date_label) .
2194 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2195 "', INTERVAL " . add_escape_custom($intervalValue) .
2196 " HOUR) AND '" . add_escape_custom($dateTarget) . "') ";
2197 break;
2198 case "minute":
2199 $dateSql = "AND (" . add_escape_custom($date_label) .
2200 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2201 "', INTERVAL " . add_escape_custom($intervalValue) .
2202 " MINUTE) AND '" . add_escape_custom($dateTarget) . "') ";
2203 break;
2204 case "second":
2205 $dateSql = "AND (" . add_escape_custom($date_label) .
2206 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2207 "', INTERVAL " . add_escape_custom($intervalValue) .
2208 " SECOND) AND '" . add_escape_custom($dateTarget) . "') ";
2209 break;
2210 case "flu_season":
2211 // Flu season to be hard-coded as September thru February
2212 // (Should make this modifiable in the future)
2213 // ($intervalValue is not used)
2214 $dateArray = explode("-",$dateTarget);
2215 $Year = $dateArray[0];
2216 $dateThisYear = $Year . "-09-01";
2217 $dateLastYear = ($Year-1) . "-09-01";
2218 $dateSql =" " .
2219 "AND ((" .
2220 "MONTH('" . add_escape_custom($dateTarget) . "') < 9 " .
2221 "AND " . add_escape_custom($date_label) . " >= '" . $dateLastYear . "' ) " .
2222 "OR (" .
2223 "MONTH('" . add_escape_custom($dateTarget) . "') >= 9 " .
2224 "AND " . add_escape_custom($date_label) . " >= '" . $dateThisYear . "' ))" .
2225 "AND " . add_escape_custom($date_label) . " <= '" . add_escape_custom($dateTarget) . "' ";
2226 break;
2229 else {
2230 $dateSql = "AND " . add_escape_custom($date_label) .
2231 " <= '" . add_escape_custom($dateTarget) . "' ";
2234 // return the sql interval string
2235 return $dateSql;
2239 * Function to collect generic column labels from tables. It currently works for date
2240 * and pid. Will need to expand this as algorithm grows.
2242 * @param string $label element (pid or date)
2243 * @param string $table selected mysql table (or EXCEPTION(s))
2244 * @return string contains official label of selected element
2246 function collect_database_label($label,$table) {
2248 if ($table == 'PROCEDURE-EXCEPTION') {
2249 // return cell to get procedure collection
2250 // special case since reuqires joing of multiple
2251 // tables to get this value
2252 if ($label == "pid") {
2253 $returnedLabel = "procedure_order.patient_id";
2255 else if ($label == "date") {
2256 $returnedLabel = "procedure_report.date_collected";
2258 else {
2259 // unknown label, so return the original label
2260 $returnedLabel = $label;
2263 else if ($table == 'immunizations') {
2264 // return requested label for immunization table
2265 if ($label == "pid") {
2266 $returnedLabel = "patient_id";
2268 else if ($label == "date") {
2269 $returnedLabel = "`administered_date`";
2271 else {
2272 // unknown label, so return the original label
2273 $returnedLabel = $label;
2276 else if ($table == 'prescriptions'){
2277 // return requested label for prescriptions table
2278 if ($label == "pid") {
2279 $returnedLabel = "patient_id";
2281 else if ($label == "date") {
2282 $returnedLabel = 'date_added';
2284 else{
2285 // unknown label, so return the original label
2286 $returnedLabel = $label;
2289 else if($table == 'procedure_result'){
2290 // return requested label for prescriptions table
2291 if ($label == "pid") {
2292 $returnedLabel = "procedure_order.patient_id";
2294 else if ($label == "date") {
2295 $returnedLabel = "procedure_report.date_collected";
2297 else {
2298 // unknown label, so return the original label
2299 $returnedLabel = $label;
2302 else {
2303 // return requested label for default tables
2304 if ($label == "pid") {
2305 $returnedLabel = "pid";
2307 else if ($label == "date") {
2308 $returnedLabel = "`date`";
2310 else {
2311 // unknown label, so return the original label
2312 $returnedLabel = $label;
2316 return $returnedLabel;
2320 * Simple function to avoid processing of duplicate actions
2322 * @param string $actions 2-dimensional array with all current active targets
2323 * @param string $action array of selected target to test for duplicate
2324 * @return boolean true if duplicate, false if not duplicate
2326 function is_duplicate_action($actions,$action) {
2327 foreach ($actions as $row) {
2328 if ($row['category'] == $action['category'] &&
2329 $row['item'] == $action['item'] &&
2330 $row['value'] == $action['value']) {
2331 // Is a duplicate
2332 return true;
2336 // Not a duplicate
2337 return false;
2341 * Calculate the reminder dates.
2343 * This function returns an array that contains three elements (each element is a date).
2344 * <pre>The three dates are:
2345 * first date is before the target date (past_due) (default of 1 month)
2346 * second date is the target date (due)
2347 * third date is after the target date (soon_due) (default of 2 weeks)
2348 * </pre>
2350 * @param string $rule id(string) of selected rule
2351 * @param string $dateTarget target date(format Y-m-d H:i:s).
2352 * @param string $type either 'patient_reminder' or 'clinical_reminder'
2353 * @return array see above for description of returned array
2355 function calculate_reminder_dates($rule, $dateTarget='',$type) {
2357 // Set date to current if not set
2358 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
2360 // Collect the current date settings (to ensure not skip)
2361 $res = resolve_reminder_sql($rule, $type.'_current');
2362 if (!empty($res)) {
2363 $row = $res[0];
2364 if ($row ['method_detail'] == "SKIP") {
2365 $dateTarget = "SKIP";
2369 // Collect the past_due date
2370 $past_due_date = "";
2371 $res = resolve_reminder_sql($rule, $type.'_post');
2372 if (!empty($res)) {
2373 $row = $res[0];
2374 if ($row ['method_detail'] == "week") {
2375 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " week"));
2377 if ($row ['method_detail'] == "month") {
2378 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " month"));
2380 if ($row ['method_detail'] == "hour") {
2381 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
2383 if ($row ['method_detail'] == "SKIP") {
2384 $past_due_date = "SKIP";
2387 else {
2388 // empty settings, so use default of one month
2389 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -1 month"));
2392 // Collect the soon_due date
2393 $soon_due_date = "";
2394 $res = resolve_reminder_sql($rule, $type.'_pre');
2395 if (!empty($res)) {
2396 $row = $res[0];
2397 if ($row ['method_detail'] == "week") {
2398 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " week"));
2400 if ($row ['method_detail'] == "month") {
2401 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " month"));
2403 if ($row ['method_detail'] == "hour") {
2404 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
2406 if ($row ['method_detail'] == "SKIP") {
2407 $soon_due_date = "SKIP";
2410 else {
2411 // empty settings, so use default of one month
2412 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +2 week"));
2415 // Return the array of three dates
2416 return array($soon_due_date,$dateTarget,$past_due_date);
2420 * Adds an action into the reminder array
2422 * @param array $reminderOldArray Contains the current array of reminders
2423 * @param array $reminderNew Array of a new reminder
2424 * @return array Reminders
2426 function reminder_results_integrate($reminderOldArray, $reminderNew) {
2428 $results = array();
2430 // If reminderArray is empty, then insert new reminder
2431 if (empty($reminderOldArray)) {
2432 array_push($results, $reminderNew);
2433 return $results;
2436 // If duplicate reminder, then replace the old one
2437 $duplicate = false;
2438 foreach ($reminderOldArray as $reminderOld) {
2439 if ( $reminderOld['pid'] == $reminderNew['pid'] &&
2440 $reminderOld['category'] == $reminderNew['category'] &&
2441 $reminderOld['item'] == $reminderNew['item']) {
2442 array_push($results, $reminderNew);
2443 $duplicate = true;
2445 else {
2446 array_push($results, $reminderOld);
2450 // If a new reminder, then insert the new reminder
2451 if (!$duplicate) {
2452 array_push($results, $reminderNew);
2455 return $results;
2459 * Compares number of items with requested comparison operator
2461 * @param string $comp Comparison operator(eq,ne,gt,ge,lt,le)
2462 * @param string $thres Threshold used in comparison
2463 * @param integer $num_items Number of items
2464 * @return boolean Comparison results
2466 function itemsNumberCompare($comp, $thres, $num_items) {
2468 if ( ($comp == "eq") && ($num_items == $thres) ) {
2469 return true;
2471 else if ( ($comp == "ne") && ($num_items != $thres) && ($num_items > 0) ) {
2472 return true;
2474 else if ( ($comp == "gt") && ($num_items > $thres) ) {
2475 return true;
2477 else if ( ($comp == "ge") && ($num_items >= $thres) ) {
2478 return true;
2480 else if ( ($comp == "lt") && ($num_items < $thres) && ($num_items > 0) ) {
2481 return true;
2483 else if ( ($comp == "le") && ($num_items <= $thres) && ($num_items > 0) ) {
2484 return true;
2486 else {
2487 return false;
2492 * Converts a text comparison operator to sql equivalent
2494 * @param string $comp Comparison operator(eq,ne,gt,ge,lt,le)
2495 * @return string contains sql compatible comparison operator
2497 function convertCompSql($comp) {
2499 if ($comp == "eq") {
2500 return "=";
2502 else if ($comp == "ne") {
2503 return "!=";
2505 else if ($comp == "gt") {
2506 return ">";
2508 else if ($comp == "ge") {
2509 return ">=";
2511 else if ($comp == "lt") {
2512 return "<";
2514 else { // ($comp == "le")
2515 return "<=";
2521 * Function to find age in years (with decimal) on the target date
2523 * @param string $dob date of birth
2524 * @param string $target date to calculate age on
2525 * @return float years(decimal) from dob to target(date)
2527 function convertDobtoAgeYearDecimal($dob,$target) {
2528 $ageInfo=parseAgeInfo($dob,$target);
2529 return $ageInfo['age'];
2533 * Function to find age in months (with decimal) on the target date
2535 * @param string $dob date of birth
2536 * @param string $target date to calculate age on
2537 * @return float months(decimal) from dob to target(date)
2539 function convertDobtoAgeMonthDecimal($dob,$target) {
2540 $ageInfo=parseAgeInfo($dob,$target);
2541 return $ageInfo['age_in_months'];
2545 * Function to calculate the percentage for reports.
2547 * @param integer $pass_filter number of patients that pass filter
2548 * @param integer $exclude_filter number of patients that are excluded
2549 * @param integer $pass_target number of patients that pass target
2550 * @return string Number formatted into a percentage
2552 function calculate_percentage($pass_filt,$exclude_filt,$pass_targ) {
2553 if ($pass_filt > 0) {
2554 $perc = number_format(($pass_targ/($pass_filt-$exclude_filt))*100,4) . xl('%');
2556 else {
2557 $perc = "0". xl('%');
2559 return $perc;