convert to new security model for chart_location_activity
[openemr.git] / library / reminders.php
blob559e1577b00a065cf4a81bb9bb44c9a50f1d1698
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@sparmy.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@sparmy.com>
27 * @link http://www.open-emr.org
30 /**
31 * Include the main CDR engine library
33 require_once(dirname(__FILE__) . "/clinical_rules.php");
35 // This is only pertinent for users of php versions less than 5.2
36 // (ie. this wrapper is only loaded when php version is less than
37 // 5.2; otherwise the native php json functions are used)
38 require_once(dirname(__FILE__) . "/jsonwrapper/jsonwrapper.php");
40 /**
41 * Display the patient reminder widget.
43 * @param integer $patient_id pid of selected patient
44 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
46 function patient_reminder_widget($patient_id,$dateTarget='') {
48 // Set date to current if not set
49 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
51 // Update reminders for patient
52 update_reminders($dateTarget, $patient_id);
54 // Fetch the active reminders
55 $listReminders = fetch_reminders($patient_id);
57 if (empty($listReminders)) {
58 // No reminders to show.
59 echo htmlspecialchars( xl('No active patient reminders.'), ENT_NOQUOTES);
60 return;
63 echo "<table cellpadding='0' cellspacing='0'>";
64 foreach ($listReminders as $reminder) {
65 echo "<tr><td style='padding:0 1em 0 1em;'><span class='small'>";
66 // show reminder label
67 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$reminder['category']) .
68 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$reminder['item']);
69 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
70 // show reminder due status
71 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$reminder['due_status']);
72 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
73 // show reminder sent date
74 if (empty($reminder['date_sent'])) {
75 echo htmlspecialchars( xl('Reminder Not Sent Yet'), ENT_NOQUOTES);
77 else {
78 echo htmlspecialchars( xl('Reminder Sent On').": ".$reminder['date_sent'], ENT_NOQUOTES);
80 echo "</span></td></tr>";
82 echo "</table>";
85 /**
86 * Function to update reminders via a batching method to improve performance and decrease memory overhead.
88 * Function that updates reminders and returns an array with a specific data structure.
89 * <pre>The data structure of the return array includes the following elements
90 * 'total_active_actions' - Number of active actions.
91 * 'total_pre_active_reminders' - Number of active reminders before processing.
92 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
93 * 'total_post_active_reminders' - Number of active reminders after processing.
94 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
95 * 'number_new_reminders' - Number of new reminders
96 * 'number_updated_reminders' - Number of updated reminders (due_status change)
97 * 'number_inactivated_reminders' - Number of inactivated reminders.
98 * 'number_unchanged_reminders' - Number of unchanged reminders.
99 * </pre>
101 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
102 * @param integer $batchSize number of patients to batch (default is 25; plan to optimize this default setting in the future)
103 * @param integer $report_id id of report in database (if already bookmarked)
104 * @param boolean $also_send if TRUE, then will also call send_reminder when done
105 * @return array see above for data structure of returned array
107 function update_reminders_batch_method($dateTarget='', $batchSize=25, $report_id=NULL, $also_send=FALSE) {
109 // Default to a batchsize, if empty
110 if (empty($batchSize)) {
111 $batchSize=25;
114 // Collect total number of pertinent patients (to calculate batching parameters)
115 $totalNumPatients = buildPatientArray('','','',NULL,NULL,TRUE);
117 // Cycle through the batches and collect/combine results
118 if (($totalNumPatients%$batchSize) > 0) {
119 $totalNumberBatches = floor($totalNumPatients/$batchSize) + 1;
121 else {
122 $totalNumberBatches = floor($totalNumPatients/$batchSize);
125 // Prepare the database to track/store results
126 if ($also_send) {
127 $report_id = beginReportDatabase("process_send_reminders",'',$report_id);
129 else {
130 $report_id = beginReportDatabase("process_reminders",'',$report_id);
132 setTotalItemsReportDatabase($report_id,$totalNumPatients);
134 $patient_counter=0;
135 for ($i=0;$i<$totalNumberBatches;$i++) {
136 $patient_counter = $batchSize*($i+1);
137 if ($patient_counter > $totalNumPatients) $patient_counter = $totalNumPatients;
138 $update_rem_log_batch = update_reminders($dateTarget,'',(($batchSize*$i)+1),$batchSize);
139 if ($i == 0) {
140 // For first cycle, simply copy it to update_rem_log
141 $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'];
159 //Update database to track results
160 updateReportDatabase($report_id,$patient_counter);
163 // Create an array for saving to database (allows combining with the send log)
164 $save_log = array();
165 $save_log[] = $update_rem_log;
167 // Send reminders, if this was selected
168 if ($also_send) {
169 $log_send = send_reminders();
170 $save_log[] = $log_send;
173 // Record combo results in database
174 finishReportDatabase($report_id,json_encode($save_log));
176 // Just return the process reminders array
177 return $update_rem_log;
181 * Function to update reminders.
183 * Function that updates reminders and returns an array with a specific data structure.
184 * <pre>The data structure of the return array includes the following elements
185 * 'total_active_actions' - Number of active actions.
186 * 'total_pre_active_reminders' - Number of active reminders before processing.
187 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
188 * 'total_post_active_reminders' - Number of active reminders after processing.
189 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
190 * 'number_new_reminders' - Number of new reminders
191 * 'number_updated_reminders' - Number of updated reminders (due_status change)
192 * 'number_inactivated_reminders' - Number of inactivated reminders.
193 * 'number_unchanged_reminders' - Number of unchanged reminders.
194 * </pre>
196 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
197 * @param integer $patient_id pid of patient. If blank then will check all patients.
198 * @param integer $start applicable patient to start at (when batching process)
199 * @param integer $batchSize number of patients to batch (when batching process)
200 * @return array see above for data structure of returned array
202 function update_reminders($dateTarget='', $patient_id='', $start=NULL, $batchSize=NULL) {
204 $logging = array();
206 // Set date to current if not set
207 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
209 // Collect reminders (note that this function removes redundant and keeps the most distant
210 // reminder (ie. prefers 'past_due' over 'due' over 'soon_due')
211 // Note that due to a limitation in the test_rules_clinic function, the patient_id is explicitly
212 // needed to work correctly. So rather than pass in a '' patient_id to do the entire clinic,
213 // we instead need to pass in each patient_id separately.
214 $collectedReminders = array();
215 $patient_id_complete = "";
216 if (!(empty($patient_id))) {
217 // only one patient id, so run the function
218 $collectedReminders = test_rules_clinic('','patient_reminder',$dateTarget,'reminders-due',$patient_id);
219 $patient_id_complete = $patient_id;
221 else {
222 // as described above, need to pass in each patient_id
223 // Collect all patient ids
224 $patientData = buildPatientArray('','','',$start,$batchSize);
225 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
226 $patientData[$iter]=$row;
228 $first_flag = TRUE;
229 foreach ($patientData as $patient) {
230 // collect reminders
231 $tempCollectReminders = test_rules_clinic('','patient_reminder',$dateTarget,'reminders-due',$patient['pid']);
232 $collectedReminders = array_merge($collectedReminders,$tempCollectReminders);
233 // build the $patient_id_complete variable
234 if ($first_flag) {
235 $patient_id_complete .= $patient['pid'];
236 $first_flag = FALSE;
238 else {
239 $patient_id_complete .= ",".$patient['pid'];
243 $logging['total_active_actions'] = count($collectedReminders);
245 // For logging purposes only:
246 // Collect number active of active and unsent reminders
247 $logging['total_pre_active_reminders'] = count(fetch_reminders($patient_id_complete));
248 $logging['total_pre_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
250 // Migrate reminders into the patient_reminders table
251 $logging['number_new_reminders'] = 0;
252 $logging['number_updated_reminders'] = 0;
253 $logging['number_unchanged_reminders'] = 0;
254 foreach ($collectedReminders as $reminder) {
256 // See if a reminder already exist
257 $sql = "SELECT `id`, `pid`, `due_status`, `category`, `item` FROM `patient_reminders` WHERE " .
258 "`active`='1' AND `pid`=? AND `category`=? AND `item`=?";
259 $result = sqlQueryCdrEngine($sql, array($reminder['pid'], $reminder['category'], $reminder['item']) );
261 if (empty($result)) {
262 // It does not yet exist, so add a new reminder
263 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
264 "VALUES (?, ?, ?, ?, NOW())";
265 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']) );
266 $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;
275 else {
276 // Change in due status, so inactivate current reminder and create a new one
277 // First, inactivate the previous reminder
278 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'due_status_update', " .
279 "`date_inactivated` = NOW() WHERE `id`=?";
280 sqlStatementCdrEngine($sql, array($result['id']) );
281 // Then, add the new reminder
282 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
283 "VALUES (?, ?, ?, ?, NOW())";
284 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']) );
289 // Inactivate reminders that no longer exist
290 // Go through each active reminder and ensure it is in the current list
291 $sqlReminders = fetch_reminders($patient_id_complete);
292 $logging['number_inactivated_reminders'] = 0;
293 foreach ( $sqlReminders as $row ) {
294 $inactivateFlag = true;
295 foreach ($collectedReminders as $reminder) {
296 if ( ($row['pid'] == $reminder['pid']) &&
297 ($row['category'] == $reminder['category']) &&
298 ($row['item'] == $reminder['item']) &&
299 ($row['due_status'] == $reminder['due_status']) ) {
300 // The sql reminder has been confirmed, so do not inactivate it
301 $inactivateFlag = false;
302 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() {
340 $logging = array();
342 // Collect active reminders that have not yet been sent.
343 $active_unsent_reminders = fetch_reminders('', 'unsent');
344 $logging['total_pre_unsent_reminders'] = count($active_unsent_reminders);
346 // Send the unsent reminders
347 $logging['number_success_emails'] = 0;
348 $logging['number_failed_emails'] = 0;
349 $logging['number_success_calls'] = 0;
350 $logging['number_failed_calls'] = 0;
351 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']++;
382 else {
383 // deal with and keep track of this unsuccesful email
384 $logging['number_failed_emails']++;
388 // Call to patient if Allow Voice Message and set reminder sent flag.
389 if ($hipaa_voice == "YES") {
390 // Automated VOIP service provided by Maviq. Please visit http://signup.maviq.com for more information.
391 $siteId = $GLOBALS['phone_gateway_username'];
392 $token = $GLOBALS['phone_gateway_password'];
393 $endpoint = $GLOBALS['phone_gateway_url'];
394 $client = new MaviqClient($siteId, $token, $endpoint);
395 //Set up params.
396 $data = array(
397 "firstName" => $patientfname,
398 "lastName" => $patientlname,
399 "phone" => $patientphone,
400 //"apptDate" => "$scheduled_date[1]/$scheduled_date[2]/$scheduled_date[0]",
401 "timeRange" => "10-18",
402 "type" => "reminder",
403 "timeZone" => date('P'),
404 "greeting" => str_replace("[[sender]]", $sender_name, str_replace("[[patient_name]]", $patientfname, $myrow['reminder_content']))
407 // Make the call.
408 $response = $client->sendRequest("appointment", "POST", $data);
410 if ($response->IsError) {
411 // deal with and keep track of this unsuccessful call
412 $logging['number_failed_calls']++;
414 else {
415 // deal with and keep track of this succesful call
416 sqlStatementCdrEngine("UPDATE `patient_reminders` SET `voice_status`='1', `date_sent`=NOW() WHERE id=?", array($reminder['id']) );
417 $logging['number_success_calls']++;
422 // For logging purposes only:
423 // Collect active reminders that have not yet been sent.
424 $logging['total_post_unsent_reminders'] = count(fetch_reminders('', 'unsent'));
426 return $logging;
430 * Function to fetch reminders.
432 * @param integer/array $patient_id pid(s) of patient(s).
433 * @param string $type Can choose unsent ('unsent') vs all active (BLANK) reminders
434 * @param string $due_status due status of reminders (soon_due,due,past_due). If blank, then will return all.
435 * @param string $select Select component of select statement. If blank, then will return all columns.
436 * @return array Returns an array of reminders.
438 function fetch_reminders($patient_id='',$type='',$due_status='',$select='*') {
440 $arraySqlBind = array();
442 if (!empty($patient_id)) {
443 // check the specified pid(s)
444 $where = "`pid` IN (".add_escape_custom($patient_id).") AND ";
447 if (!empty($due_status)) {
448 $where .= "`due_status`=? AND ";
449 array_push($arraySqlBind,$due_status);
452 if (empty($type)) {
453 $where .= "`active`='1'";
455 else { // $type == 'unsent'
456 $where .= "`active`='1' AND `date_sent` IS NULL";
459 $order = "`due_status`, `date_created`";
461 $sql = "SELECT " . $select . " FROM `patient_reminders` WHERE " .
462 $where . " ORDER BY " . $order;
463 $rez = sqlStatementCdrEngine($sql, $arraySqlBind);
465 $returnval=array();
466 for($iter=0; $row=sqlFetchArray($rez); $iter++)
467 $returnval[$iter]=$row;
469 return $returnval;