php fixes for #1486 #1471 and #1469
[openemr.git] / library / reminders.php
blob3c95d48ee1df862f571bb93c2ba1306b091ceebc
1 <?php
2 /**
3 * Patient reminders 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 * Functions for collection/displaying/sending patient reminders. This is
10 * part of the CDR engine, which can be found at library/clinical_rules.php.
12 * Copyright (C) 2010-2012 Brady Miller <brady.g.miller@gmail.com>
14 * LICENSE: This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation; either version 2
17 * of the License, or (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
25 * @package OpenEMR
26 * @author Brady Miller <brady.g.miller@gmail.com>
27 * @link http://www.open-emr.org
30 /**
31 * Include the main CDR engine library, email class and maviq class
33 require_once(dirname(__FILE__) . "/clinical_rules.php");
34 require_once(dirname(__FILE__) . "/maviq_phone_api.php");
36 /**
37 * Display the patient reminder widget.
39 * @param integer $patient_id pid of selected patient
40 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
42 function patient_reminder_widget($patient_id, $dateTarget = '')
45 // Set date to current if not set
46 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
48 // Update reminders for patient
49 update_reminders($dateTarget, $patient_id);
51 // Fetch the active reminders
52 $listReminders = fetch_reminders($patient_id);
54 if (empty($listReminders)) {
55 // No reminders to show.
56 echo htmlspecialchars(xl('No active patient reminders.'), ENT_NOQUOTES);
57 return;
60 echo "<table cellpadding='0' cellspacing='0'>";
61 foreach ($listReminders as $reminder) {
62 echo "<tr><td style='padding:0 1em 0 1em;'><span class='small'>";
63 // show reminder label
64 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'), $reminder['category']) .
65 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'), $reminder['item']);
66 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
67 // show reminder due status
68 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'), $reminder['due_status']);
69 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
70 // show reminder sent date
71 if (empty($reminder['date_sent'])) {
72 echo htmlspecialchars(xl('Reminder Not Sent Yet'), ENT_NOQUOTES);
73 } else {
74 echo htmlspecialchars(xl('Reminder Sent On').": ".$reminder['date_sent'], ENT_NOQUOTES);
77 echo "</span></td></tr>";
80 echo "</table>";
83 /**
84 * Function to update reminders via a batching method to improve performance and decrease memory overhead.
86 * Function that updates reminders and returns an array with a specific data structure.
87 * <pre>The data structure of the return array includes the following elements
88 * 'total_active_actions' - Number of active actions.
89 * 'total_pre_active_reminders' - Number of active reminders before processing.
90 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
91 * 'total_post_active_reminders' - Number of active reminders after processing.
92 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
93 * 'number_new_reminders' - Number of new reminders
94 * 'number_updated_reminders' - Number of updated reminders (due_status change)
95 * 'number_inactivated_reminders' - Number of inactivated reminders.
96 * 'number_unchanged_reminders' - Number of unchanged reminders.
97 * </pre>
99 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
100 * @param integer $batchSize number of patients to batch (default is 25; plan to optimize this default setting in the future)
101 * @param integer $report_id id of report in database (if already bookmarked)
102 * @param boolean $also_send if TRUE, then will also call send_reminder when done
103 * @return array see above for data structure of returned array
105 function update_reminders_batch_method($dateTarget = '', $batchSize = 25, $report_id = null, $also_send = false)
108 // Default to a batchsize, if empty
109 if (empty($batchSize)) {
110 $batchSize=25;
113 // Collect total number of pertinent patients (to calculate batching parameters)
114 $totalNumPatients = buildPatientArray('', '', '', null, null, true);
116 // Cycle through the batches and collect/combine results
117 if (($totalNumPatients%$batchSize) > 0) {
118 $totalNumberBatches = floor($totalNumPatients/$batchSize) + 1;
119 } else {
120 $totalNumberBatches = floor($totalNumPatients/$batchSize);
123 // Prepare the database to track/store results
124 if ($also_send) {
125 $report_id = beginReportDatabase("process_send_reminders", '', $report_id);
126 } else {
127 $report_id = beginReportDatabase("process_reminders", '', $report_id);
130 setTotalItemsReportDatabase($report_id, $totalNumPatients);
132 $patient_counter=0;
133 for ($i=0; $i<$totalNumberBatches; $i++) {
134 $patient_counter = $batchSize*($i+1);
135 if ($patient_counter > $totalNumPatients) {
136 $patient_counter = $totalNumPatients;
139 $update_rem_log_batch = update_reminders($dateTarget, '', (($batchSize*$i)+1), $batchSize);
140 if ($i == 0) {
141 // For first cycle, simply copy it to update_rem_log
142 $update_rem_log = $update_rem_log_batch;
143 } else {
144 // Debug statements
145 //error_log("CDR: ".print_r($update_rem_log,TRUE),0);
146 //error_log("CDR: ".($batchSize*$i). " records",0);
148 // Integrate batch results into main update_rem_log
149 $update_rem_log['total_active_actions'] = $update_rem_log['total_active_actions'] + $update_rem_log_batch['total_active_actions'];
150 $update_rem_log['total_pre_active_reminders'] = $update_rem_log['total_pre_active_reminders'] + $update_rem_log_batch['total_pre_active_reminders'];
151 $update_rem_log['total_pre_unsent_reminders'] = $update_rem_log['total_pre_unsent_reminders'] + $update_rem_log_batch['total_pre_unsent_reminders'];
152 $update_rem_log['number_new_reminders'] = $update_rem_log['number_new_reminders'] + $update_rem_log_batch['number_new_reminders'];
153 $update_rem_log['number_updated_reminders'] = $update_rem_log['number_updated_reminders'] + $update_rem_log_batch['number_updated_reminders'];
154 $update_rem_log['number_unchanged_reminders'] = $update_rem_log['number_unchanged_reminders'] + $update_rem_log_batch['number_unchanged_reminders'];
155 $update_rem_log['number_inactivated_reminders'] = $update_rem_log['number_inactivated_reminders'] + $update_rem_log_batch['number_inactivated_reminders'];
156 $update_rem_log['total_post_active_reminders'] = $update_rem_log['total_post_active_reminders'] + $update_rem_log_batch['total_post_active_reminders'];
157 $update_rem_log['total_post_unsent_reminders'] = $update_rem_log['total_post_unsent_reminders'] + $update_rem_log_batch['total_post_unsent_reminders'];
160 //Update database to track results
161 updateReportDatabase($report_id, $patient_counter);
164 // Create an array for saving to database (allows combining with the send log)
165 $save_log = array();
166 $save_log[] = $update_rem_log;
168 // Send reminders, if this was selected
169 if ($also_send) {
170 $log_send = send_reminders();
171 $save_log[] = $log_send;
174 // Record combo results in database
175 finishReportDatabase($report_id, json_encode($save_log));
177 // Just return the process reminders array
178 return $update_rem_log;
182 * Function to update reminders.
184 * Function that updates reminders and returns an array with a specific data structure.
185 * <pre>The data structure of the return array includes the following elements
186 * 'total_active_actions' - Number of active actions.
187 * 'total_pre_active_reminders' - Number of active reminders before processing.
188 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
189 * 'total_post_active_reminders' - Number of active reminders after processing.
190 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
191 * 'number_new_reminders' - Number of new reminders
192 * 'number_updated_reminders' - Number of updated reminders (due_status change)
193 * 'number_inactivated_reminders' - Number of inactivated reminders.
194 * 'number_unchanged_reminders' - Number of unchanged reminders.
195 * </pre>
197 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
198 * @param integer $patient_id pid of patient. If blank then will check all patients.
199 * @param integer $start applicable patient to start at (when batching process)
200 * @param integer $batchSize number of patients to batch (when batching process)
201 * @return array see above for data structure of returned array
203 function update_reminders($dateTarget = '', $patient_id = '', $start = null, $batchSize = null)
206 $logging = array();
208 // Set date to current if not set
209 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
211 // Collect reminders (note that this function removes redundant and keeps the most distant
212 // reminder (ie. prefers 'past_due' over 'due' over 'soon_due')
213 // Note that due to a limitation in the test_rules_clinic function, the patient_id is explicitly
214 // needed to work correctly. So rather than pass in a '' patient_id to do the entire clinic,
215 // we instead need to pass in each patient_id separately.
216 $collectedReminders = array();
217 $patient_id_complete = "";
218 if (!(empty($patient_id))) {
219 // only one patient id, so run the function
220 $collectedReminders = test_rules_clinic('', 'patient_reminder', $dateTarget, 'reminders-due', $patient_id);
221 $patient_id_complete = $patient_id;
222 } else {
223 // as described above, need to pass in each patient_id
224 // Collect all patient ids
225 $patientData = buildPatientArray('', '', '', $start, $batchSize);
226 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
227 $patientData[$iter]=$row;
230 $first_flag = true;
231 foreach ($patientData as $patient) {
232 // collect reminders
233 $tempCollectReminders = test_rules_clinic('', 'patient_reminder', $dateTarget, 'reminders-due', $patient['pid']);
234 $collectedReminders = array_merge($collectedReminders, $tempCollectReminders);
235 // build the $patient_id_complete variable
236 if ($first_flag) {
237 $patient_id_complete .= $patient['pid'];
238 $first_flag = false;
239 } else {
240 $patient_id_complete .= ",".$patient['pid'];
245 $logging['total_active_actions'] = count($collectedReminders);
247 // For logging purposes only:
248 // Collect number active of active and unsent reminders
249 $logging['total_pre_active_reminders'] = count(fetch_reminders($patient_id_complete));
250 $logging['total_pre_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
252 // Migrate reminders into the patient_reminders table
253 $logging['number_new_reminders'] = 0;
254 $logging['number_updated_reminders'] = 0;
255 $logging['number_unchanged_reminders'] = 0;
256 foreach ($collectedReminders as $reminder) {
257 // See if a reminder already exist
258 $sql = "SELECT `id`, `pid`, `due_status`, `category`, `item` FROM `patient_reminders` WHERE " .
259 "`active`='1' AND `pid`=? AND `category`=? AND `item`=?";
260 $result = sqlQueryCdrEngine($sql, array($reminder['pid'], $reminder['category'], $reminder['item']));
262 if (empty($result)) {
263 // It does not yet exist, so add a new reminder
264 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
265 "VALUES (?, ?, ?, ?, NOW())";
266 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']));
267 $logging['number_new_reminders']++;
268 } else {
269 // It already exist (see if if needs to be updated via adding a new reminder)
270 if ($reminder['due_status'] == $result['due_status']) {
271 // No change in due status, so no need to update
272 $logging['number_unchanged_reminders']++;
273 continue;
274 } else {
275 // Change in due status, so inactivate current reminder and create a new one
276 // First, inactivate the previous reminder
277 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'due_status_update', " .
278 "`date_inactivated` = NOW() WHERE `id`=?";
279 sqlStatementCdrEngine($sql, array($result['id']));
280 // Then, add the new reminder
281 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
282 "VALUES (?, ?, ?, ?, NOW())";
283 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']));
288 // Inactivate reminders that no longer exist
289 // Go through each active reminder and ensure it is in the current list
290 $sqlReminders = fetch_reminders($patient_id_complete);
291 $logging['number_inactivated_reminders'] = 0;
292 foreach ($sqlReminders as $row) {
293 $inactivateFlag = true;
294 foreach ($collectedReminders as $reminder) {
295 if (($row['pid'] == $reminder['pid']) &&
296 ($row['category'] == $reminder['category']) &&
297 ($row['item'] == $reminder['item']) &&
298 ($row['due_status'] == $reminder['due_status']) ) {
299 // The sql reminder has been confirmed, so do not inactivate it
300 $inactivateFlag = false;
301 break;
305 if ($inactivateFlag) {
306 // The sql reminder was not confirmed, so inactivate it
307 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'auto', " .
308 "`date_inactivated` = NOW() WHERE `id`=?";
309 sqlStatementCdrEngine($sql, array($row['id']));
310 $logging['number_inactivated_reminders']++;
314 // For logging purposes only:
315 // Collect number of active and unsent reminders
316 $logging['total_post_active_reminders'] = count(fetch_reminders($patient_id_complete));
317 $logging['total_post_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
319 return $logging;
324 * Function to send reminders.
326 * Function that sends reminders and returns an array with a specific data structure.
327 * <pre>The data structure of the return array includes the following elements
328 * 'total_pre_unsent_reminders' - Number of reminders before processing.
329 * 'total_post_unsent_reminders' - Number of reminders after processing.
330 * 'number_success_emails' - Number of successfully sent email reminders.
331 * 'number_failed_emails' - Number of failed sent email reminders.
332 * 'number_success_calls' - Number of successfully call reminders.
333 * 'number_failed_calls' - Number of failed call reminders.
334 * </pre>
336 * @return array see above for data structure of returned array
338 function send_reminders()
341 $logging = array();
343 // Collect active reminders that have not yet been sent.
344 $active_unsent_reminders = fetch_reminders('', 'unsent');
345 $logging['total_pre_unsent_reminders'] = count($active_unsent_reminders);
347 // Send the unsent reminders
348 $logging['number_success_emails'] = 0;
349 $logging['number_failed_emails'] = 0;
350 $logging['number_success_calls'] = 0;
351 $logging['number_failed_calls'] = 0;
352 foreach ($active_unsent_reminders as $reminder) {
353 // Collect patient information that reminder is going to.
354 $sql = "SELECT `fname`, `lname`, `email`, `phone_home`, `hipaa_voice`, `hipaa_allowemail` from `patient_data` where `pid`=?";
355 $result = sqlQueryCdrEngine($sql, array($reminder['pid']));
356 $patientfname = $result['fname'];
357 $patientlname = $result['lname'];
358 $patientemail = $result['email'];
359 $patientphone = $result['phone_home'];
360 $hipaa_voice = $result['hipaa_voice'];
361 $hipaa_allowemail = $result['hipaa_allowemail'];
363 // Email to patient if Allow Email and set reminder sent flag.
364 if ($hipaa_allowemail == "YES") {
365 $mail = new MyMailer();
366 $sender_name = $GLOBALS['patient_reminder_sender_name'];
367 $email_address = $GLOBALS['patient_reminder_sender_email'];
368 $mail->FromName = $sender_name; // required
369 $mail->Sender = $email_address; // required
370 $mail->From = $email_address; // required
371 $mail->AddAddress($patientemail, $patientfname.", ".$patientlname); // required
372 $mail->AddReplyTo($email_address, $sender_name); // required
373 $category_title = generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'), $reminder['category']);
374 $item_title = generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'), $reminder['item']);
375 $mail->Body = "Dear ".$patientfname.", This is a message from your clinic to remind you of your ".$category_title.": ".$item_title;
376 $mail->Subject = "Clinic Reminder";
377 if ($mail->Send()) {
378 // deal with and keep track of this successful email
379 sqlStatementCdrEngine("UPDATE `patient_reminders` SET `email_status`='1', `date_sent`=NOW() WHERE id=?", array($reminder['id']));
380 $logging['number_success_emails']++;
381 } else {
382 // deal with and keep track of this unsuccesful email
383 $logging['number_failed_emails']++;
387 // Call to patient if Allow Voice Message and set reminder sent flag.
388 if ($hipaa_voice == "YES") {
389 /******************************************************************************
390 * // Maviq does not work, is not currently supported, and seems to break on windows servers, so this
391 * // feature has been commented out for now.
392 * // Automated VOIP service provided by Maviq. Please visit http://signup.maviq.com for more information.
393 * $siteId = $GLOBALS['phone_gateway_username'];
394 * $token = $GLOBALS['phone_gateway_password'];
395 * $endpoint = $GLOBALS['phone_gateway_url'];
396 * $client = new MaviqClient($siteId, $token, $endpoint);
397 * //Set up params.
398 * $data = array(
399 * "firstName" => $patientfname,
400 * "lastName" => $patientlname,
401 * "phone" => $patientphone,
402 * //"apptDate" => "$scheduled_date[1]/$scheduled_date[2]/$scheduled_date[0]",
403 * "timeRange" => "10-18",
404 * "type" => "reminder",
405 * "timeZone" => date('P'),
406 * "greeting" => str_replace("[[sender]]", $sender_name, str_replace("[[patient_name]]", $patientfname, $myrow['reminder_content']))
407 * );
409 * // Make the call.
410 * $response = $client->sendRequest("appointment", "POST", $data);
412 * if ($response->IsError) {
413 * // deal with and keep track of this unsuccessful call
414 * $logging['number_failed_calls']++;
416 * else {
417 * // deal with and keep track of this succesful call
418 * sqlStatementCdrEngine("UPDATE `patient_reminders` SET `voice_status`='1', `date_sent`=NOW() WHERE id=?", array($reminder['id']) );
419 * $logging['number_success_calls']++;
421 *******************************************************************************/
425 // For logging purposes only:
426 // Collect active reminders that have not yet been sent.
427 $logging['total_post_unsent_reminders'] = count(fetch_reminders('', 'unsent'));
429 return $logging;
433 * Function to fetch reminders.
435 * @param integer/array $patient_id pid(s) of patient(s).
436 * @param string $type Can choose unsent ('unsent') vs all active (BLANK) reminders
437 * @param string $due_status due status of reminders (soon_due,due,past_due). If blank, then will return all.
438 * @param string $select Select component of select statement. If blank, then will return all columns.
439 * @return array Returns an array of reminders.
441 function fetch_reminders($patient_id = '', $type = '', $due_status = '', $select = '*')
444 $arraySqlBind = array();
446 if (!empty($patient_id)) {
447 // check the specified pid(s)
448 $where = "`pid` IN (?) AND ";
449 array_push($arraySqlBind, $patient_id);
452 if (!empty($due_status)) {
453 $where .= "`due_status`=? AND ";
454 array_push($arraySqlBind, $due_status);
457 if (empty($type)) {
458 $where .= "`active`='1'";
459 } else { // $type == 'unsent'
460 $where .= "`active`='1' AND `date_sent` IS NULL";
463 $order = "`due_status`, `date_created`";
465 $sql = "SELECT " . $select . " FROM `patient_reminders` WHERE " .
466 $where . " ORDER BY " . $order;
467 $rez = sqlStatementCdrEngine($sql, $arraySqlBind);
469 $returnval=array();
470 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
471 $returnval[$iter]=$row;
474 return $returnval;