Highway to PSR2
[openemr.git] / library / clinical_rules.php
blob86b8a132060bf72c4aae903e6cba9b33be558fb7
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.g.miller@gmail.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.g.miller@gmail.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__) . "/options.inc.php");
34 require_once(dirname(__FILE__) . "/report_database.inc");
36 /**
37 * Return listing of CDR reminders in log.
39 * @param string $begin_date begin date (optional)
40 * @param string $end_date end date (optional)
41 * @return sqlret sql return query
43 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);
58 $sql .= " ORDER BY `date` DESC";
60 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 = '')
75 // Set date to current if not set
76 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
78 // Collect active actions
79 $actions = test_rules_clinic('', 'passive_alert', $dateTarget, $mode, $patient_id, '', $organize_mode, array(), 'primary', null, null, $user);
81 // Display the actions
82 $current_targets = array();
83 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;";
108 if (!empty($developer)) {
109 $tooltip .= xla('Rule Developer') . ": " . attr($developer) . "&#013;";
112 if (!empty($funding_source)) {
113 $tooltip .= xla('Rule Funding Source') . ": " . attr($funding_source) . "&#013;";
116 if (!empty($release)) {
117 $tooltip .= xla('Rule Release') . ": " . attr($release);
120 if ((!empty($tooltip)) || (!empty($web_reference))) {
121 if (!empty($web_reference)) {
122 $tooltip = "<a href='".attr($web_reference)."' target='_blank' style='white-space: pre-line;' title='".$tooltip."'>?</a>";
123 } else {
124 $tooltip = "<span style='white-space: pre-line;' title='".$tooltip."'>?</span>";
129 if ($action['custom_flag']) {
130 // Start link for reminders that use the custom rules input screen
131 $url = "../rules/patient_data.php?category=".htmlspecialchars($action['category'], ENT_QUOTES);
132 $url .= "&item=".htmlspecialchars($action['item'], ENT_QUOTES);
133 echo "<a href='".$url."' class='iframe medium_modal' onclick='top.restoreSession()'>";
134 } else if ($action['clin_rem_link']) {
135 // Start link for reminders that use the custom rules input screen
136 $pieces_url = parse_url($action['clin_rem_link']);
137 $url_prefix = $pieces_url['scheme'];
138 if ($url_prefix == 'https' || $url_prefix == 'http') {
139 echo "<a href='" . $action['clin_rem_link'] .
140 "' class='iframe medium_modal' onclick='top.restoreSession()'>";
141 } else {
142 echo "<a href='../../../" . $action['clin_rem_link'] .
143 "' class='iframe medium_modal' onclick='top.restoreSession()'>";
145 } else {
146 // continue since no link is needed
149 // Display Reminder Details
150 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'), $action['category']) .
151 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'), $action['item']);
153 if ($action['custom_flag'] || $action['clin_rem_link']) {
154 // End link for reminders that use an html link
155 echo "</a>";
158 // Display due status
159 if ($action['due_status']) {
160 // Color code the status (red for past due, purple for due, green for not due and black for soon due)
161 if ($action['due_status'] == "past_due") {
162 echo "&nbsp;&nbsp;(<span style='color:red'>";
163 } else if ($action['due_status'] == "due") {
164 echo "&nbsp;&nbsp;(<span style='color:purple'>";
165 } else if ($action['due_status'] == "not_due") {
166 echo "&nbsp;&nbsp;(<span style='color:green'>";
167 } else {
168 echo "&nbsp;&nbsp;(<span>";
171 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'), $action['due_status']) . "</span>)";
174 // Display the tooltip
175 if (!empty($tooltip)) {
176 echo "&nbsp;".$tooltip."<br>";
177 } else {
178 echo "<br>";
181 // Add the target(and rule id and room for future elements as needed) to the $current_targets array.
182 // Only when $mode is reminders-due
183 if ($mode == "reminders-due" && $GLOBALS['enable_alert_log']) {
184 $target_temp = $action['category'].":".$action['item'];
185 $current_targets[$target_temp] = array('rule_id'=>$action['rule_id'],'due_status'=>$action['due_status']);
189 // Compare the current with most recent action log (this function will also log the current actions)
190 // Only when $mode is reminders-due
191 if ($mode == "reminders-due" && $GLOBALS['enable_alert_log']) {
192 $new_targets = compare_log_alerts($patient_id, $current_targets, 'clinical_reminder_widget', $_SESSION['authId']);
193 if (!empty($new_targets) && $GLOBALS['enable_cdr_new_crp']) {
194 // If there are new action(s), then throw a popup (if the enable_cdr_new_crp global is turned on)
195 // Note I am taking advantage of a slight hack in order to run javascript within code that
196 // is being passed via an ajax call by using a dummy image.
197 echo '<img src="../../pic/empty.gif" onload="alert(\''.xls('New Due Clinical Reminders').'\n\n';
198 foreach ($new_targets as $key => $value) {
199 $category_item = explode(":", $key);
200 $category = $category_item[0];
201 $item = $category_item[1];
202 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'), $category) .
203 ': ' . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'), $item). '\n';
206 echo '\n' . '('. xls('See the Clinical Reminders widget for more details'). ')';
207 echo '\');this.parentNode.removeChild(this);" />';
213 * Display the active screen reminder.
215 * @param integer $patient_id pid of selected patient
216 * @param string $mode choose either 'reminders-all' or 'reminders-due' (required)
217 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
218 * @param string $organize_mode Way to organize the results (default or plans)
219 * @param string $user If a user is set, then will only show rules that user has permission to see
220 * @param string $test Set to true when only checking if there are alerts (skips the logging then)
221 * @return string html display output.
223 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) {
241 // Deal with plan names first
242 if ($action['is_plan']) {
243 $returnOutput .= "<br><b>";
244 $returnOutput .= htmlspecialchars(xl("Plan"), ENT_NOQUOTES) . ": ";
245 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'clinical_plans'), $action['id']);
246 $returnOutput .= "</b><br>";
247 continue;
250 // Display Reminder Details
251 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'), $action['category']) .
252 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'), $action['item']);
254 // Display due status
255 if ($action['due_status']) {
256 // Color code the status (red for past due, purple for due, green for not due and black for soon due)
257 if ($action['due_status'] == "past_due") {
258 $returnOutput .= "&nbsp;&nbsp;(<span style='color:red'>";
259 } else if ($action['due_status'] == "due") {
260 $returnOutput .= "&nbsp;&nbsp;(<span style='color:purple'>";
261 } else if ($action['due_status'] == "not_due") {
262 $returnOutput .= "&nbsp;&nbsp;(<span style='color:green'>";
263 } else {
264 $returnOutput .= "&nbsp;&nbsp;(<span>";
267 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'), $action['due_status']) . "</span>)<br>";
268 } else {
269 $returnOutput .= "<br>";
272 // Add the target(and rule id and room for future elements as needed) to the $current_targets array.
273 // Only when $mode is reminders-due and $test is FALSE
274 if (($mode == "reminders-due") && ($test === false) && ($GLOBALS['enable_alert_log'])) {
275 $target_temp = $action['category'].":".$action['item'];
276 $current_targets[$target_temp] = array('rule_id'=>$action['rule_id'],'due_status'=>$action['due_status']);
280 // Compare the current with most recent action log (this function will also log the current actions)
281 // Only when $mode is reminders-due and $test is FALSE
282 if (($mode == "reminders-due") && ($test === false) && ($GLOBALS['enable_alert_log'])) {
283 $new_targets = compare_log_alerts($patient_id, $current_targets, 'active_reminder_popup', $_SESSION['authId']);
284 if (!empty($new_targets)) {
285 $returnOutput .="<br>" . xlt('New Items (see above for details)') . ":<br>";
286 foreach ($new_targets as $key => $value) {
287 $category_item = explode(":", $key);
288 $category = $category_item[0];
289 $item = $category_item[1];
290 $returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'), $category) .
291 ': ' . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'), $item). '<br>';
296 return $returnOutput;
300 * Process and return allergy conflicts (when a active medication or presciption is on allergy list).
302 * @param integer $patient_id pid of selected patient
303 * @param string $mode either 'all' or 'new' (required)
304 * @param string $user If a user is set, then will only show rules that user has permission to see
305 * @param string $test Set to true when only checking if there are alerts (skips the logging then)
306 * @return array/boolean Array of allergy alerts or FALSE is empty.
308 function allergy_conflict($patient_id, $mode, $user, $test = false)
311 // Collect allergies
312 $res_allergies = sqlStatement("SELECT `title` FROM `lists` WHERE `type`='allergy' " .
313 "AND `activity`=1 " .
314 "AND ( `enddate` IS NULL OR `enddate`='' OR `enddate` > NOW() ) " .
315 "AND `pid`=?", array($patient_id));
316 $allergies = array();
317 for ($iter=0; $row=sqlFetchArray($res_allergies); $iter++) {
318 $allergies[$iter]=$row['title'];
321 // Build sql element of IN for below queries
322 $sqlParam = array();
323 $sqlIN = '';
324 $firstFlag = true;
325 foreach ($allergies as $allergy) {
326 array_push($sqlParam, $allergy);
327 if ($firstFlag) {
328 $sqlIN .= "?";
329 $firstFlag = false;
330 } else {
331 $sqlIN .= ",?";
335 // Check if allergies conflict with medications or prescriptions
336 $conflicts_unique = array();
337 if (!empty($sqlParam)) {
338 $conflicts = array();
339 array_push($sqlParam, $patient_id);
340 $res_meds = sqlStatement("SELECT `title` FROM `lists` WHERE `type`='medication' " .
341 "AND `activity`=1 " .
342 "AND ( `enddate` IS NULL OR `enddate`='' OR `enddate` > NOW() ) " .
343 "AND `title` IN (" . $sqlIN . ") AND `pid`=?", $sqlParam);
344 while ($urow = sqlFetchArray($res_meds)) {
345 array_push($conflicts, $urow['title']);
348 $res_rx = sqlStatement("SELECT `drug` FROM `prescriptions` WHERE `active`=1 " .
349 "AND `drug` IN (" . $sqlIN . ") AND `patient_id`=?", $sqlParam);
350 while ($urow = sqlFetchArray($res_rx)) {
351 array_push($conflicts, $urow['drug']);
354 if (!empty($conflicts)) {
355 $conflicts_unique = array_unique($conflicts);
359 // If there are conflicts, $test is FALSE, and alert logging is on, then run through compare_log_alerts
360 $new_conflicts = array();
361 if ((!empty($conflicts_unique)) && $GLOBALS['enable_alert_log'] && ($test===false)) {
362 $new_conflicts = compare_log_alerts($patient_id, $conflicts_unique, 'allergy_alert', $_SESSION['authId'], $mode);
365 if ($mode == 'all') {
366 if (!empty($conflicts_unique)) {
367 return $conflicts_unique;
368 } else {
369 return false;
371 } else { // $mode = 'new'
372 if (!empty($new_conflicts)) {
373 return $new_conflicts;
374 } else {
375 return false;
381 * Compare current alerts with prior (in order to find new actions)
382 * Also functions to log the actions.
384 * @param integer $patient_id pid of selected patient
385 * @param array $current_targets array of targets
386 * @param string $category clinical_reminder_widget, active_reminder_popup, or allergy_alert
387 * @param integer $userid user id of user.
388 * @param string $log_trigger if 'all', then always log. If 'new', then only trigger log when a new item noted.
389 * @return array array with targets with associated rule.
391 function compare_log_alerts($patient_id, $current_targets, $category = 'clinical_reminder_widget', $userid = '', $log_trigger = 'all')
394 if (empty($userid)) {
395 $userid = $_SESSION['authId'];
398 if (empty($current_targets)) {
399 $current_targets = array();
402 // Collect most recent action_log
403 $prior_targets_sql = sqlQuery("SELECT `value` FROM `clinical_rules_log` " .
404 "WHERE `category` = ? AND `pid` = ? AND `uid` = ? " .
405 "ORDER BY `id` DESC LIMIT 1", array($category,$patient_id,$userid));
406 $prior_targets = array();
407 if (!empty($prior_targets_sql['value'])) {
408 $prior_targets = json_decode($prior_targets_sql['value'], true);
411 // Compare the current with most recent log
412 if (($category == 'clinical_reminder_widget') || ($category == 'active_reminder_popup')) {
413 //using fancy structure to store multiple elements
414 $new_targets = array_diff_key($current_targets, $prior_targets);
415 } else { // $category == 'allergy_alert'
416 //using simple array
417 $new_targets = array_diff($current_targets, $prior_targets);
420 // Store current action_log and the new items
421 // If $log_trigger=='all'
422 // or If $log_trigger=='new' and there are new items
423 if (($log_trigger=='all') || (($log_trigger=='new') && (!empty($new_targets)))) {
424 $current_targets_json = json_encode($current_targets);
425 $new_targets_json = '';
426 if (!empty($new_targets)) {
427 $new_targets_json = json_encode($new_targets);
430 sqlInsert("INSERT INTO `clinical_rules_log` " .
431 "(`date`,`pid`,`uid`,`category`,`value`,`new_value`) " .
432 "VALUES (NOW(),?,?,?,?,?)", array($patient_id,$userid,$category,$current_targets_json,$new_targets_json));
435 // Return new actions (if there are any)
436 return $new_targets;
440 * Process clinic rules via a batching method to improve performance and decrease memory overhead.
442 * Test the clinic rules of entire clinic and create a report or patient reminders (can also test
443 * on one patient or patients of one provider). The structure of the returned results is dependent on the
444 * $organize_mode and $mode parameters.
445 * <pre>The results are dependent on the $organize_mode parameter settings
446 * 'default' organize_mode:
447 * Returns a two-dimensional array of results organized by rules (dependent on the following $mode settings):
448 * 'reminders-due' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
449 * 'reminders-all' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
450 * 'report' mode - returns an array of rows for the Clinical Quality Measures (CQM) report
451 * 'plans' organize_mode:
452 * Returns similar to default, but organizes by the active plans
453 * </pre>
455 * @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).
456 * @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.
457 * @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').
458 * @param string $mode choose either 'report' or 'reminders-all' or 'reminders-due' (required)
459 * @param string $plan test for specific plan only
460 * @param string $organize_mode Way to organize the results (default, plans). See above for organization structure of the results.
461 * @param array $options can hold various option (for now, used to hold the manual number of labs for the AMC report)
462 * @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.
463 * @param integer $batchSize number of patients to batch (default is 100; plan to optimize this default setting in the future)
464 * @param integer $report_id id of report in database (if already bookmarked)
465 * @return array See above for organization structure of the results.
467 function test_rules_clinic_batch_method($provider = '', $type = '', $dateTarget = '', $mode = '', $plan = '', $organize_mode = 'default', $options = array(), $pat_prov_rel = 'primary', $batchSize = '', $report_id = null)
470 // Default to a batchsize, if empty
471 if (empty($batchSize)) {
472 $batchSize=100;
475 // Collect total number of pertinent patients (to calculate batching parameters)
476 $totalNumPatients = buildPatientArray('', $provider, $pat_prov_rel, null, null, true);
478 // Cycle through the batches and collect/combine results
479 if (($totalNumPatients%$batchSize) > 0) {
480 // not perfectly divisible
481 $totalNumberBatches = floor($totalNumPatients/$batchSize) + 1;
482 } else {
483 // perfectly divisible
484 $totalNumberBatches = floor($totalNumPatients/$batchSize);
487 // Fix things in the $options array(). This now stores the number of labs to be used in the denominator in the AMC report.
488 // 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
489 // of planned batches(note the fixed array will go into the test_rules_clinic function, however the original will be used
490 // in the report storing/tracking engine.
491 $options_modified=$options;
492 if (!empty($options_modified['labs_manual'])) {
493 $options_modified['labs_manual'] = $options_modified['labs_manual'] / $totalNumberBatches;
496 // Prepare the database to track/store results
497 $fields = array('provider'=>$provider,'mode'=>$mode,'plan'=>$plan,'organize_mode'=>$organize_mode,'pat_prov_rel'=>$pat_prov_rel);
498 if (is_array($dateTarget)) {
499 $fields = array_merge($fields, array(date_target=>$dateTarget['dateTarget']));
500 $fields = array_merge($fields, array(date_begin=>$dateTarget['dateBegin']));
501 } else {
502 if (empty($dateTarget)) {
503 $fields = array_merge($fields, array(date_target=>date("Y-m-d H:i:s")));
504 } else {
505 $fields = array_merge($fields, array(date_target=>$dateTarget));
509 if (!empty($options)) {
510 foreach ($options as $key => $value) {
511 $fields = array_merge($fields, array($key=>$value));
515 $report_id = beginReportDatabase($type, $fields, $report_id);
516 setTotalItemsReportDatabase($report_id, $totalNumPatients);
518 // Set ability to itemize report if this feature is turned on
519 if (( ($type == "active_alert" || $type == "passive_alert") && ($GLOBALS['report_itemizing_standard']) ) ||
520 ( ($type == "cqm" || $type == "cqm_2011" || $type == "cqm_2014") && ($GLOBALS['report_itemizing_cqm']) ) ||
521 ( ($type == "amc" || $type == "amc_2011" || $type == "amc_2014" || $type == "amc_2014_stage1" || $type == "amc_2014_stage2") && ($GLOBALS['report_itemizing_amc']) ) ) {
522 $GLOBALS['report_itemizing_temp_flag_and_id'] = $report_id;
523 } else {
524 $GLOBALS['report_itemizing_temp_flag_and_id'] = 0;
527 for ($i=0; $i<$totalNumberBatches; $i++) {
528 // If itemization is turned on, then reset the rule id iterator
529 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
530 $GLOBALS['report_itemized_test_id_iterator'] = 1;
533 $dataSheet_batch = test_rules_clinic($provider, $type, $dateTarget, $mode, '', $plan, $organize_mode, $options_modified, $pat_prov_rel, (($batchSize*$i)+1), $batchSize);
534 if ($i == 0) {
535 // For first cycle, simply copy it to dataSheet
536 $dataSheet = $dataSheet_batch;
537 } else {
538 //debug
539 //error_log("CDR: ".print_r($dataSheet,TRUE),0);
540 //error_log("CDR: ".($batchSize*$i)." records",0);
542 // Integrate batch results into main dataSheet
543 foreach ($dataSheet_batch as $key => $row) {
544 if (!$row['is_sub']) {
545 //skip this stuff for the sub entries (and use previous main entry in percentage calculation)
546 $total_patients = $dataSheet[$key]['total_patients'] + $row['total_patients'];
547 $dataSheet[$key]['total_patients'] = $total_patients;
548 $excluded = $dataSheet[$key]['excluded'] + $row['excluded'];
549 $dataSheet[$key]['excluded'] = $excluded;
550 $pass_filter = $dataSheet[$key]['pass_filter'] + $row['pass_filter'];
551 $dataSheet[$key]['pass_filter'] = $pass_filter;
554 $pass_target = $dataSheet[$key]['pass_target'] + $row['pass_target'];
555 $dataSheet[$key]['pass_target'] = $pass_target;
556 $dataSheet[$key]['percentage'] = calculate_percentage($pass_filter, $excluded, $pass_target);
560 //Update database to track results
561 updateReportDatabase($report_id, $total_patients);
564 // Record results in database and send to screen, if applicable.
565 finishReportDatabase($report_id, json_encode($dataSheet));
566 return $dataSheet;
570 * Process clinic rules.
572 * Test the clinic rules of entire clinic and create a report or patient reminders (can also test
573 * on one patient or patients of one provider). The structure of the returned results is dependent on the
574 * $organize_mode and $mode parameters.
575 * <pre>The results are dependent on the $organize_mode parameter settings
576 * 'default' organize_mode:
577 * Returns a two-dimensional array of results organized by rules (dependent on the following $mode settings):
578 * 'reminders-due' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
579 * 'reminders-all' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
580 * 'report' mode - returns an array of rows for the Clinical Quality Measures (CQM) report
581 * 'plans' organize_mode:
582 * Returns similar to default, but organizes by the active plans
583 * </pre>
585 * @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).
586 * @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.
587 * @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').
588 * @param string $mode choose either 'report' or 'reminders-all' or 'reminders-due' (required)
589 * @param integer $patient_id pid of patient. If blank then will check all patients.
590 * @param string $plan test for specific plan only
591 * @param string $organize_mode Way to organize the results (default, plans). See above for organization structure of the results.
592 * @param array $options can hold various option (for now, used to hold the manual number of labs for the AMC report)
593 * @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.
594 * @param integer $start applicable patient to start at (when batching process)
595 * @param integer $batchSize number of patients to batch (when batching process)
596 * @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).
597 * @return array See above for organization structure of the results.
599 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 = '')
602 // If dateTarget is an array, then organize them.
603 if (is_array($dateTarget)) {
604 $dateArray = $dateTarget;
605 $dateTarget = $dateTarget['dateTarget'];
608 // Set date to current if not set
609 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
611 // Prepare the results array
612 $results = array();
614 // If set the $provider to collate_outer (or collate_inner without plans organize mode),
615 // then run through this function recursively and return results.
616 if (($provider == "collate_outer") || ($provider == "collate_inner" && $organize_mode != 'plans')) {
617 // First, collect an array of all providers
618 $query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
619 $ures = sqlStatementCdrEngine($query);
620 // Second, run through each provider recursively
621 while ($urow = sqlFetchArray($ures)) {
622 $newResults = test_rules_clinic($urow['id'], $type, $dateTarget, $mode, $patient_id, $plan, $organize_mode, $options, $pat_prov_rel, $start, $batchSize, $user);
623 if (!empty($newResults)) {
624 $provider_item['is_provider'] = true;
625 $provider_item['prov_lname'] = $urow['lname'];
626 $provider_item['prov_fname'] = $urow['fname'];
627 $provider_item['npi'] = $urow['npi'];
628 $provider_item['federaltaxid'] = $urow['federaltaxid'];
629 array_push($results, $provider_item);
630 $results = array_merge($results, $newResults);
634 // done, so now can return results
635 return $results;
638 // If set organize-mode to plans, then collects active plans and run through this
639 // function recursively and return results.
640 if ($organize_mode == "plans") {
641 // First, collect active plans
642 $plans_resolve = resolve_plans_sql($plan, $patient_id);
643 // Second, run through function recursively
644 foreach ($plans_resolve as $plan_item) {
645 // (if collate_inner, then nest a collation of providers within each plan)
646 if ($provider == "collate_inner") {
647 // First, collect an array of all providers
648 $query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
649 $ures = sqlStatementCdrEngine($query);
650 // Second, run through each provider recursively
651 $provider_results = array();
652 while ($urow = sqlFetchArray($ures)) {
653 $newResults = test_rules_clinic($urow['id'], $type, $dateTarget, $mode, $patient_id, $plan_item['id'], 'default', $options, $pat_prov_rel, $start, $batchSize, $user);
654 if (!empty($newResults)) {
655 $provider_item['is_provider'] = true;
656 $provider_item['prov_lname'] = $urow['lname'];
657 $provider_item['prov_fname'] = $urow['fname'];
658 $provider_item['npi'] = $urow['npi'];
659 $provider_item['federaltaxid'] = $urow['federaltaxid'];
660 array_push($provider_results, $provider_item);
661 $provider_results = array_merge($provider_results, $newResults);
665 if (!empty($provider_results)) {
666 $plan_item['is_plan'] = true;
667 array_push($results, $plan_item);
668 $results = array_merge($results, $provider_results);
670 } else {
671 // (not collate_inner, so do not nest providers within each plan)
672 $newResults = test_rules_clinic($provider, $type, $dateTarget, $mode, $patient_id, $plan_item['id'], 'default', $options, $pat_prov_rel, $start, $batchSize, $user);
673 if (!empty($newResults)) {
674 $plan_item['is_plan'] = true;
675 array_push($results, $plan_item);
676 $results = array_merge($results, $newResults);
681 // done, so now can return results
682 return $results;
685 // Collect applicable patient pids
686 $patientData = array();
687 $patientData = buildPatientArray($patient_id, $provider, $pat_prov_rel, $start, $batchSize);
689 // Go through each patient(s)
691 // If in report mode, then tabulate for each rule:
692 // Total Patients
693 // Patients that pass the filter
694 // Patients that pass the target
695 // If in reminders mode, then create reminders for each rule:
696 // Reminder that action is due soon
697 // Reminder that action is due
698 // Reminder that action is post-due
700 //Collect applicable rules
701 // Note that due to a limitation in the this function, the patient_id is explicitly
702 // for grouping items when not being done in real-time or for official reporting.
703 // So for cases such as patient reminders on a clinic scale, the calling function
704 // will actually need rather than pass in a explicit patient_id for each patient in
705 // a separate call to this function.
706 if ($mode != "report") {
707 // Use per patient custom rules (if exist)
708 // Note as discussed above, this only works for single patient instances.
709 $rules = resolve_rules_sql($type, $patient_id, false, $plan, $user);
710 } else { // $mode = "report"
711 // Only use default rules (do not use patient custom rules)
712 $rules = resolve_rules_sql($type, $patient_id, false, $plan, $user);
715 foreach ($rules as $rowRule) {
716 // If using cqm or amc type, then use the hard-coded rules set.
717 // Note these rules are only used in report mode.
718 if ($rowRule['cqm_flag'] || $rowRule['amc_flag']) {
719 require_once(dirname(__FILE__)."/classes/rulesets/ReportManager.php");
720 $manager = new ReportManager();
721 if ($rowRule['amc_flag']) {
722 // Send array of dates ('dateBegin' and 'dateTarget')
723 $tempResults = $manager->runReport($rowRule, $patientData, $dateArray, $options);
724 } else {
725 // Send target date
726 $tempResults = $manager->runReport($rowRule, $patientData, $dateTarget);
729 if (!empty($tempResults)) {
730 foreach ($tempResults as $tempResult) {
731 array_push($results, $tempResult);
735 // Go on to the next rule
736 continue;
739 // If in reminder mode then need to collect the measurement dates
740 // from rule_reminder table
741 $target_dates = array();
742 if ($mode != "report") {
743 // Calculate the dates to check for
744 if ($type == "patient_reminder") {
745 $reminder_interval_type = "patient_reminder";
746 } else { // $type == "passive_alert" or $type == "active_alert"
747 $reminder_interval_type = "clinical_reminder";
750 $target_dates = calculate_reminder_dates($rowRule['id'], $dateTarget, $reminder_interval_type);
751 } else { // $mode == "report"
752 // Only use the target date in the report
753 $target_dates[0] = $dateTarget;
756 //Reset the counters
757 $total_patients = 0;
758 $pass_filter = 0;
759 $exclude_filter = 0;
760 $pass_target = 0;
762 // Find the number of target groups
763 $targetGroups = returnTargetGroups($rowRule['id']);
765 if ((count($targetGroups) == 1) || ($mode == "report")) {
766 // If report itemization is turned on, then iterate the rule id iterator
767 if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {
768 $GLOBALS['report_itemized_test_id_iterator']++;
771 //skip this section if not report and more than one target group
772 foreach ($patientData as $rowPatient) {
773 // First, deal with deceased patients
774 // (for now will simply skip the patient)
775 // If want to support rules for deceased patients then will need to migrate this below
776 // in target_dates foreach(guessing won't ever need to do this, though).
777 // Note using the dateTarget rather than dateFocus
778 if (is_patient_deceased($rowPatient['pid'], $dateTarget)) {
779 continue;
782 // Count the total patients
783 $total_patients++;
785 $dateCounter = 1; // for reminder mode to keep track of which date checking
786 // If report itemization is turned on, reset flag.
787 if (!empty($GLOBALS['report_itemizing_temp_flag_and_id'])) {
788 $temp_track_pass = 1;
791 foreach ($target_dates as $dateFocus) {
792 //Skip if date is set to SKIP
793 if ($dateFocus == "SKIP") {
794 $dateCounter++;
795 continue;
798 //Set date counter and reminder token (applicable for reminders only)
799 if ($dateCounter == 1) {
800 $reminder_due = "soon_due";
801 } else if ($dateCounter == 2) {
802 $reminder_due = "due";
803 } else { // $dateCounter == 3
804 $reminder_due = "past_due";
807 // Check if pass filter
808 $passFilter = test_filter($rowPatient['pid'], $rowRule['id'], $dateFocus);
809 if ($passFilter === "EXCLUDED") {
810 // increment EXCLUDED and pass_filter counters
811 // and set as FALSE for reminder functionality.
812 $pass_filter++;
813 $exclude_filter++;
814 $passFilter = false;
817 if ($passFilter) {
818 // increment pass filter counter
819 $pass_filter++;
820 // If report itemization is turned on, trigger flag.
821 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
822 $temp_track_pass = 0;
824 } else {
825 $dateCounter++;
826 continue;
829 // Check if pass target
830 $passTarget = test_targets($rowPatient['pid'], $rowRule['id'], '', $dateFocus);
831 if ($passTarget) {
832 // increment pass target counter
833 $pass_target++;
834 // If report itemization is turned on, then record the "passed" item and set the flag
835 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
836 insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 1, $rowPatient['pid']);
837 $temp_track_pass = 1;
840 // send to reminder results
841 if ($mode == "reminders-all") {
842 // place the completed actions into the reminder return array
843 $actionArray = resolve_action_sql($rowRule['id'], '1');
844 foreach ($actionArray as $action) {
845 $action_plus = $action;
846 $action_plus['due_status'] = "not_due";
847 $action_plus['pid'] = $rowPatient['pid'];
848 $action_plus['rule_id'] = $rowRule['id'];
849 $results = reminder_results_integrate($results, $action_plus);
853 break;
854 } else {
855 // send to reminder results
856 if ($mode != "report") {
857 // place the uncompleted actions into the reminder return array
858 $actionArray = resolve_action_sql($rowRule['id'], '1');
859 foreach ($actionArray as $action) {
860 $action_plus = $action;
861 $action_plus['due_status'] = $reminder_due;
862 $action_plus['pid'] = $rowPatient['pid'];
863 $action_plus['rule_id'] = $rowRule['id'];
864 $results = reminder_results_integrate($results, $action_plus);
869 $dateCounter++;
872 // If report itemization is turned on, then record the "failed" item if it did not pass
873 if (!empty($GLOBALS['report_itemizing_temp_flag_and_id']) && !($temp_track_pass)) {
874 insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 0, $rowPatient['pid']);
879 // Calculate and save the data for the rule
880 $percentage = calculate_percentage($pass_filter, $exclude_filter, $pass_target);
881 if ($mode == "report") {
882 $newRow=array('is_main'=>true,'total_patients'=>$total_patients,'excluded'=>$exclude_filter,'pass_filter'=>$pass_filter,'pass_target'=>$pass_target,'percentage'=>$percentage);
883 $newRow=array_merge($newRow, $rowRule);
885 // If itemization is turned on, then record the itemized_test_id
886 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
887 $newRow=array_merge($newRow, array('itemized_test_id'=>$GLOBALS['report_itemized_test_id_iterator']));
890 array_push($results, $newRow);
893 // Now run through the target groups if more than one
894 if (count($targetGroups) > 1) {
895 foreach ($targetGroups as $i) {
896 // If report itemization is turned on, then iterate the rule id iterator
897 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
898 $GLOBALS['report_itemized_test_id_iterator']++;
901 //Reset the target counter
902 $pass_target = 0;
904 foreach ($patientData as $rowPatient) {
905 // First, deal with deceased patients
906 // (for now will simply skip the patient)
907 // If want to support rules for deceased patients then will need to migrate this below
908 // in target_dates foreach(guessing won't ever need to do this, though).
909 // Note using the dateTarget rather than dateFocus
910 if (is_patient_deceased($rowPatient['pid'], $dateTarget)) {
911 continue;
914 $dateCounter = 1; // for reminder mode to keep track of which date checking
915 // If report itemization is turned on, reset flag.
916 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
917 $temp_track_pass = 1;
920 foreach ($target_dates as $dateFocus) {
921 //Skip if date is set to SKIP
922 if ($dateFocus == "SKIP") {
923 $dateCounter++;
924 continue;
927 //Set date counter and reminder token (applicable for reminders only)
928 if ($dateCounter == 1) {
929 $reminder_due = "soon_due";
930 } else if ($dateCounter == 2) {
931 $reminder_due = "due";
932 } else { // $dateCounter == 3
933 $reminder_due = "past_due";
936 // Check if pass filter
937 $passFilter = test_filter($rowPatient['pid'], $rowRule['id'], $dateFocus);
938 if ($passFilter === "EXCLUDED") {
939 $passFilter = false;
942 if (!$passFilter) {
943 $dateCounter++;
944 continue;
945 } else {
946 // If report itemization is turned on, trigger flag.
947 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
948 $temp_track_pass = 0;
952 //Check if pass target
953 $passTarget = test_targets($rowPatient['pid'], $rowRule['id'], $i, $dateFocus);
954 if ($passTarget) {
955 // increment pass target counter
956 $pass_target++;
957 // If report itemization is turned on, then record the "passed" item and set the flag
958 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
959 insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 1, $rowPatient['pid']);
960 $temp_track_pass = 1;
963 // send to reminder results
964 if ($mode == "reminders-all") {
965 // place the completed actions into the reminder return array
966 $actionArray = resolve_action_sql($rowRule['id'], $i);
967 foreach ($actionArray as $action) {
968 $action_plus = $action;
969 $action_plus['due_status'] = "not_due";
970 $action_plus['pid'] = $rowPatient['pid'];
971 $action_plus['rule_id'] = $rowRule['id'];
972 $results = reminder_results_integrate($results, $action_plus);
976 break;
977 } else {
978 // send to reminder results
979 if ($mode != "report") {
980 // place the actions into the reminder return array
981 $actionArray = resolve_action_sql($rowRule['id'], $i);
982 foreach ($actionArray as $action) {
983 $action_plus = $action;
984 $action_plus['due_status'] = $reminder_due;
985 $action_plus['pid'] = $rowPatient['pid'];
986 $action_plus['rule_id'] = $rowRule['id'];
987 $results = reminder_results_integrate($results, $action_plus);
992 $dateCounter++;
995 // If report itemization is turned on, then record the "failed" item if it did not pass
996 if ($GLOBALS['report_itemizing_temp_flag_and_id'] && !($temp_track_pass)) {
997 insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 0, $rowPatient['pid']);
1001 // Calculate and save the data for the rule
1002 $percentage = calculate_percentage($pass_filter, $exclude_filter, $pass_target);
1004 // Collect action for title (just use the first one, if more than one)
1005 $actionArray = resolve_action_sql($rowRule['id'], $i);
1006 $action = $actionArray[0];
1007 if ($mode == "report") {
1008 $newRow=array('is_sub'=>true,'action_category'=>$action['category'],'action_item'=>$action['item'],'total_patients'=>'','excluded'=>'','pass_filter'=>'','pass_target'=>$pass_target,'percentage'=>$percentage);
1010 // If itemization is turned on, then record the itemized_test_id
1011 if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
1012 $newRow=array_merge($newRow, array('itemized_test_id'=>$GLOBALS['report_itemized_test_id_iterator']));
1015 array_push($results, $newRow);
1021 // Return the data
1022 return $results;
1026 * Process patient array that is to be tested.
1028 * @param integer $provider id of a selected provider. If blank, then will test entire clinic.
1029 * @param integer $patient_id pid of patient. If blank then will check all patients.
1030 * @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.
1031 * @param integer $start applicable patient to start at (when batching process)
1032 * @param integer $batchSize number of patients to batch (when batching process)
1033 * @param boolean $onlyCount If true, then will just return the total number of applicable records (ignores batching parameters)
1034 * @return array/integer Array of patient pid values or number total pertinent patients (if $onlyCount is TRUE)
1036 function buildPatientArray($patient_id = '', $provider = '', $pat_prov_rel = 'primary', $start = null, $batchSize = null, $onlyCount = false)
1039 if (!empty($patient_id)) {
1040 // only look at the selected patient
1041 if ($onlyCount) {
1042 $patientNumber = 1;
1043 } else {
1044 $patientData[0]['pid'] = $patient_id;
1046 } else {
1047 if (empty($provider)) {
1048 // Look at entire practice
1049 if ($start == null || $batchSize == null || $onlyCount) {
1050 $rez = sqlStatementCdrEngine("SELECT `pid` FROM `patient_data` ORDER BY `pid`");
1051 if ($onlyCount) {
1052 $patientNumber = sqlNumRows($rez);
1054 } else {
1055 // batching
1056 $rez = sqlStatementCdrEngine("SELECT `pid` FROM `patient_data` ORDER BY `pid` LIMIT ?,?", array(($start-1),$batchSize));
1058 } else {
1059 // Look at an individual physician
1060 if ($pat_prov_rel == 'encounter') {
1061 // Choose patients that are related to specific physician by an encounter
1062 if ($start == null || $batchSize == null || $onlyCount) {
1063 $rez = sqlStatementCdrEngine("SELECT DISTINCT `pid` FROM `form_encounter` ".
1064 " WHERE `provider_id`=? OR `supervisor_id`=? ORDER BY `pid`", array($provider,$provider));
1065 if ($onlyCount) {
1066 $patientNumber = sqlNumRows($rez);
1068 } else {
1069 //batching
1070 $rez = sqlStatementCdrEngine("SELECT DISTINCT `pid` FROM `form_encounter` ".
1071 " WHERE `provider_id`=? OR `supervisor_id`=? ORDER BY `pid` LIMIT ?,?", array($provider,$provider,($start-1),$batchSize));
1073 } else { //$pat_prov_rel == 'primary'
1074 // Choose patients that are assigned to the specific physician (primary physician in patient demographics)
1075 if ($start == null || $batchSize == null || $onlyCount) {
1076 $rez = sqlStatementCdrEngine("SELECT `pid` FROM `patient_data` " .
1077 "WHERE `providerID`=? ORDER BY `pid`", array($provider));
1078 if ($onlyCount) {
1079 $patientNumber = sqlNumRows($rez);
1081 } else {
1082 $rez = sqlStatementCdrEngine("SELECT `pid` FROM `patient_data` " .
1083 "WHERE `providerID`=? ORDER BY `pid` LIMIT ?,?", array($provider,($start-1),$batchSize));
1088 // convert the sql query results into an array if returning the array
1089 if (!$onlyCount) {
1090 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
1091 $patientData[$iter]=$row;
1096 if ($onlyCount) {
1097 // return the number of applicable patients
1098 return $patientNumber;
1099 } else {
1100 // return array of patient pids
1101 return $patientData;
1106 * Test filter of a selected rule on a selected patient
1108 * @param integer $patient_id pid of selected patient.
1109 * @param string $rule id(string) of selected rule
1110 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
1111 * @return boolean/string if pass filter then TRUE; if excluded then 'EXCLUDED'; if not pass filter then FALSE
1113 function test_filter($patient_id, $rule, $dateTarget)
1116 // Set date to current if not set
1117 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1119 // Collect patient information
1120 $patientData = getPatientData($patient_id, "sex, DATE_FORMAT(DOB,'%Y %m %d') as DOB_TS");
1123 // ----------------- INCLUSIONS -----------------
1126 // -------- Age Filter (inclusion) ------------
1127 // Calculate patient age in years and months
1128 $patientAgeYears = convertDobtoAgeYearDecimal($patientData['DOB_TS'], $dateTarget);
1129 $patientAgeMonths = convertDobtoAgeMonthDecimal($patientData['DOB_TS'], $dateTarget);
1131 // Min age (year) Filter (assume that there in not more than one of each)
1132 $filter = resolve_filter_sql($rule, 'filt_age_min');
1133 if (!empty($filter)) {
1134 $row = $filter[0];
1135 if ($row ['method_detail'] == "year") {
1136 if ($row['value'] && ($row['value'] > $patientAgeYears)) {
1137 return false;
1141 if ($row ['method_detail'] == "month") {
1142 if ($row['value'] && ($row['value'] > $patientAgeMonths)) {
1143 return false;
1148 // Max age (year) Filter (assume that there in not more than one of each)
1149 $filter = resolve_filter_sql($rule, 'filt_age_max');
1150 if (!empty($filter)) {
1151 $row = $filter[0];
1152 if ($row ['method_detail'] == "year") {
1153 if ($row['value'] && ($row['value'] < $patientAgeYears)) {
1154 return false;
1158 if ($row ['method_detail'] == "month") {
1159 if ($row['value'] && ($row['value'] < $patientAgeMonths)) {
1160 return false;
1165 // -------- Gender Filter (inclusion) ---------
1166 // Gender Filter (assume that there in not more than one of each)
1167 $filter = resolve_filter_sql($rule, 'filt_sex');
1168 if (!empty($filter)) {
1169 $row = $filter[0];
1170 if ($row['value'] && ($row['value'] != $patientData['sex'])) {
1171 return false;
1175 // -------- Database Filter (inclusion) ------
1176 // Database Filter
1177 $filter = resolve_filter_sql($rule, 'filt_database');
1178 if ((!empty($filter)) && !database_check($patient_id, $filter, '', $dateTarget)) {
1179 return false;
1182 // -------- Lists Filter (inclusion) ----
1183 // Set up lists filter, which is fully customizable and currently includes diagnoses, meds,
1184 // surgeries and allergies.
1185 $filter = resolve_filter_sql($rule, 'filt_lists');
1186 if ((!empty($filter)) && !lists_check($patient_id, $filter, $dateTarget)) {
1187 return false;
1190 // -------- Procedure (labs,imaging,test,procedures,etc) Filter (inlcusion) ----
1191 // Procedure Target (includes) (may need to include an interval in the future)
1192 $filter = resolve_filter_sql($rule, 'filt_proc');
1193 if ((!empty($filter)) && !procedure_check($patient_id, $filter, '', $dateTarget)) {
1194 return false;
1198 // ----------------- EXCLUSIONS -----------------
1201 // -------- Lists Filter (EXCLUSION) ----
1202 // Set up lists EXCLUSION filter, which is fully customizable and currently includes diagnoses, meds,
1203 // surgeries and allergies.
1204 $filter = resolve_filter_sql($rule, 'filt_lists', 0);
1205 if ((!empty($filter)) && lists_check($patient_id, $filter, $dateTarget)) {
1206 return "EXCLUDED";
1209 // Passed all filters, so return true.
1210 return true;
1214 * Return an array containing existing group ids for a rule
1216 * @param string $rule id(string) of rule
1217 * @return array listing of group ids
1219 function returnTargetGroups($rule)
1222 $sql = sqlStatementCdrEngine("SELECT DISTINCT `group_id` FROM `rule_target` " .
1223 "WHERE `id`=?", array($rule));
1225 $groups = array();
1226 for ($iter=0; $row=sqlFetchArray($sql); $iter++) {
1227 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)
1245 // -------- Interval Target ----
1246 $interval = resolve_target_sql($rule, $group_id, 'target_interval');
1248 // -------- Database Target ----
1249 // Database Target (includes)
1250 $target = resolve_target_sql($rule, $group_id, 'target_database');
1251 if ((!empty($target)) && !database_check($patient_id, $target, $interval, $dateTarget)) {
1252 return false;
1255 // -------- Procedure (labs,imaging,test,procedures,etc) Target ----
1256 // Procedure Target (includes)
1257 $target = resolve_target_sql($rule, $group_id, 'target_proc');
1258 if ((!empty($target)) && !procedure_check($patient_id, $target, $interval, $dateTarget)) {
1259 return false;
1262 // -------- Appointment Target ----
1263 // Appointment Target (includes) (Specialized functionality for appointment reminders)
1264 $target = resolve_target_sql($rule, $group_id, 'target_appt');
1265 if ((!empty($target)) && appointment_check($patient_id, $dateTarget)) {
1266 return false;
1269 // Passed all target tests, so return true.
1270 return true;
1274 * Function to return active plans
1276 * @param string $type plan type filter (normal or cqm or blank)
1277 * @param integer $patient_id pid of selected patient. (if custom plan does not exist then will use the default plan)
1278 * @param boolean $configurableOnly true if only want the configurable (per patient) plans (ie. ignore cqm plans)
1279 * @return array active plans
1281 function resolve_plans_sql($type = '', $patient_id = '0', $configurableOnly = false)
1284 if ($configurableOnly) {
1285 // Collect all default, configurable (per patient) plans into an array
1286 // (ie. ignore the cqm rules)
1287 $sql = sqlStatementCdrEngine("SELECT * FROM `clinical_plans` WHERE `pid`=0 AND `cqm_flag` !=1 ORDER BY `id`");
1288 } else {
1289 // Collect all default plans into an array
1290 $sql = sqlStatementCdrEngine("SELECT * FROM `clinical_plans` WHERE `pid`=0 ORDER BY `id`");
1293 $returnArray= array();
1294 for ($iter=0; $row=sqlFetchArray($sql); $iter++) {
1295 array_push($returnArray, $row);
1298 // Now collect the pertinent plans
1299 $newReturnArray = array();
1301 // Need to select rules (use custom if exist)
1302 foreach ($returnArray as $plan) {
1303 $customPlan = sqlQueryCdrEngine("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan['id'],$patient_id));
1305 // Decide if use default vs custom plan (preference given to custom plan)
1306 if (!empty($customPlan)) {
1307 if ($type == "cqm") {
1308 // For CQM , do not use custom plans (these are to create standard clinic wide reports)
1309 $goPlan = $plan;
1310 } else {
1311 // merge the custom plan with the default plan
1312 $mergedPlan = array();
1313 foreach ($customPlan as $key => $value) {
1314 if ($value == null && preg_match("/_flag$/", $key)) {
1315 // use default setting
1316 $mergedPlan[$key] = $plan[$key];
1317 } else {
1318 // use custom setting
1319 $mergedPlan[$key] = $value;
1323 $goPlan = $mergedPlan;
1325 } else {
1326 $goPlan = $plan;
1329 // Use the chosen plan if set
1330 if (!empty($type)) {
1331 if ($goPlan["${type}_flag"] == 1) {
1332 // active, so use the plan
1333 array_push($newReturnArray, $goPlan);
1335 } else {
1336 if ($goPlan['normal_flag'] == 1 ||
1337 $goPlan['cqm_flag'] == 1) {
1338 // active, so use the plan
1339 array_push($newReturnArray, $goPlan);
1344 $returnArray = $newReturnArray;
1346 return $returnArray;
1351 * Function to return a specific plan
1353 * @param string $plan id(string) of plan
1354 * @param integer $patient_id pid of selected patient. (if set to 0, then will return the default rule).
1355 * @return array a plan
1357 function collect_plan($plan, $patient_id = '0')
1360 return sqlQueryCdrEngine("SELECT * FROM `clinical_plans` WHERE `id`=? AND `pid`=?", array($plan,$patient_id));
1364 * Function to set a specific plan activity for a specific patient
1366 * @param string $plan id(string) of plan
1367 * @param string $type plan filter (normal,cqm)
1368 * @param string $setting activity of plan (yes,no,default)
1369 * @param integer $patient_id pid of selected patient.
1371 function set_plan_activity_patient($plan, $type, $setting, $patient_id)
1374 // Don't allow messing with the default plans here
1375 if ($patient_id == "0") {
1376 return;
1379 // Convert setting
1380 if ($setting == "on") {
1381 $setting = 1;
1382 } else if ($setting == "off") {
1383 $setting = 0;
1384 } else { // $setting == "default"
1385 $setting = null;
1388 // Collect patient specific plan, if already exists.
1389 $query = "SELECT * FROM `clinical_plans` WHERE `id` = ? AND `pid` = ?";
1390 $patient_plan = sqlQueryCdrEngine($query, array($plan,$patient_id));
1392 if (empty($patient_plan)) {
1393 // Create a new patient specific plan with flags all set to default
1394 $query = "INSERT into `clinical_plans` (`id`, `pid`) VALUES (?,?)";
1395 sqlStatementCdrEngine($query, array($plan, $patient_id));
1398 // Update patient specific row
1399 $query = "UPDATE `clinical_plans` SET `" . escape_sql_column_name($type."_flag", array("clinical_plans")) . "`= ? WHERE id = ? AND pid = ?";
1400 sqlStatementCdrEngine($query, array($setting,$plan,$patient_id));
1404 * Function to return active rules
1406 * @param string $type rule filter (active_alert,passive_alert,cqm,cqm_2011,cqm_2014,amc_2011,amc_2014,patient_reminder)
1407 * @param integer $patient_id pid of selected patient. (if custom rule does not exist then will use the default rule)
1408 * @param boolean $configurableOnly true if only want the configurable (per patient) rules (ie. ignore cqm and amc rules)
1409 * @param string $plan collect rules for specific plan
1410 * @param string $user If a user is set, then will only show rules that user has permission to see
1411 * @return array rules
1413 function resolve_rules_sql($type = '', $patient_id = '0', $configurableOnly = false, $plan = '', $user = '')
1416 if ($configurableOnly) {
1417 // Collect all default, configurable (per patient) rules into an array
1418 // (ie. ignore the cqm and amc rules)
1419 $sql = sqlStatementCdrEngine("SELECT * FROM `clinical_rules` WHERE `pid`=0 AND `cqm_flag` !=1 AND `amc_flag` !=1 ORDER BY `id`");
1420 } else {
1421 // Collect all default rules into an array
1422 $sql = sqlStatementCdrEngine("SELECT * FROM `clinical_rules` WHERE `pid`=0 ORDER BY `id`");
1425 $returnArray= array();
1426 for ($iter=0; $row=sqlFetchArray($sql); $iter++) {
1427 array_push($returnArray, $row);
1430 // Now filter rules for plan (if applicable)
1431 if (!empty($plan)) {
1432 $planReturnArray = array();
1433 foreach ($returnArray as $rule) {
1434 $standardRule = sqlQueryCdrEngine("SELECT * FROM `clinical_plans_rules` " .
1435 "WHERE `plan_id`=? AND `rule_id`=?", array($plan,$rule['id']));
1436 if (!empty($standardRule)) {
1437 array_push($planReturnArray, $rule);
1441 $returnArray = $planReturnArray;
1444 // Now collect the pertinent rules
1445 $newReturnArray = array();
1447 // Need to select rules (use custom if exist)
1448 foreach ($returnArray as $rule) {
1449 // If user is set, then check if user has access to the rule
1450 if (!empty($user)) {
1451 $access_control = explode(':', $rule['access_control']);
1452 if (!empty($access_control[0]) && !empty($access_control[1])) {
1453 // Section and ACO filters are not empty, so do the test for access.
1454 if (!acl_check($access_control[0], $access_control[1], $user)) {
1455 // User does not have access to this rule, so skip the rule.
1456 continue;
1458 } else {
1459 // Section or ACO filters are empty, so use default patients:med aco
1460 if (!acl_check('patients', 'med', $user)) {
1461 // User does not have access to this rule, so skip the rule.
1462 continue;
1467 $customRule = sqlQueryCdrEngine("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule['id'],$patient_id));
1469 // Decide if use default vs custom rule (preference given to custom rule)
1470 if (!empty($customRule)) {
1471 if ($type == "cqm" || $type == "amc") {
1472 // For CQM and AMC, do not use custom rules (these are to create standard clinic wide reports)
1473 $goRule = $rule;
1474 } else {
1475 // merge the custom rule with the default rule
1476 $mergedRule = array();
1477 foreach ($customRule as $key => $value) {
1478 if ($value == null && preg_match("/_flag$/", $key)) {
1479 // use default setting
1480 $mergedRule[$key] = $rule[$key];
1481 } else {
1482 // use custom setting
1483 $mergedRule[$key] = $value;
1487 $goRule = $mergedRule;
1489 } else {
1490 $goRule = $rule;
1493 // Use the chosen rule if set
1494 if (!empty($type)) {
1495 if ($goRule["${type}_flag"] == 1) {
1496 // active, so use the rule
1497 array_push($newReturnArray, $goRule);
1499 } else {
1500 // no filter, so return the rule
1501 array_push($newReturnArray, $goRule);
1505 $returnArray = $newReturnArray;
1507 return $returnArray;
1511 * Function to return a specific rule
1513 * @param string $rule id(string) of rule
1514 * @param integer $patient_id pid of selected patient. (if set to 0, then will return the default rule).
1515 * @return array rule
1517 function collect_rule($rule, $patient_id = '0')
1520 return sqlQueryCdrEngine("SELECT * FROM `clinical_rules` WHERE `id`=? AND `pid`=?", array($rule,$patient_id));
1524 * Function to set a specific rule activity for a specific patient
1526 * @param string $rule id(string) of rule
1527 * @param string $type rule filter (active_alert,passive_alert,cqm,amc,patient_reminder)
1528 * @param string $setting activity of rule (yes,no,default)
1529 * @param integer $patient_id pid of selected patient.
1531 function set_rule_activity_patient($rule, $type, $setting, $patient_id)
1534 // Don't allow messing with the default rules here
1535 if ($patient_id == "0") {
1536 return;
1539 // Convert setting
1540 if ($setting == "on") {
1541 $setting = 1;
1542 } else if ($setting == "off") {
1543 $setting = 0;
1544 } else { // $setting == "default"
1545 $setting = null;
1548 //Collect main rule to allow setting of the access_control
1549 $original_query = "SELECT * FROM `clinical_rules` WHERE `id` = ? AND `pid` = 0";
1550 $patient_rule_original = sqlQueryCdrEngine($original_query, array($rule));
1552 // Collect patient specific rule, if already exists.
1553 $query = "SELECT * FROM `clinical_rules` WHERE `id` = ? AND `pid` = ?";
1554 $patient_rule = sqlQueryCdrEngine($query, array($rule,$patient_id));
1556 if (empty($patient_rule)) {
1557 // Create a new patient specific rule with flags all set to default
1558 $query = "INSERT into `clinical_rules` (`id`, `pid`, `access_control`) VALUES (?,?,?)";
1559 sqlStatementCdrEngine($query, array($rule, $patient_id, $patient_rule_original['access_control']));
1562 // Update patient specific row
1563 $query = "UPDATE `clinical_rules` SET `" . add_escape_custom($type) . "_flag`= ?, `access_control` = ? WHERE id = ? AND pid = ?";
1564 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)
1576 $sql = sqlStatementCdrEngine("SELECT `method_detail`, `value` FROM `rule_reminder` " .
1577 "WHERE `id`=? AND `method`=?", array($rule, $reminder_method));
1579 $returnArray= array();
1580 for ($iter=0; $row=sqlFetchArray($sql); $iter++) {
1581 array_push($returnArray, $row);
1584 return $returnArray;
1588 * Function to return applicable filters
1590 * @param string $rule id(string) of selected rule
1591 * @param string $filter_method string label of filter type
1592 * @param string $include_flag to allow selection for included or excluded filters
1593 * @return array filters
1595 function resolve_filter_sql($rule, $filter_method, $include_flag = 1)
1597 $sql = sqlStatementCdrEngine("SELECT `method_detail`, `value`, `required_flag` FROM `rule_filter` " .
1598 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $filter_method, $include_flag));
1600 $returnArray= array();
1601 for ($iter=0; $row=sqlFetchArray($sql); $iter++) {
1602 array_push($returnArray, $row);
1605 return $returnArray;
1609 * Function to return applicable targets
1611 * @param string $rule id(string) of selected rule
1612 * @param integer $group_id group id of target group (if blank, then will ignore grouping)
1613 * @param string $target_method string label of target type
1614 * @param string $include_flag to allow selection for included or excluded targets
1615 * @return array targets
1617 function resolve_target_sql($rule, $group_id = '', $target_method, $include_flag = 1)
1620 if ($group_id) {
1621 $sql = sqlStatementCdrEngine("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
1622 "WHERE `id`=? AND `group_id`=? AND `method`=? AND `include_flag`=?", array($rule, $group_id, $target_method, $include_flag));
1623 } else {
1624 $sql = sqlStatementCdrEngine("SELECT `value`, `required_flag`, `interval` FROM `rule_target` " .
1625 "WHERE `id`=? AND `method`=? AND `include_flag`=?", array($rule, $target_method, $include_flag));
1628 $returnArray= array();
1629 for ($iter=0; $row=sqlFetchArray($sql); $iter++) {
1630 array_push($returnArray, $row);
1633 return $returnArray;
1637 * Function to return applicable actions
1639 * @param string $rule id(string) of selected rule
1640 * @param integer $group_id group id of target group (if blank, then will ignore grouping)
1641 * @return array actions
1643 function resolve_action_sql($rule, $group_id = '')
1646 if ($group_id) {
1647 $sql = sqlStatementCdrEngine("SELECT b.category, b.item, b.clin_rem_link, b.reminder_message, b.custom_flag " .
1648 "FROM `rule_action` as a " .
1649 "JOIN `rule_action_item` as b " .
1650 "ON a.category = b.category AND a.item = b.item " .
1651 "WHERE a.id=? AND a.group_id=?", array($rule,$group_id));
1652 } else {
1653 $sql = sqlStatementCdrEngine("SELECT b.category, b.item, b.value, b.custom_flag " .
1654 "FROM `rule_action` as a " .
1655 "JOIN `rule_action_item` as b " .
1656 "ON a.category = b.category AND a.item = b.item " .
1657 "WHERE a.id=?", array($rule));
1660 $returnArray= array();
1661 for ($iter=0; $row=sqlFetchArray($sql); $iter++) {
1662 array_push($returnArray, $row);
1665 return $returnArray;
1669 * Function to check database filters and targets
1671 * @param string $patient_id pid of selected patient.
1672 * @param array $filter array containing filter/target elements
1673 * @param array $interval array containing interval elements
1674 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
1675 * @return boolean true if check passed, otherwise false
1677 function database_check($patient_id, $filter, $interval = '', $dateTarget = '')
1679 $isMatch = false; //matching flag
1681 // Set date to current if not set
1682 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1684 // Unpackage interval information
1685 // (Assume only one for now and only pertinent for targets)
1686 $intervalType = '';
1687 $intervalValue = '';
1688 if (!empty($interval)) {
1689 $intervalType = $interval[0]['value'];
1690 $intervalValue = $interval[0]['interval'];
1693 $cond_loop = 0;
1694 foreach ($filter as $row) {
1695 // Row description
1696 // [0]=>special modes
1697 $temp_df = explode("::", $row['value']);
1699 if ($temp_df[0] == "CUSTOM") {
1700 // Row description
1701 // [0]=>special modes(CUSTOM) [1]=>category [2]=>item [3]=>complete? [4]=>number of hits comparison [5]=>number of hits
1702 if (exist_custom_item($patient_id, $temp_df[1], $temp_df[2], $temp_df[3], $temp_df[4], $temp_df[5], $intervalType, $intervalValue, $dateTarget)) {
1703 // Record the match
1704 $isMatch = true;
1705 } else {
1706 // If this is a required entry then return false
1707 if ($row['required_flag']) {
1708 return false;
1711 } else if ($temp_df[0] == "LIFESTYLE") {
1712 // Row description
1713 // [0]=>special modes(LIFESTYLE) [1]=>column [2]=>status
1714 if (exist_lifestyle_item($patient_id, $temp_df[1], $temp_df[2], $dateTarget)) {
1715 // Record the match
1716 $isMatch = true;
1717 } else {
1718 // If this is a required entry then return false
1719 if ($row['required_flag']) {
1720 return false;
1723 } else {
1724 // Default mode
1725 // Row description
1726 // [0]=>special modes(BLANK) [1]=>table [2]=>column [3]=>value comparison [4]=>value [5]=>number of hits comparison [6]=>number of hits
1727 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)) {
1728 // Record the match
1729 if ($cond_loop > 0) { // For multiple condition check
1730 $isMatch = $isMatch && true;
1731 } else {
1732 $isMatch = true;
1734 } else {
1735 // If this is a required entry then return false
1736 if ($row['required_flag']) {
1737 return false;
1742 $cond_loop++;
1745 // return results of check
1746 return $isMatch;
1750 * Function to check procedure filters and targets
1752 * @param string $patient_id pid of selected patient.
1753 * @param array $filter array containing filter/target elements
1754 * @param array $interval array containing interval elements
1755 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
1756 * @return boolean true if check passed, otherwise false
1758 function procedure_check($patient_id, $filter, $interval = '', $dateTarget = '')
1760 $isMatch = false; //matching flag
1762 // Set date to current if not set
1763 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1765 // Unpackage interval information
1766 // (Assume only one for now and only pertinent for targets)
1767 $intervalType = '';
1768 $intervalValue = '';
1769 if (!empty($interval)) {
1770 $intervalType = $interval[0]['value'];
1771 $intervalValue = $interval[0]['interval'];
1774 foreach ($filter as $row) {
1775 // Row description
1776 // [0]=>title [1]=>code [2]=>value comparison [3]=>value [4]=>number of hits comparison [5]=>number of hits
1777 // code description
1778 // <type(ICD9,CPT4)>:<identifier>||<type(ICD9,CPT4)>:<identifier>||<identifier> etc.
1779 $temp_df = explode("::", $row['value']);
1780 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)) {
1781 // Record the match
1782 $isMatch = true;
1783 } else {
1784 // If this is a required entry then return false
1785 if ($row['required_flag']) {
1786 return false;
1791 // return results of check
1792 return $isMatch;
1796 * Function to check for appointment
1798 * @todo Complete this to allow appointment reminders.
1799 * @param string $patient_id pid of selected patient.
1800 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
1801 * @return boolean true if appt exist, otherwise false
1803 function appointment_check($patient_id, $dateTarget = '')
1805 $isMatch = false; //matching flag
1807 // Set date to current if not set (although should always be set)
1808 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1809 $dateTargetRound = date('Y-m-d', $dateTarget);
1811 // Set current date
1812 $currentDate = date('Y-m-d H:i:s');
1813 $currentDateRound = date('Y-m-d', $dateCurrent);
1815 // Basically, if the appointment is within the current date to the target date,
1816 // then return true. (will not send reminders on same day as appointment)
1817 $sql = sqlStatementCdrEngine("SELECT openemr_postcalendar_events.pc_eid, " .
1818 "openemr_postcalendar_events.pc_title, " .
1819 "openemr_postcalendar_events.pc_eventDate, " .
1820 "openemr_postcalendar_events.pc_startTime, " .
1821 "openemr_postcalendar_events.pc_endTime " .
1822 "FROM openemr_postcalendar_events " .
1823 "WHERE openemr_postcalendar_events.pc_eventDate > ? " .
1824 "AND openemr_postcalendar_events.pc_eventDate <= ? " .
1825 "AND openemr_postcalendar_events.pc_pid = ?", array($currentDate,$dateTarget,$patient_id));
1827 // return results of check
1829 // TODO: Figure out how to have multiple appointment and changing appointment reminders.
1830 // Plan to send back array of appt info (eid, time, date, etc.)
1831 // to do this.
1832 if (sqlNumRows($sql) > 0) {
1833 $isMatch = true;
1836 return $isMatch;
1840 * Function to check lists filters and targets. Customizable and currently includes diagnoses, medications, allergies and surgeries.
1842 * @param string $patient_id pid of selected patient.
1843 * @param array $filter array containing lists filter/target elements
1844 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
1845 * @return boolean true if check passed, otherwise false
1847 function lists_check($patient_id, $filter, $dateTarget)
1849 $isMatch = false; //matching flag
1851 // Set date to current if not set
1852 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1854 foreach ($filter as $row) {
1855 if (exist_lists_item($patient_id, $row['method_detail'], $row['value'], $dateTarget)) {
1856 // Record the match
1857 $isMatch = true;
1858 } else {
1859 // If this is a required entry then return false
1860 if ($row['required_flag']) {
1861 return false;
1866 // return results of check
1867 return $isMatch;
1871 * Function to check for existance of data in database for a patient
1873 * @param string $patient_id pid of selected patient.
1874 * @param string $table selected mysql table
1875 * @param string $column selected mysql column
1876 * @param string $data_comp data comparison (eq,ne,gt,ge,lt,le)
1877 * @param string $data selected data in the mysql database (1)(2)
1878 * @param string $num_items_comp number items comparison (eq,ne,gt,ge,lt,le)
1879 * @param integer $num_items_thres number of items threshold
1880 * @param string $intervalType type of interval (ie. year)
1881 * @param integer $intervalValue searched for within this many times of the interval type
1882 * @param string $dateTarget target date(format Y-m-d H:i:s).
1883 * @return boolean true if check passed, otherwise false
1885 * (1) If data ends with **, operators ne/eq are replaced by (NOT)LIKE operators
1886 * (2) If $data contains '#CURDATE#', then it will be converted to the current date.
1889 function exist_database_item($patient_id, $table, $column = '', $data_comp, $data = '', $num_items_comp, $num_items_thres, $intervalType = '', $intervalValue = '', $dateTarget = '')
1892 // Set date to current if not set
1893 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
1895 // Collect the correct column label for patient id in the table
1896 $patient_id_label = collect_database_label('pid', $table);
1898 // Get the interval sql query string
1899 $dateSql = sql_interval_string($table, $intervalType, $intervalValue, $dateTarget);
1901 // If just checking for existence (ie. data is empty),
1902 // then simply set the comparison operator to ne.
1903 if (empty($data)) {
1904 $data_comp = "ne";
1907 // get the appropriate sql comparison operator
1908 $compSql = convertCompSql($data_comp);
1910 // custom issues per table can be placed here
1911 $customSQL = '';
1912 if ($table == 'immunizations') {
1913 $customSQL = " AND `added_erroneously` = '0' ";
1916 //adding table list for where condition
1917 $whereTables = '';
1918 if ($table == 'procedure_result') {
1919 $whereTables = ", procedure_order_code, " .
1920 "procedure_order, " .
1921 "procedure_report " ;
1922 $customSQL = " AND procedure_order.procedure_order_id = procedure_order_code.procedure_order_id AND " .
1923 "procedure_report.procedure_order_id = procedure_order.procedure_order_id AND " .
1924 "procedure_report.procedure_order_seq = procedure_order_code.procedure_order_seq AND " .
1925 "procedure_result.procedure_report_id = procedure_report.procedure_report_id ";
1928 // check for items
1929 if (empty($column)) {
1930 // simple search for any table entries
1931 $sql = sqlStatementCdrEngine("SELECT * " .
1932 "FROM `" . add_escape_custom($table) . "` " .
1933 " ". $whereTables. " ".
1934 "WHERE " . add_escape_custom($patient_id_label) . "=? " . $customSQL, array($patient_id));
1935 } else {
1936 // mdsupport : Allow trailing '**' in the strings to perform LIKE searches
1937 if ((substr($data, -2)=='**') && (($compSql == "=") || ($compSql == "!="))) {
1938 $compSql = ($compSql == "!=" ? " NOT": "")." LIKE CONCAT('%',?,'%') ";
1939 $data = substr_replace($data, '', -2);
1940 } else {
1941 $compSql = $compSql . "? ";
1944 if ($whereTables=="" && strpos($table, 'form_')!== false) {
1945 //To handle standard forms starting with form_
1946 //In this case, we are assuming the date field is "date"
1947 $sql =sqlStatementCdrEngine(
1948 "SELECT b.`" . add_escape_custom($column) . "` " .
1949 "FROM forms a ".
1950 "LEFT JOIN `" . add_escape_custom($table) . "` " . " b ".
1951 "ON (a.form_id=b.id AND a.formdir LIKE '".add_escape_custom(substr($table, 5))."') ".
1952 "WHERE a.deleted != '1' ".
1953 "AND b.`" .add_escape_custom($column) ."`" . $compSql .
1954 "AND b." . add_escape_custom($patient_id_label) . "=? " . $customSQL
1955 . str_replace("`date`", "b.`date`", $dateSql),
1956 array($data, $patient_id)
1958 } else {
1959 // This allows to enter the wild card #CURDATE# in the CDR Demographics filter criteria at the value field
1960 // #CURDATE# is replace by the Current date allowing a dynamic date filtering
1961 if ($data=='#CURDATE#') {
1962 $data = date("Y-m-d");
1965 // search for number of specific items
1966 $sql = sqlStatementCdrEngine("SELECT `" . add_escape_custom($column) . "` " .
1967 "FROM `" . add_escape_custom($table) . "` " .
1968 " " . $whereTables . " " .
1969 "WHERE `" . add_escape_custom($column) . "`" . $compSql .
1970 "AND " . add_escape_custom($patient_id_label) . "=? " . $customSQL .
1971 $dateSql, array($data, $patient_id));
1975 // See if number of returned items passes the comparison
1976 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
1980 * Function to check for existence of procedure(s) for a patient
1982 * @param string $patient_id pid of selected patient.
1983 * @param string $proc_title procedure title
1984 * @param string $proc_code procedure identifier code (array of <type(ICD9,CPT4)>:<identifier>||<type(ICD9,CPT4)>:<identifier>||<identifier> etc.)
1985 * @param string $results_comp results comparison (eq,ne,gt,ge,lt,le)
1986 * @param string $result_data results data (1)
1987 * @param string $num_items_comp number items comparison (eq,ne,gt,ge,lt,le)
1988 * @param integer $num_items_thres number of items threshold
1989 * @param string $intervalType type of interval (ie. year)
1990 * @param integer $intervalValue searched for within this many times of the interval type
1991 * @param string $dateTarget target date(format Y-m-d H:i:s).
1992 * @return boolean true if check passed, otherwise false
1994 * (1) If result_data ends with **, operators ne/eq are replaced by (NOT)LIKE operators
1997 function exist_procedure_item($patient_id, $proc_title, $proc_code, $result_comp, $result_data = '', $num_items_comp, $num_items_thres, $intervalType = '', $intervalValue = '', $dateTarget = '')
2000 // Set date to current if not set
2001 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
2003 // Set the table exception (for looking up pertinent date and pid sql columns)
2004 $table = "PROCEDURE-EXCEPTION";
2006 // Collect the correct column label for patient id in the table
2007 $patient_id_label = collect_database_label('pid', $table);
2009 // Get the interval sql query string
2010 $dateSql = sql_interval_string($table, $intervalType, $intervalValue, $dateTarget);
2012 // If just checking for existence (ie result_data is empty),
2013 // then simply set the comparison operator to ne.
2014 if (empty($result_data)) {
2015 $result_comp = "ne";
2018 // get the appropriate sql comparison operator
2019 $compSql = convertCompSql($result_comp);
2021 // explode the code array
2022 $codes= array();
2023 if (!empty($proc_code)) {
2024 $codes = explode("||", $proc_code);
2025 } else {
2026 $codes[0] = '';
2029 // ensure proc_title is at least blank
2030 if (empty($proc_title)) {
2031 $proc_title = '';
2034 // collect specific items (use both title and/or codes) that fulfill request
2035 $sqlBindArray=array();
2036 $sql_query = "SELECT procedure_result.result FROM " .
2037 "procedure_order_code, " .
2038 "procedure_order, " .
2039 "procedure_type, " .
2040 "procedure_report, " .
2041 "procedure_result " .
2042 "WHERE " .
2043 "procedure_order_code.procedure_code = procedure_type.procedure_code AND " .
2044 "procedure_order.procedure_order_id = procedure_order_code.procedure_order_id AND " .
2045 "procedure_order.lab_id = procedure_type.lab_id AND " .
2046 "procedure_report.procedure_order_id = procedure_order.procedure_order_id AND " .
2047 "procedure_report.procedure_order_seq = procedure_order_code.procedure_order_seq AND " .
2048 "procedure_result.procedure_report_id = procedure_report.procedure_report_id AND " .
2049 "procedure_type.procedure_type = 'ord' AND ";
2050 foreach ($codes as $tem) {
2051 $sql_query .= "( ( (procedure_type.standard_code = ? AND procedure_type.standard_code != '') " .
2052 "OR (procedure_type.procedure_code = ? AND procedure_type.procedure_code != '') ) OR ";
2053 array_push($sqlBindArray, $tem, $tem);
2056 // mdsupport : Allow trailing '**' in the strings to perform LIKE searches
2057 if ((substr($result_data, -2)=='**') && (($compSql == "=") || ($compSql == "!="))) {
2058 $compSql = ($compSql == "!=" ? " NOT": "")." LIKE CONCAT('%',?,'%') ";
2059 $result_data = substr_replace($result_data, '', -2);
2060 } else {
2061 $compSql = $compSql . "? ";
2064 $sql_query .= "(procedure_type.name = ? AND procedure_type.name != '') ) " .
2065 "AND procedure_result.result " . $compSql .
2066 "AND " . add_escape_custom($patient_id_label) . " = ? " . $dateSql;
2067 array_push($sqlBindArray, $proc_title, $result_data, $patient_id);
2069 $sql = sqlStatementCdrEngine($sql_query, $sqlBindArray);
2071 // See if number of returned items passes the comparison
2072 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
2076 * Function to check for existance of data for a patient in the rule_patient_data table
2078 * @param string $patient_id pid of selected patient.
2079 * @param string $category label in category column
2080 * @param string $item label in item column
2081 * @param string $complete label in complete column (YES,NO, or blank)
2082 * @param string $num_items_comp number items comparison (eq,ne,gt,ge,lt,le)
2083 * @param integer $num_items_thres number of items threshold
2084 * @param string $intervalType type of interval (ie. year)
2085 * @param integer $intervalValue searched for within this many times of the interval type
2086 * @param string $dateTarget target date(format Y-m-d H:i:s).
2087 * @return boolean true if check passed, otherwise false
2089 function exist_custom_item($patient_id, $category, $item, $complete, $num_items_comp, $num_items_thres, $intervalType = '', $intervalValue = '', $dateTarget)
2092 // Set the table
2093 $table = 'rule_patient_data';
2095 // Collect the correct column label for patient id in the table
2096 $patient_id_label = collect_database_label('pid', $table);
2098 // Get the interval sql query string
2099 $dateSql = sql_interval_string($table, $intervalType, $intervalValue, $dateTarget);
2101 // search for number of specific items
2102 $sql = sqlStatementCdrEngine("SELECT `result` " .
2103 "FROM `" . add_escape_custom($table) . "` " .
2104 "WHERE `category`=? " .
2105 "AND `item`=? " .
2106 "AND `complete`=? " .
2107 "AND `" . add_escape_custom($patient_id_label) . "`=? " .
2108 $dateSql, array($category,$item,$complete,$patient_id));
2110 // See if number of returned items passes the comparison
2111 return itemsNumberCompare($num_items_comp, $num_items_thres, sqlNumRows($sql));
2115 * Function to check for existance of data for a patient in lifestyle section
2117 * @param string $patient_id pid of selected patient.
2118 * @param string $lifestyle selected label of mysql column of patient history
2119 * @param string $status specific status of selected lifestyle element
2120 * @param string $dateTarget target date(format Y-m-d H:i:s). blank is current date.
2121 * @return boolean true if check passed, otherwise false
2123 function exist_lifestyle_item($patient_id, $lifestyle, $status, $dateTarget)
2126 // Set date to current if not set
2127 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
2129 // Collect pertinent history data
2130 $history = getHistoryData($patient_id, $lifestyle, '', $dateTarget);
2132 // See if match
2133 $stringFlag = strstr($history[$lifestyle], "|".$status);
2134 if (empty($status)) {
2135 // Only ensuring any data has been entered into the field
2136 $stringFlag = true;
2139 if ($history[$lifestyle] &&
2140 $history[$lifestyle] != '|0|' &&
2141 $stringFlag ) {
2142 return true;
2143 } else {
2144 return false;
2149 * Function to check for lists item of a patient. Fully customizable and includes diagnoses, medications,
2150 * allergies, and surgeries.
2152 * @param string $patient_id pid of selected patient.
2153 * @param string $type type (medical_problem, allergy, medication, etc)
2154 * @param string $value value searching for (1)
2155 * @param string $dateTarget target date(format Y-m-d H:i:s).
2156 * @return boolean true if check passed, otherwise false
2158 * (1) If value ends with **, operators ne/eq are replaced by (NOT)LIKE operators
2161 function exist_lists_item($patient_id, $type, $value, $dateTarget)
2164 // Set date to current if not set
2165 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
2167 // Attempt to explode the value into a code type and code (if applicable)
2168 $value_array = explode("::", $value);
2169 if (count($value_array) == 2) {
2170 // Collect the code type and code
2171 $code_type = $value_array[0];
2172 $code = $value_array[1];
2174 // Modify $code for both 'CUSTOM' and diagnosis searches
2175 // Note: Diagnosis is always 'LIKE' and should not have '**'
2176 if (substr($code, -2)=='**') {
2177 $sqloper = " LIKE CONCAT('%',?,'%') ";
2178 $code = substr_replace($code, '', -2);
2179 } else {
2180 $sqloper = "=?";
2183 if ($code_type=='CUSTOM') {
2184 // Deal with custom code type first (title column in lists table)
2185 $response = sqlQueryCdrEngine("SELECT * FROM `lists` " .
2186 "WHERE `type`=? " .
2187 "AND `pid`=? " .
2188 "AND `title` $sqloper " .
2189 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
2190 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$code,$dateTarget,$dateTarget,$dateTarget));
2191 if (!empty($response)) {
2192 return true;
2194 } else {
2195 // Deal with the set code types (diagnosis column in lists table)
2196 $response = sqlQueryCdrEngine("SELECT * FROM `lists` " .
2197 "WHERE `type`=? " .
2198 "AND `pid`=? " .
2199 "AND `diagnosis` LIKE ? " .
2200 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
2201 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,"%".$code_type.":".$code."%",$dateTarget,$dateTarget,$dateTarget));
2202 if (!empty($response)) {
2203 return true;
2206 } else { // count($value_array) == 1
2207 // Search the title column in lists table
2208 // Yes, this is essentially the same as the code type listed as CUSTOM above. This provides flexibility and will ensure compatibility.
2210 // Check for '**'
2211 if (substr($value, -2)=='**') {
2212 $sqloper = " LIKE CONCAT('%',?,'%') ";
2213 $value = substr_replace($value, '', -2);
2214 } else {
2215 $sqloper = "=?";
2218 $response = sqlQueryCdrEngine("SELECT * FROM `lists` " .
2219 "WHERE `type`=? " .
2220 "AND `pid`=? " .
2221 "AND `title` $sqloper ".
2222 "AND ( (`begdate` IS NULL AND `date`<=?) OR (`begdate` IS NOT NULL AND `begdate`<=?) ) " .
2223 "AND ( (`enddate` IS NULL) OR (`enddate` IS NOT NULL AND `enddate`>=?) )", array($type,$patient_id,$value,$dateTarget,$dateTarget,$dateTarget));
2224 if (!empty($response)) {
2225 return true;
2228 if ($type == 'medication') { // Special case needed for medication as it need to be looked into current medications (prescriptions table) from ccda import
2229 $response = sqlQueryCdrEngine("SELECT * FROM `prescriptions` where `patient_id` = ? and `drug` $sqloper and `date_added` <= ?", array($patient_id,$value,$dateTarget));
2230 if (!empty($response)) {
2231 return true;
2236 return false;
2240 * Function to return part of sql query to deal with interval
2242 * @param string $table selected mysql table (or EXCEPTION(s))
2243 * @param string $intervalType type of interval (ie. year)
2244 * @param string $intervalValue searched for within this many times of the interval type
2245 * @param string $dateTarget target date(format Y-m-d H:i:s).
2246 * @return string contains pertinent date interval filter for mysql query
2248 function sql_interval_string($table, $intervalType, $intervalValue, $dateTarget)
2251 $dateSql="";
2253 // Collect the correct column label for date in the table
2254 $date_label = collect_database_label('date', $table);
2256 // Deal with interval
2257 if (!empty($intervalType)) {
2258 switch ($intervalType) {
2259 case "year":
2260 $dateSql = "AND (" . add_escape_custom($date_label) .
2261 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2262 "', INTERVAL " . add_escape_custom($intervalValue) .
2263 " YEAR) AND '" . add_escape_custom($dateTarget) . "') ";
2264 break;
2265 case "month":
2266 $dateSql = "AND (" . add_escape_custom($date_label) .
2267 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2268 "', INTERVAL " . add_escape_custom($intervalValue) .
2269 " MONTH) AND '" . add_escape_custom($dateTarget) . "') ";
2270 break;
2271 case "week":
2272 $dateSql = "AND (" . add_escape_custom($date_label) .
2273 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2274 "', INTERVAL " . add_escape_custom($intervalValue) .
2275 " WEEK) AND '" . add_escape_custom($dateTarget) . "') ";
2276 break;
2277 case "day":
2278 $dateSql = "AND (" . add_escape_custom($date_label) .
2279 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2280 "', INTERVAL " . add_escape_custom($intervalValue) .
2281 " DAY) AND '" . add_escape_custom($dateTarget) . "') ";
2282 break;
2283 case "hour":
2284 $dateSql = "AND (" . add_escape_custom($date_label) .
2285 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2286 "', INTERVAL " . add_escape_custom($intervalValue) .
2287 " HOUR) AND '" . add_escape_custom($dateTarget) . "') ";
2288 break;
2289 case "minute":
2290 $dateSql = "AND (" . add_escape_custom($date_label) .
2291 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2292 "', INTERVAL " . add_escape_custom($intervalValue) .
2293 " MINUTE) AND '" . add_escape_custom($dateTarget) . "') ";
2294 break;
2295 case "second":
2296 $dateSql = "AND (" . add_escape_custom($date_label) .
2297 " BETWEEN DATE_SUB('" . add_escape_custom($dateTarget) .
2298 "', INTERVAL " . add_escape_custom($intervalValue) .
2299 " SECOND) AND '" . add_escape_custom($dateTarget) . "') ";
2300 break;
2301 case "flu_season":
2302 // Flu season to be hard-coded as September thru February
2303 // (Should make this modifiable in the future)
2304 // ($intervalValue is not used)
2305 $dateArray = explode("-", $dateTarget);
2306 $Year = $dateArray[0];
2307 $dateThisYear = $Year . "-09-01";
2308 $dateLastYear = ($Year-1) . "-09-01";
2309 $dateSql =" " .
2310 "AND ((" .
2311 "MONTH('" . add_escape_custom($dateTarget) . "') < 9 " .
2312 "AND " . add_escape_custom($date_label) . " >= '" . $dateLastYear . "' ) " .
2313 "OR (" .
2314 "MONTH('" . add_escape_custom($dateTarget) . "') >= 9 " .
2315 "AND " . add_escape_custom($date_label) . " >= '" . $dateThisYear . "' ))" .
2316 "AND " . add_escape_custom($date_label) . " <= '" . add_escape_custom($dateTarget) . "' ";
2317 break;
2319 } else {
2320 $dateSql = "AND " . add_escape_custom($date_label) .
2321 " <= '" . add_escape_custom($dateTarget) . "' ";
2324 // return the sql interval string
2325 return $dateSql;
2329 * Function to collect generic column labels from tables. It currently works for date
2330 * and pid. Will need to expand this as algorithm grows.
2332 * @param string $label element (pid or date)
2333 * @param string $table selected mysql table (or EXCEPTION(s))
2334 * @return string contains official label of selected element
2336 function collect_database_label($label, $table)
2339 if ($table == 'PROCEDURE-EXCEPTION') {
2340 // return cell to get procedure collection
2341 // special case since reuqires joing of multiple
2342 // tables to get this value
2343 if ($label == "pid") {
2344 $returnedLabel = "procedure_order.patient_id";
2345 } else if ($label == "date") {
2346 $returnedLabel = "procedure_report.date_collected";
2347 } else {
2348 // unknown label, so return the original label
2349 $returnedLabel = $label;
2351 } else if ($table == 'immunizations') {
2352 // return requested label for immunization table
2353 if ($label == "pid") {
2354 $returnedLabel = "patient_id";
2355 } else if ($label == "date") {
2356 $returnedLabel = "`administered_date`";
2357 } else {
2358 // unknown label, so return the original label
2359 $returnedLabel = $label;
2361 } else if ($table == 'prescriptions') {
2362 // return requested label for prescriptions table
2363 if ($label == "pid") {
2364 $returnedLabel = "patient_id";
2365 } else if ($label == "date") {
2366 $returnedLabel = 'date_added';
2367 } else {
2368 // unknown label, so return the original label
2369 $returnedLabel = $label;
2371 } else if ($table == 'procedure_result') {
2372 // return requested label for prescriptions table
2373 if ($label == "pid") {
2374 $returnedLabel = "procedure_order.patient_id";
2375 } else if ($label == "date") {
2376 $returnedLabel = "procedure_report.date_collected";
2377 } else {
2378 // unknown label, so return the original label
2379 $returnedLabel = $label;
2381 } else {
2382 // return requested label for default tables
2383 if ($label == "pid") {
2384 $returnedLabel = "pid";
2385 } else if ($label == "date") {
2386 $returnedLabel = "`date`";
2387 } else {
2388 // unknown label, so return the original label
2389 $returnedLabel = $label;
2393 return $returnedLabel;
2397 * Simple function to avoid processing of duplicate actions
2399 * @param string $actions 2-dimensional array with all current active targets
2400 * @param string $action array of selected target to test for duplicate
2401 * @return boolean true if duplicate, false if not duplicate
2403 function is_duplicate_action($actions, $action)
2405 foreach ($actions as $row) {
2406 if ($row['category'] == $action['category'] &&
2407 $row['item'] == $action['item'] &&
2408 $row['value'] == $action['value']) {
2409 // Is a duplicate
2410 return true;
2414 // Not a duplicate
2415 return false;
2419 * Calculate the reminder dates.
2421 * This function returns an array that contains three elements (each element is a date).
2422 * <pre>The three dates are:
2423 * first date is before the target date (past_due) (default of 1 month)
2424 * second date is the target date (due)
2425 * third date is after the target date (soon_due) (default of 2 weeks)
2426 * </pre>
2428 * @param string $rule id(string) of selected rule
2429 * @param string $dateTarget target date(format Y-m-d H:i:s).
2430 * @param string $type either 'patient_reminder' or 'clinical_reminder'
2431 * @return array see above for description of returned array
2433 function calculate_reminder_dates($rule, $dateTarget = '', $type)
2436 // Set date to current if not set
2437 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
2439 // Collect the current date settings (to ensure not skip)
2440 $res = resolve_reminder_sql($rule, $type.'_current');
2441 if (!empty($res)) {
2442 $row = $res[0];
2443 if ($row ['method_detail'] == "SKIP") {
2444 $dateTarget = "SKIP";
2448 // Collect the past_due date
2449 $past_due_date = "";
2450 $res = resolve_reminder_sql($rule, $type.'_post');
2451 if (!empty($res)) {
2452 $row = $res[0];
2453 if ($row ['method_detail'] == "week") {
2454 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " week"));
2457 if ($row ['method_detail'] == "month") {
2458 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " month"));
2461 if ($row ['method_detail'] == "hour") {
2462 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
2465 if ($row ['method_detail'] == "SKIP") {
2466 $past_due_date = "SKIP";
2468 } else {
2469 // empty settings, so use default of one month
2470 $past_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -1 month"));
2473 // Collect the soon_due date
2474 $soon_due_date = "";
2475 $res = resolve_reminder_sql($rule, $type.'_pre');
2476 if (!empty($res)) {
2477 $row = $res[0];
2478 if ($row ['method_detail'] == "week") {
2479 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " week"));
2482 if ($row ['method_detail'] == "month") {
2483 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +" . $row ['value'] . " month"));
2486 if ($row ['method_detail'] == "hour") {
2487 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " -" . $row ['value'] . " hour"));
2490 if ($row ['method_detail'] == "SKIP") {
2491 $soon_due_date = "SKIP";
2493 } else {
2494 // empty settings, so use default of one month
2495 $soon_due_date = date("Y-m-d H:i:s", strtotime($dateTarget . " +2 week"));
2498 // Return the array of three dates
2499 return array($soon_due_date,$dateTarget,$past_due_date);
2503 * Adds an action into the reminder array
2505 * @param array $reminderOldArray Contains the current array of reminders
2506 * @param array $reminderNew Array of a new reminder
2507 * @return array Reminders
2509 function reminder_results_integrate($reminderOldArray, $reminderNew)
2512 $results = array();
2514 // If reminderArray is empty, then insert new reminder
2515 if (empty($reminderOldArray)) {
2516 array_push($results, $reminderNew);
2517 return $results;
2520 // If duplicate reminder, then replace the old one
2521 $duplicate = false;
2522 foreach ($reminderOldArray as $reminderOld) {
2523 if ($reminderOld['pid'] == $reminderNew['pid'] &&
2524 $reminderOld['category'] == $reminderNew['category'] &&
2525 $reminderOld['item'] == $reminderNew['item']) {
2526 array_push($results, $reminderNew);
2527 $duplicate = true;
2528 } else {
2529 array_push($results, $reminderOld);
2533 // If a new reminder, then insert the new reminder
2534 if (!$duplicate) {
2535 array_push($results, $reminderNew);
2538 return $results;
2542 * Compares number of items with requested comparison operator
2544 * @param string $comp Comparison operator(eq,ne,gt,ge,lt,le)
2545 * @param string $thres Threshold used in comparison
2546 * @param integer $num_items Number of items
2547 * @return boolean Comparison results
2549 function itemsNumberCompare($comp, $thres, $num_items)
2552 if (($comp == "eq") && ($num_items == $thres)) {
2553 return true;
2554 } else if (($comp == "ne") && ($num_items != $thres) && ($num_items > 0)) {
2555 return true;
2556 } else if (($comp == "gt") && ($num_items > $thres)) {
2557 return true;
2558 } else if (($comp == "ge") && ($num_items >= $thres)) {
2559 return true;
2560 } else if (($comp == "lt") && ($num_items < $thres) && ($num_items > 0)) {
2561 return true;
2562 } else if (($comp == "le") && ($num_items <= $thres) && ($num_items > 0)) {
2563 return true;
2564 } else {
2565 return false;
2570 * Converts a text comparison operator to sql equivalent
2572 * @param string $comp Comparison operator(eq,ne,gt,ge,lt,le)
2573 * @return string contains sql compatible comparison operator
2575 function convertCompSql($comp)
2578 if ($comp == "eq") {
2579 return "=";
2580 } else if ($comp == "ne") {
2581 return "!=";
2582 } else if ($comp == "gt") {
2583 return ">";
2584 } else if ($comp == "ge") {
2585 return ">=";
2586 } else if ($comp == "lt") {
2587 return "<";
2588 } else { // ($comp == "le")
2589 return "<=";
2595 * Function to find age in years (with decimal) on the target date
2597 * @param string $dob date of birth
2598 * @param string $target date to calculate age on
2599 * @return float years(decimal) from dob to target(date)
2601 function convertDobtoAgeYearDecimal($dob, $target)
2603 $ageInfo=parseAgeInfo($dob, $target);
2604 return $ageInfo['age'];
2608 * Function to find age in months (with decimal) on the target date
2610 * @param string $dob date of birth
2611 * @param string $target date to calculate age on
2612 * @return float months(decimal) from dob to target(date)
2614 function convertDobtoAgeMonthDecimal($dob, $target)
2616 $ageInfo=parseAgeInfo($dob, $target);
2617 return $ageInfo['age_in_months'];
2621 * Function to calculate the percentage for reports.
2623 * @param integer $pass_filter number of patients that pass filter
2624 * @param integer $exclude_filter number of patients that are excluded
2625 * @param integer $pass_target number of patients that pass target
2626 * @return string Number formatted into a percentage
2628 function calculate_percentage($pass_filt, $exclude_filt, $pass_targ)
2630 if ($pass_filt > 0) {
2631 $perc = number_format(($pass_targ/($pass_filt-$exclude_filt))*100, 4) . xl('%');
2632 } else {
2633 $perc = "0". xl('%');
2636 return $perc;