Dated reminders bug fix to use correct patient pid in log array
[openemr.git] / library / dated_reminder_functions.php
blob1d2fdc57b33a528d639b6f6e90ac33f95f66420c
1 <?php
2 // ------------------------------------------------------------------------ //
3 // OpenEMR Electronic Medical Records System //
4 // Copyright (c) 2012 tajemo.co.za //
5 // <http://www.tajemo.co.za/> //
6 // ------------------------------------------------------------------------ //
7 // This program is free software; you can redistribute it and/or modify //
8 // it under the terms of the GNU General Public License as published by //
9 // the Free Software Foundation; either version 2 of the License, or //
10 // (at your option) any later version. //
11 // //
12 // You may not change or alter any portion of this comment or credits //
13 // of supporting developers from this source code or any supporting //
14 // source code which is considered copyrighted (c) material of the //
15 // original comment or credit authors. //
16 // //
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 // //
22 // You should have received a copy of the GNU General Public License //
23 // along with this program; if not, write to the Free Software //
24 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
25 // --------------------------------------------------------------------------//
26 // Original Author of this file: Craig Bezuidenhout (Tajemo Enterprises) //
27 // Purpose of this file: Contains functions used in the dated reminders //
28 // --------------------------------------------------------------------------//
29 require_once("$srcdir/htmlspecialchars.inc.php");
31 // ------------------------------------------------
32 // @ RemindersArray function
33 // @ returns array with reminders for specified user, defaults to current user if none specified
34 // ------------------------------------------------
35 function RemindersArray($days_to_show,$today,$alerts_to_show,$userID = false){
36 if(!$userID) $userID = $_SESSION['authId'];
37 global $hasAlerts;
38 // ----- define a blank reminders array
39 $reminders = array();
41 // ----- sql statement for getting uncompleted reminders (sorts by date, then by priority)
42 $drSQL = sqlStatement(
43 "SELECT
44 dr.pid, dr.dr_id, dr.dr_message_text,dr.dr_message_due_date,
45 u.fname ffname, u.mname fmname, u.lname flname
46 FROM `dated_reminders` dr
47 JOIN `users` u ON dr.dr_from_ID = u.id
48 JOIN `dated_reminders_link` drl ON dr.dr_id = drl.dr_id
49 WHERE drl.to_id = ?
50 AND dr.`message_processed` = 0
51 AND dr.`dr_message_due_date` < ADDDATE(NOW(), INTERVAL $days_to_show DAY)
52 ORDER BY `dr_message_due_date` ASC , `message_priority` ASC LIMIT 0,$alerts_to_show"
53 , array($userID)
54 );
56 // --------- loop through the results
57 for($i=0; $drRow=sqlFetchArray($drSQL); $i++){
58 // --------- need to run patient query seperately to allow for reminders not linked to a patient
59 $pRow = array();
60 if($drRow['pid'] > 0){
61 $pSQL = sqlStatement("SELECT pd.title ptitle, pd.fname pfname, pd.mname pmname, pd.lname plname FROM `patient_data` pd WHERE pd.pid = ?",array($drRow['pid']));
62 $pRow = sqlFetchArray($pSQL);
65 // --------- fill the $reminders array
66 $reminders[$i]['messageID'] = $drRow['dr_id'];
67 $reminders[$i]['PatientID'] = $drRow['pid'];
69 // ------------------------------------- if there was a patient linked, set the name, else set it to blank
70 $reminders[$i]['PatientName'] = (empty($pRow) ? '' : $pRow['ptitle'].' '.$pRow['pfname'].' '.$pRow['pmname'].' '.$pRow['plname']);
71 // -------------------------------------
73 $reminders[$i]['message'] = $drRow['dr_message_text'];
74 $reminders[$i]['dueDate'] = $drRow['dr_message_due_date'];
75 $reminders[$i]['fromName'] = $drRow['ffname'].' '.$drRow['fmname'].' '.$drRow['flname'];
77 // --------- if the message is due or overdue set $hasAlerts to true, this will stop autohiding of reminders
78 if(strtotime($drRow['dr_message_due_date']) <= $today) $hasAlerts = true;
80 // --------- END OF loop through the results
82 return $reminders;
84 // ------------------------------------------------
85 // @ END OF RemindersArray function
86 // ------------------------------------------------
91 // ------------------------------------------------
92 // @ GetDueReminder function
93 // @ returns int with number of due reminders for specified user, defaults to current user if none specified
94 // ------------------------------------------------
95 function GetDueReminderCount($days_to_show,$today,$userID = false){
96 if(!$userID) $userID = $_SESSION['authId'];
98 // ----- sql statement for getting uncompleted reminders (sorts by date, then by priority)
99 $drSQL = sqlStatement(
100 "SELECT count(dr.dr_id) c
101 FROM `dated_reminders` dr
102 JOIN `users` u ON dr.dr_from_ID = u.id
103 JOIN `dated_reminders_link` drl ON dr.dr_id = drl.dr_id
104 WHERE drl.to_id = ?
105 AND dr.`message_processed` = 0
106 AND dr.`dr_message_due_date` < ADDDATE(NOW(), INTERVAL $days_to_show DAY)"
107 , array($userID)
110 $drRow=sqlFetchArray($drSQL);
111 return $drRow['c'];
113 // ------------------------------------------------
114 // @ END OF GetDueReminder function
115 // ------------------------------------------------
117 // ------------------------------------------------
118 // @ GetAllReminderCount function
119 // @ returns int with number of unprocessed reminders for specified user, defaults to current user if none specified
120 // ------------------------------------------------
121 function GetAllReminderCount($userID = false){
122 if(!$userID) $userID = $_SESSION['authId'];
124 // ----- sql statement for getting uncompleted reminders
125 $drSQL = sqlStatement(
126 "SELECT count(dr.dr_id) c
127 FROM `dated_reminders` dr
128 JOIN `users` u ON dr.dr_from_ID = u.id
129 JOIN `dated_reminders_link` drl ON dr.dr_id = drl.dr_id
130 WHERE drl.to_id = ?
131 AND dr.`message_processed` = 0"
132 , array($userID)
135 $drRow=sqlFetchArray($drSQL);
136 return $drRow['c'];
138 // ------------------------------------------------
139 // @ END OF GetAllReminderCount function
140 // ------------------------------------------------
142 // ------------------------------------------------
143 // @ getRemindersHTML(array $reminders)
144 // @ returns HTML as a string, for printing
145 // ------------------------------------------------
146 function getRemindersHTML($reminders = array(),$today){
147 global $hasAlerts;
148 // --- initialize the string as blank
149 $pdHTML = '';
150 // --- loop through the $reminders
151 foreach($reminders as $r){
152 // --- initialize $warning as the date, this is placed in front of the message
153 $warning = text($r['dueDate']);
154 // --- initialize $class as 'text dr', this is the basic class
155 $class='text dr';
157 // --------- check if reminder is overdue
158 if(strtotime($r['dueDate']) < $today){
159 $warning = '! '.xlt('OVERDUE');
160 $class = 'bold alert dr';
162 // --------- check if reminder is due
163 elseif(strtotime($r['dueDate']) == $today){
164 $warning = xlt('TODAY');
165 $class='bold alert dr';
167 // end check if reminder is due or overdue
168 // apend to html string
169 $pdHTML .= '<p id="p_'.attr($r['messageID']).'">
170 <a class="dnRemover css_button_small" onclick="updateme('."'".attr($r['messageID'])."'".')" id="'.attr($r['messageID']).'" href="#">
171 <span>'.xlt('Set As Completed').'</span>
172 </a>
173 <span title="'.($r['PatientID'] > 0 ? xla('Click Patient Name to Open Patient File') : '').'" class="'.attr($class).'">'.
174 $warning.'
175 <span onclick="goPid('.attr($r['PatientID']).')" class="patLink" id="'.attr($r['PatientID']).'">'.
176 text($r['PatientName']).'
177 </span> '.
178 text($r['message']).' - ['.text($r['fromName']).']
179 </span> ----->
180 <a onclick="openAddScreen('.attr($r['messageID']).')" class="dnForwarder" id="'.attr($r['messageID']).'" href="#">[ '.xlt('Forward').' ]</a>
181 </p>';
183 return ($pdHTML == '' ? '<p class="alert"><br />'.xlt('No Reminders').'</p>' : $pdHTML);
185 // ------------------------------------------------
186 // @ END OF getRemindersHTML function
187 // ------------------------------------------------
190 // ------------------------------------------------
191 // @ setReminderAsProccessed(int $rID)
192 // @ marks reminder as processed
193 // ------------------------------------------------
194 function setReminderAsProcessed($rID,$userID = false){
195 if(!$userID) $userID = $_SESSION['authId'];
196 if(is_numeric($rID) and $rID > 0){
197 // --- check if this user can remove this message
198 // --- need a better way of checking the current user, I don't like using $_SESSION for checks
199 $rdrSQL = sqlStatement("SELECT count(dr.dr_id) c FROM `dated_reminders` dr JOIN `dated_reminders_link` drl ON dr.dr_id = drl.dr_id WHERE drl.to_id = ? AND dr.`dr_id` = ? LIMIT 0,1", array($userID,$rID));
200 $rdrRow=sqlFetchArray($rdrSQL);
202 // --- if this user can delete this message (ie if it was sent to this user)
203 if($rdrRow['c'] == 1){
204 // ----- update the data, set the message to proccesses
205 sqlStatement("UPDATE `dated_reminders` SET `message_processed` = 1, `processed_date` = NOW(), `dr_processed_by` = ? WHERE `dr_id` = ? ", array(intval($userID),intval($rID)));
209 // ------------------------------------------------
210 // @ END OF setReminderAsProccessed function
211 // ------------------------------------------------
214 // ------------------------------------------------
215 // @ getReminderById(int $mID)
216 // @ returns an array with message details for forwarding
217 // ------------------------------------------------
218 function getReminderById($mID,$userID = false){
219 if(!$userID) $userID = $_SESSION['authId'];
220 $rdrSQL = sqlStatement("SELECT * FROM `dated_reminders` dr
221 JOIN `dated_reminders_link` drl ON dr.dr_id = drl.dr_id
222 WHERE drl.to_id = ? AND dr.`dr_id` = ? LIMIT 0,1", array($userID,$mID));
223 $rdrRow=sqlFetchArray($rdrSQL);
224 if(!empty($rdrRow)){
225 return $rdrRow;
227 return false;
229 // ------------------------------------------------
230 // @ END OF getReminderById function
231 // ------------------------------------------------
234 // ------------------------------------------------
235 // @ getReminderById(
236 // array $sendTo
237 // int $fromID
238 // string $message
239 // date $dueDate
240 // int $patID
241 // int $priority
242 // )
243 // @ returns an array with message details for forwarding
244 // ------------------------------------------------
245 function sendReminder($sendTo,$fromID,$message,$dueDate,$patID,$priority){
246 if(
247 // ------- Should run data checks before running this function for more accurate error reporting
248 // ------- check sendTo is not empty
249 !empty($sendTo) and
250 // ------- check dueDate, only allow valid dates, todo -> enhance date checker
251 preg_match('/\d{4}[-]\d{2}[-]\d{2}/',$dueDate) and
252 // ------- check priority, only allow 1-3
253 intval($priority) <= 3 and
254 // ------- check message, only up to 255 characters
255 strlen($message) <= 255 and strlen($message) > 0 and
256 // ------- check if PatientID is set and in numeric
257 is_numeric($patID)
259 // ------- check for valid recipient
260 $cRow=sqlFetchArray(sqlStatement('SELECT count(id) FROM `users` WHERE `id` = ?',array($sendDMTo)));
261 if($cRow == 0){
262 return false;
264 // ------- if no errors
265 // --------- insert the new message
266 $mID = sqlInsert("INSERT INTO `dated_reminders`
267 (`dr_from_ID` ,`dr_message_text` ,`dr_message_sent_date` ,`dr_message_due_date` ,`pid` ,`message_priority` ,`message_processed` ,`processed_date`)
268 VALUES (?, ?, NOW( ), ?, ?, ?, '0', '');",
269 array($fromID,$message,$dueDate,$patID,$priority));
271 foreach($sendTo as $st){
272 sqlInsert("INSERT INTO `dated_reminders_link`
273 (`dr_id` ,`to_id`)
274 VALUES (?, ?);",
275 array($mID,$st));
277 return true;
278 } //---- end of if block
279 return false;
282 // ------- get current patient name
283 // ---- returns string, blank if no current patient
284 function getPatName($patientID){
285 $patientID = intval($patientID);
286 $pSQL = sqlStatement("SELECT pd.title ptitle, pd.fname pfname, pd.mname pmname, pd.lname plname FROM `patient_data` pd WHERE pd.pid = ?",array($patientID));
287 $pRow = sqlFetchArray($pSQL);
288 return (empty($pRow) ? '' : $pRow['ptitle'].' '.$pRow['pfname'].' '.$pRow['pmname'].' '.$pRow['plname']);
291 // -- log reminders array function uses $_GET to filter
292 function logRemindersArray(){
294 // set blank array for data to be parsed to sql
295 $input = array();
296 // set blank string for the query
297 $where = '';
298 $sentBy = $_GET['sentBy'];
299 $sentTo = $_GET['sentTo'];
300 //------------------------------------------
301 // ----- HANDLE SENT BY FILTER
302 if(!empty($sentBy)){
303 $sbCount = 0;
304 foreach($sentBy as $sb){
305 $where .= ($sbCount == 0 ? '(' : ' OR ').'dr.dr_from_ID = ? ';
306 $sbCount++;
307 $input[] = $sb;
309 $where .= ')';
311 //------------------------------------------
312 // ----- HANDLE SENT TO FILTER
313 if(!empty($sentTo)){
314 $where = ($where == '' ? '' : $where.' AND ');
315 $stCount = 0;
316 foreach($sentTo as $st){
317 $where .= ($stCount == 0 ? '(' : ' OR ').'drl.to_id = ? ';
318 $stCount++;
319 $input[] = $st;
321 $where .= ')';
323 //------------------------------------------
324 // ----- HANDLE PROCCESSED/PENDING FILTER ONLY RUN THIS IF BOTH ARE NOT SET
325 if(isset($_GET['processed']) and !isset($_GET['pending'])){
326 $where = ($where == '' ? 'dr.message_processed = 1' : $where.' AND dr.message_processed = 1');
328 elseif(!isset($_GET['processed']) and isset($_GET['pending'])){
329 $where = ($where == '' ? 'dr.message_processed = 0' : $where.' AND dr.message_processed = 0');
331 //------------------------------------------
332 // ----- HANDLE DATE RANGE FILTERS
333 if(isset($_GET['sd']) and $_GET['sd'] != ''){
334 $where = ($where == '' ? 'dr.dr_message_sent_date >= ?' : $where.' AND dr.dr_message_sent_date >= ?');
335 $input[] = $_GET['sd'].' 00:00:00';
337 if(isset($_GET['ed']) and $_GET['ed'] != ''){
338 $where = ($where == '' ? 'dr.dr_message_sent_date <= ?' : $where.' AND dr.dr_message_sent_date <= ?');
339 $input[] = $_GET['ed'].' 24:00:00';
341 //------------------------------------------
344 //-------- add the "WHERE" the string if string is not blank, avoid sql errors for blannk WHERE statements
345 $where = ($where == '' ? '' : 'WHERE '.$where);
347 // ----- define a blank reminders array
348 $reminders = array();
350 // ----- sql statement for getting uncompleted reminders (sorts by date, then by priority)
351 $drSQL = sqlStatement(
352 "SELECT
353 dr.pid, dr.dr_id, dr.dr_message_text, dr.dr_message_due_date dDate, dr.dr_message_sent_date sDate,dr.processed_date processedDate, dr.dr_processed_by,
354 u.fname ffname, u.mname fmname, u.lname flname,
355 tu.fname tfname, tu.mname tmname, tu.lname tlname
356 FROM `dated_reminders` dr
357 JOIN `dated_reminders_link` drl ON dr.dr_id = drl.dr_id
358 JOIN `users` u ON dr.dr_from_ID = u.id
359 JOIN `users` tu ON drl.to_id = tu.id
360 $where"
361 ,$input);
362 // --------- loop through the results
363 for($i=0; $drRow=sqlFetchArray($drSQL); $i++){
364 // --------- need to run patient query seperately to allow for messages not linked to a patient
365 $pSQL = sqlStatement("SELECT pd.title ptitle, pd.fname pfname, pd.mname pmname, pd.lname plname FROM `patient_data` pd WHERE pd.pid = ?",array($drRow['pid']));
366 $pRow = sqlFetchArray($pSQL);
368 $prSQL = sqlStatement("SELECT u.fname pfname, u.mname pmname, u.lname plname FROM `users` u WHERE u.id = ?",array($drRow['dr_processed_by']));
369 $prRow = sqlFetchArray($prSQL );
371 // --------- fill the $reminders array
372 $reminders[$i]['messageID'] = $drRow['dr_id'];
373 $reminders[$i]['PatientID'] = $drRow['pid'];
375 $reminders[$i]['pDate'] = ($drRow['processedDate'] == '0000-00-00 00:00:00' ? 'N/A' : $drRow['processedDate']);
376 $reminders[$i]['sDate'] = $drRow['sDate'];
377 $reminders[$i]['dDate'] = $drRow['dDate'];
379 // ------------------------------------- if there was a patient linked, set the name, else set it to blank
380 $reminders[$i]['PatientName'] = (empty($pRow) ? 'N/A' : $pRow['ptitle'].' '.$pRow['pfname'].' '.$pRow['pmname'].' '.$pRow['plname']);
381 // -------------------------------------
383 $reminders[$i]['message'] = $drRow['dr_message_text'];
384 $reminders[$i]['fromName'] = $drRow['ffname'].' '.$drRow['fmname'].' '.$drRow['flname'];
385 $reminders[$i]['ToName'] = $drRow['tfname'].' '.$drRow['tmname'].' '.$drRow['tlname'];
386 $reminders[$i]['processedByName'] = (empty($prRow) ? 'N/A' : $prRow['ptitle'].' '.$prRow['pfname'].' '.$prRow['pmname'].' '.$prRow['plname']);
388 // --------- END OF loop through the results
390 return $reminders;