Space to separate "&&" so that all "&$var" can be made into "$var" later
[openemr.git] / library / pnotes.inc
blob303f5ac02648ffea998d7aad98436ad5a2ed81b1
1 <?php
2 /**
3  * This file contains functions for handling notes attached to patient files. 
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * 2013-02-08 EMR Direct: changes to allow notes added by background-services with pid=0
11  */
13 /* for sqlQuery(), sqlStatement(), sqlNumRows(), sqlFetchArray(). */
14 require_once($GLOBALS['srcdir'].'/sql.inc');
16 /**
17  * Retrieve a note, given its ID
18  *
19  * @param string $id the ID of the note to retrieve.
20  * @param string $cols A list of columns to retrieve. defaults to '*' for all.
21  */
22 function getPnoteById($id, $cols = "*")
24   return sqlQuery("SELECT $cols FROM pnotes WHERE id=? " .
25     ' AND deleted != 1 '. // exclude ALL deleted notes
26     'order by date DESC limit 0,1', array($id) );
29 /**
30  * Get the patient notes for the given user.
31  *
32  * This function is used to retrieve notes assigned to the given user, or
33  * optionally notes assigned to any user.
34  *
35  * @param string $activity 0 for deleted notes, 1 (the default) for active
36  *                         notes, or 'All' for all.
37  * @param string $show_all whether to display only the selected user's 
38  *                         messages, or all users' messages.
39  * @param string $user The user whom's notes you want to retrieve.
40  * @param bool $count Whether to return a count, or just return 0.
41  * @param string $sortby A field to sort results by. (options are users.lname,patient_data.lname,pnotes.title,pnotes.date,pnotes.message_status) (will default to users.lname)
42  * @param string $sortorder whether to sort ascending or descending.
43  * @param string $begin what row to start retrieving results from.
44  * @param string $listnumber number of rows to return.
45  * @return int The number of rows retrieved, or 0 if $count was true.
46  */
47 function getPnotesByUser($activity="1",$show_all="no",$user='',$count=false,$sortby='',$sortorder='',$begin='',$listnumber='')
50   // Set the activity part of query
51   if ($activity=='1') {
52     $activity_query = " pnotes.message_status != 'Done' AND pnotes.activity = 1 AND ";
53   }
54   else if ($activity=='0') {
55     $activity_query = " (pnotes.message_status = 'Done' OR pnotes.activity = 0) AND ";
56   }
57   else { //$activity=='all'
58     $activity_query = " ";
59   }
61   // Set whether to show chosen user or all users
62   if ($show_all == 'yes' ) {
63     $usrvar='_%';
64   } else {
65     $usrvar=$user;
66   } 
68   // run the query 
69   // 2013-02-08 EMR Direct: minor changes to query so notes with pid=0 don't disappear
70   $sql = "SELECT pnotes.id, pnotes.user, pnotes.pid, pnotes.title, pnotes.date, pnotes.message_status,
71           IF(pnotes.pid = 0 OR pnotes.user != pnotes.pid,users.fname,patient_data.fname) as users_fname,
72           IF(pnotes.pid = 0 OR pnotes.user != pnotes.pid,users.lname,patient_data.lname) as users_lname,
73           patient_data.fname as patient_data_fname, patient_data.lname as patient_data_lname
74           FROM ((pnotes LEFT JOIN users ON pnotes.user = users.username)
75           LEFT JOIN patient_data ON pnotes.pid = patient_data.pid) WHERE $activity_query
76           pnotes.deleted != '1' AND pnotes.assigned_to LIKE ?";
77   if (!empty($sortby) || !empty($sortorder)  || !empty($begin) || !empty($listnumber)) {
78     $sql .= " order by ".escape_sql_column_name($sortby,array('users','patient_data','pnotes'),TRUE).
79             " ".escape_sort_order($sortorder).
80             " limit ".escape_limit($begin).", ".escape_limit($listnumber);
81   }
82   $result = sqlStatement($sql, array($usrvar));
84   // return the results
85   if ($count) {
86     if(sqlNumRows($result) != 0) {
87         $total = sqlNumRows($result);
88     }
89     else {
90         $total = 0;
91     }
92     return $total;
93   }
94   else {
95     return $result;
96   }
99 function getPnotesByDate($date, $activity = "1", $cols = "*", $pid = "%",
100   $limit = "all", $start = 0, $username = '', $docid = 0, $status = "", $orderid = 0)
102 $sqlParameterArray = array();
103   if ($docid) {
104     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
105     "WHERE p.date LIKE ? AND r.type1 = 1 AND " .
106     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid != p.user";
107     array_push($sqlParameterArray, '%'.$date.'%', $docid);
108   }
109   else if ($orderid) {
110     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
111     "WHERE p.date LIKE ? AND r.type1 = 2 AND " .
112     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid != p.user";
113     array_push($sqlParameterArray, '%'.$date.'%', $orderid);
114   }
115   else {
116     $sql = "SELECT $cols FROM pnotes AS p " .
117       "WHERE date LIKE ? AND pid LIKE ? AND p.pid != p.user";
118     array_push($sqlParameterArray, '%'.$date.'%', $pid);
119   }
120   $sql .= " AND deleted != 1"; // exclude ALL deleted notes
121   if ($activity != "all") {
122     if ($activity == '0') {
123       // only return inactive
124       $sql .= " AND (activity = '0' OR message_status = 'Done') ";
125     }
126     else { // $activity == '1'
127       // only return active
128       $sql .= " AND activity = '1' AND message_status != 'Done' ";
129     }
130   }
131   if ($username) {
132     $sql .= " AND assigned_to LIKE ?";
133     array_push($sqlParameterArray, $username);
134   }
135   if ($status)
136     $sql .= " AND message_status IN ('".str_replace(",", "','", add_escape_custom($status) )."')";
137   $sql .= " ORDER BY date DESC";
138   if($limit != "all")
139     $sql .= " LIMIT ".escape_limit($start).", ".escape_limit($limit);
141   $res = sqlStatement($sql, $sqlParameterArray);
143   $all=array();
144   for ($iter = 0;$row = sqlFetchArray($res);$iter++)
145     $all[$iter] = $row;
146   return $all;
149 // activity can only be 0, 1, or 'all'
150 function getSentPnotesByDate($date, $activity = "1", $cols = "*", $pid = "%",
151   $limit = "all", $start = 0, $username = '', $docid = 0, $status = "", $orderid = 0)
153 $sqlParameterArray = array();
154   if ($docid) {
155     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
156     "WHERE p.date LIKE ? AND r.type1 = 1 AND " .
157     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user";
158     array_push($sqlParameterArray, '%'.$date.'%', $docid);
159   }
160   else if ($orderid) {
161     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
162     "WHERE p.date LIKE ? AND r.type1 = 2 AND " .
163     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user";
164     array_push($sqlParameterArray, '%'.$date.'%', $orderid);
165   }
166   else {
167     $sql = "SELECT $cols FROM pnotes AS p " .
168       "WHERE date LIKE ? AND pid LIKE ? AND p.pid = p.user";
169     array_push($sqlParameterArray, '%'.$date.'%', $pid);
170   }
171   $sql .= " AND deleted != 1"; // exclude ALL deleted notes
172   if ($activity != "all") {
173     if ($activity == '0') {
174       // only return inactive
175       $sql .= " AND (activity = '0' OR message_status = 'Done') ";
176     }
177     else { // $activity == '1'
178       // only return active
179       $sql .= " AND activity = '1' AND message_status != 'Done' ";
180     }
181   }
182   if ($username) {
183     $sql .= " AND assigned_to LIKE ?";
184     array_push($sqlParameterArray, $username);
185   }
186   if ($status)
187     $sql .= " AND message_status IN ('".str_replace(",", "','", add_escape_custom($status) )."')";
188   $sql .= " ORDER BY date DESC";
189   if($limit != "all")
190     $sql .= " LIMIT ".escape_limit($start).", ".escape_limit($limit);
192   $res = sqlStatement($sql, $sqlParameterArray);
194   $all=array();
195   for ($iter = 0;$row = sqlFetchArray($res);$iter++)
196     $all[$iter] = $row;
197   return $all;
200 function getPatientNotes($pid = '', $limit = '', $offset = 0, $search = '')
202   if($limit){
203     $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
204   }
205   $sql = "
206     SELECT
207       p.id,
208       p.date,
209       p.user,
210       p.title,
211       REPLACE(
212         p.body,
213         '-patient-',
214         CONCAT(pd.fname, ' ', pd.lname)
215       ) AS body,
216       p.message_status,
217       'Message' as `type`
218     FROM
219       pnotes AS p 
220       LEFT JOIN patient_data AS pd 
221         ON pd.id = p.pid 
222     WHERE assigned_to = '-patient-' 
223       AND p.deleted != 1 
224       AND p.pid = ?
225       $search
226     ORDER BY `date` desc
227     $limit
228   ";
229   $res = sqlStatement($sql, array($pid));
230   for($iter = 0;$row = sqlFetchArray($res);$iter++){
231     $all[$iter] = $row;
232   }
233   return $all;
236 function getPatientNotifications($pid = '', $limit = '', $offset = 0, $search = '')
238   if($limit){
239     $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
240   }
241   $sql = "
242     SELECT
243       pr.id,
244       date_created AS `date`,
245       'Patient Reminders' AS `user`,
246       due_status AS title,
247       CONCAT(lo.title, ':', lo2.title) AS body,
248       '' as message_status,
249       'Notification' as `type`
250     FROM
251       patient_reminders AS pr 
252       LEFT JOIN list_options AS lo 
253         ON lo.option_id = pr.category 
254         AND lo.list_id = 'rule_action_category' 
255       LEFT JOIN list_options AS lo2 
256         ON lo2.option_id = pr.item 
257         AND lo2.list_id = 'rule_action' 
258     WHERE pid = ?
259       AND active = 1
260       AND date_created > DATE_SUB(NOW(), INTERVAL 1 MONTH)
261       $search
262     ORDER BY `date` desc
263     $limit
264   ";
265   $res = sqlStatement($sql, array($pid));
266   for($iter = 0;$row = sqlFetchArray($res);$iter++){
267     $all[$iter] = $row;
268   }
269   return $all;
272 function getPatientSentNotes($pid = '', $limit = '', $offset = 0, $search = '')
274   if($limit){
275     $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
276   }
277   $sql = "
278     SELECT
279       p.id,
280       p.date,
281       p.assigned_to,
282       p.title,
283       REPLACE(
284         p.body,
285         '-patient-',
286         CONCAT(pd.lname, ' ', pd.fname)
287       ) AS body,
288       p.activity,
289       p.message_status,
290       'Message' as `type`
291     FROM
292       pnotes AS p 
293       LEFT JOIN patient_data AS pd 
294         ON pd.id = p.pid 
295     WHERE `user` = ?
296       AND p.deleted != 1 
297       AND p.pid = ?
298       AND p.message_status != 'Done'
299       $search
300     ORDER BY `date` desc
301     $limit
302   ";
303   $res = sqlStatement($sql, array($pid,$pid));
304   for($iter = 0;$row = sqlFetchArray($res);$iter++){
305     $all[$iter] = $row;
306   }
307   return $all;
310 // activity can be 0, 1, or 'all'
311 function getPnotesByPid ($pid, $activity = "1", $cols = "*", $limit=10, $start=0)
313  if ($activity == '1') {
314   // return only active
315   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
316     "AND activity = '1' ".
317     " AND message_status != 'Done' ".
318     " AND deleted != 1 ".
319     " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid) );
321  else if ($activity == '0') {
322   // return only inactive
323   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
324     "AND (activity = '0' ".
325     " OR message_status = 'Done') ".
326     " AND deleted != 1 ".
327     " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid) );
329  else { // $activity == "all"
330   // return both active and inactive
331   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
332     " AND deleted != 1 ".
333     " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid) );
335   for ($iter = 0; $row = sqlFetchArray($res); $iter++)
336     $all[$iter] = $row;
337   return $all;
340 /** Add a note to a patient's medical record.
342  * @param int $pid the ID of the patient whos medical record this note is going to be attached to.
343  * @param string $newtext the note contents.
344  * @param int $authorized
345  * @param int $activity
346  * @param string $title
347  * @param string $assigned_to
348  * @param string $datetime
349  * @param string $message_status
350  * @param string $background_user if set then the pnote is created by a background-service rather than a user
351  * @return int the ID of the added note.
352  */
353 function addPnote($pid, $newtext, $authorized = '0', $activity = '1',
354   $title= 'Unassigned', $assigned_to = '', $datetime = '',
355   $message_status = 'New', $background_user="")
357   if (empty($datetime)) $datetime = date('Y-m-d H:i:s');
359   // make inactive if set as Done
360   if ($message_status == 'Done') $activity = 0;
362   $user = ($background_user!="" ? $background_user : $_SESSION['authUser']);
363   $body = date('Y-m-d H:i') . ' (' . $user;
364   if ($assigned_to) $body .= " to $assigned_to";
365   $body = $body . ') ' . $newtext;
367   return sqlInsert('INSERT INTO pnotes (date, body, pid, user, groupname, ' .
368     'authorized, activity, title, assigned_to, message_status) VALUES ' .
369     '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
370     array($datetime, $body, $pid, $user, $_SESSION['authProvider'], $authorized, $activity, $title, $assigned_to, $message_status) );
373 function addMailboxPnote($pid, $newtext, $authorized = '0', $activity = '1',
374   $title='Unassigned', $assigned_to = '', $datetime = '', $message_status = "New")
376   if (empty($datetime)) $datetime = date('Y-m-d H:i:s');
378   // make inactive if set as Done
379   if ($message_status == "Done") $activity = 0;
381   $body = date('Y-m-d H:i') . ' (' . $pid;
382   if ($assigned_to) $body .= " to $assigned_to";
383   $body = $body . ') ' . $newtext;
385   return sqlInsert("INSERT INTO pnotes (date, body, pid, user, groupname, " .
386     "authorized, activity, title, assigned_to, message_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
387     array($datetime, $body, $pid, $pid, 'Default', $authorized, $activity, $title, $assigned_to, $message_status) );
390 function updatePnote($id, $newtext, $title, $assigned_to, $message_status = "")
392   $row = getPnoteById($id);
393   if (! $row) die("updatePnote() did not find id '".text($id)."'");
394   $activity = $assigned_to ? '1' : '0';
396   // make inactive if set as Done
397   if ($message_status == "Done") $activity = 0;
399   $body = $row['body'] . "\n" . date('Y-m-d H:i') .
400     ' (' . $_SESSION['authUser'];
401   if ($assigned_to) $body .= " to $assigned_to";
402   $body = $body . ') ' . $newtext;
404   if ($message_status) {
405     sqlStatement("UPDATE pnotes SET " .
406       "body = ?, activity = ?, title= ?, " .
407       "assigned_to = ?, message_status = ? WHERE id = ?",
408       array($body, $activity, $title, $assigned_to, $message_status, $id) );
409   }
410   else {
411     sqlStatement("UPDATE pnotes SET " .
412       "body = ?, activity = ?, title= ?, " .
413       "assigned_to = ? WHERE id = ?",
414       array($body, $activity, $title, $assigned_to, $id) );
415   }
418 function updatePnoteMessageStatus($id, $message_status)
420   if ($message_status == "Done") {
421     sqlStatement("update pnotes set message_status = ?, activity = '0' where id = ?", array($message_status, $id) );
422   }
423   else {
424     sqlStatement("update pnotes set message_status = ?, activity = '1' where id = ?", array($message_status, $id) );
425   }
429  * Set the patient id in an existing message where pid=0
430  * @param $id the id of the existing note
431  * @param $patient_id the patient id to associate with the note
432  * @author EMR Direct <http://www.emrdirect.com/>
433  */
434 function updatePnotePatient($id, $patient_id)
436   $row = getPnoteById($id);
437   if (! $row) die("updatePnotePatient() did not find id '".text($id)."'");
438   $activity = $assigned_to ? '1' : '0';
440   $pid = $row['pid'];
441   if($pid != 0 || (int)$patient_id < 1) die("updatePnotePatient invalid operation");
443   $pid = (int) $patient_id;
444   $newtext = "\n" . date('Y-m-d H:i') . " (patient set by " . $_SESSION['authUser'] .")";
445   $body = $row['body'] . $newtext;
447   sqlStatement("UPDATE pnotes SET pid = ?, body = ? WHERE id = ?", array($pid, $body, $id) );
450 function authorizePnote($id, $authorized = "1")
452   sqlQuery("UPDATE pnotes SET authorized = ? WHERE id = ?", array ($authorized,$id) );
455 function disappearPnote($id)
457   sqlStatement("UPDATE pnotes SET activity = '0', message_status = 'Done' WHERE id=?", array($id) );
458   return true;
461 function reappearPnote ($id)
463   sqlStatement("UPDATE pnotes SET activity = '1', message_status = IF(message_status='Done','New',message_status) WHERE id=?", array($id) );
464   return true;
467 function deletePnote($id)
469   sqlStatement("UPDATE pnotes SET deleted = '1' WHERE id=?", array($id) );
470   return true;