more organization of autoloaded files (#424)
[openemr.git] / library / pnotes.inc
blob3a9d030790d05b7dda47f7d06beedfaad01c008f
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  */
14 /**
15  * Retrieve a note, given its ID
16  *
17  * @param string $id the ID of the note to retrieve.
18  * @param string $cols A list of columns to retrieve. defaults to '*' for all.
19  */
20 function getPnoteById($id, $cols = "*")
22   return sqlQuery("SELECT $cols FROM pnotes WHERE id=? " .
23     ' AND deleted != 1 '. // exclude ALL deleted notes
24     'order by date DESC limit 0,1', array($id) );
27 /**
28  * Get the patient notes for the given user.
29  *
30  * This function is used to retrieve notes assigned to the given user, or
31  * optionally notes assigned to any user.
32  *
33  * @param string $activity 0 for deleted notes, 1 (the default) for active
34  *                         notes, or 'All' for all.
35  * @param string $show_all whether to display only the selected user's
36  *                         messages, or all users' messages.
37  * @param string $user The user whom's notes you want to retrieve.
38  * @param bool $count Whether to return a count, or just return 0.
39  * @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)
40  * @param string $sortorder whether to sort ascending or descending.
41  * @param string $begin what row to start retrieving results from.
42  * @param string $listnumber number of rows to return.
43  * @return int The number of rows retrieved, or 0 if $count was true.
44  */
45 function getPnotesByUser($activity="1",$show_all="no",$user='',$count=false,$sortby='',$sortorder='',$begin='',$listnumber='')
48   // Set the activity part of query
49   if ($activity=='1') {
50     $activity_query = " pnotes.message_status != 'Done' AND pnotes.activity = 1 AND ";
51   }
52   else if ($activity=='0') {
53     $activity_query = " (pnotes.message_status = 'Done' OR pnotes.activity = 0) AND ";
54   }
55   else { //$activity=='all'
56     $activity_query = " ";
57   }
59   // Set whether to show chosen user or all users
60   if ($show_all == 'yes' ) {
61     $usrvar='_%';
62   } else {
63     $usrvar=$user;
64   }
66   // run the query
67   // 2013-02-08 EMR Direct: minor changes to query so notes with pid=0 don't disappear
68   $sql = "SELECT pnotes.id, pnotes.user, pnotes.pid, pnotes.title, pnotes.date, pnotes.message_status,
69           IF(pnotes.pid = 0 OR pnotes.user != pnotes.pid,users.fname,patient_data.fname) as users_fname,
70           IF(pnotes.pid = 0 OR pnotes.user != pnotes.pid,users.lname,patient_data.lname) as users_lname,
71           patient_data.fname as patient_data_fname, patient_data.lname as patient_data_lname
72           FROM ((pnotes LEFT JOIN users ON pnotes.user = users.username)
73           LEFT JOIN patient_data ON pnotes.pid = patient_data.pid) WHERE $activity_query
74           pnotes.deleted != '1' AND pnotes.assigned_to LIKE ?";
75   if (!empty($sortby) || !empty($sortorder)  || !empty($begin) || !empty($listnumber)) {
76     $sql .= " order by ".escape_sql_column_name($sortby,array('users','patient_data','pnotes'),TRUE).
77             " ".escape_sort_order($sortorder).
78             " limit ".escape_limit($begin).", ".escape_limit($listnumber);
79   }
80   $result = sqlStatement($sql, array($usrvar));
82   // return the results
83   if ($count) {
84     if(sqlNumRows($result) != 0) {
85         $total = sqlNumRows($result);
86     }
87     else {
88         $total = 0;
89     }
90     return $total;
91   }
92   else {
93     return $result;
94   }
97 function getPnotesByDate($date, $activity = "1", $cols = "*", $pid = "%",
98   $limit = "all", $start = 0, $username = '', $docid = 0, $status = "", $orderid = 0)
100 $sqlParameterArray = array();
101   if ($docid) {
102     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
103     "WHERE p.date LIKE ? AND r.type1 = 1 AND " .
104     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid != p.user";
105     array_push($sqlParameterArray, '%'.$date.'%', $docid);
106   }
107   else if ($orderid) {
108     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
109     "WHERE p.date LIKE ? AND r.type1 = 2 AND " .
110     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid != p.user";
111     array_push($sqlParameterArray, '%'.$date.'%', $orderid);
112   }
113   else {
114     $sql = "SELECT $cols FROM pnotes AS p " .
115       "WHERE date LIKE ? AND pid LIKE ? AND p.pid != p.user";
116     array_push($sqlParameterArray, '%'.$date.'%', $pid);
117   }
118   $sql .= " AND deleted != 1"; // exclude ALL deleted notes
119   if ($activity != "all") {
120     if ($activity == '0') {
121       // only return inactive
122       $sql .= " AND (activity = '0' OR message_status = 'Done') ";
123     }
124     else { // $activity == '1'
125       // only return active
126       $sql .= " AND activity = '1' AND message_status != 'Done' ";
127     }
128   }
129   if ($username) {
130     $sql .= " AND assigned_to LIKE ?";
131     array_push($sqlParameterArray, $username);
132   }
133   if ($status)
134     $sql .= " AND message_status IN ('".str_replace(",", "','", add_escape_custom($status) )."')";
135   $sql .= " ORDER BY date DESC";
136   if($limit != "all")
137     $sql .= " LIMIT ".escape_limit($start).", ".escape_limit($limit);
139   $res = sqlStatement($sql, $sqlParameterArray);
141   $all=array();
142   for ($iter = 0;$row = sqlFetchArray($res);$iter++)
143     $all[$iter] = $row;
144   return $all;
147 // activity can only be 0, 1, or 'all'
148 function getSentPnotesByDate($date, $activity = "1", $cols = "*", $pid = "%",
149   $limit = "all", $start = 0, $username = '', $docid = 0, $status = "", $orderid = 0)
151 $sqlParameterArray = array();
152   if ($docid) {
153     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
154     "WHERE p.date LIKE ? AND r.type1 = 1 AND " .
155     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user";
156     array_push($sqlParameterArray, '%'.$date.'%', $docid);
157   }
158   else if ($orderid) {
159     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
160     "WHERE p.date LIKE ? AND r.type1 = 2 AND " .
161     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user";
162     array_push($sqlParameterArray, '%'.$date.'%', $orderid);
163   }
164   else {
165     $sql = "SELECT $cols FROM pnotes AS p " .
166       "WHERE date LIKE ? AND pid LIKE ? AND p.pid = p.user";
167     array_push($sqlParameterArray, '%'.$date.'%', $pid);
168   }
169   $sql .= " AND deleted != 1"; // exclude ALL deleted notes
170   if ($activity != "all") {
171     if ($activity == '0') {
172       // only return inactive
173       $sql .= " AND (activity = '0' OR message_status = 'Done') ";
174     }
175     else { // $activity == '1'
176       // only return active
177       $sql .= " AND activity = '1' AND message_status != 'Done' ";
178     }
179   }
180   if ($username) {
181     $sql .= " AND assigned_to LIKE ?";
182     array_push($sqlParameterArray, $username);
183   }
184   if ($status)
185     $sql .= " AND message_status IN ('".str_replace(",", "','", add_escape_custom($status) )."')";
186   $sql .= " ORDER BY date DESC";
187   if($limit != "all")
188     $sql .= " LIMIT ".escape_limit($start).", ".escape_limit($limit);
190   $res = sqlStatement($sql, $sqlParameterArray);
192   $all=array();
193   for ($iter = 0;$row = sqlFetchArray($res);$iter++)
194     $all[$iter] = $row;
195   return $all;
198 function getPatientNotes($pid = '', $limit = '', $offset = 0, $search = '')
200   if($limit){
201     $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
202   }
203   $sql = "
204     SELECT
205       p.id,
206       p.date,
207       p.user,
208       p.title,
209       REPLACE(
210         p.body,
211         '-patient-',
212         CONCAT(pd.fname, ' ', pd.lname)
213       ) AS body,
214       p.message_status,
215       'Message' as `type`
216     FROM
217       pnotes AS p
218       LEFT JOIN patient_data AS pd
219         ON pd.id = p.pid
220     WHERE assigned_to = '-patient-'
221       AND p.deleted != 1
222       AND p.pid = ?
223       $search
224     ORDER BY `date` desc
225     $limit
226   ";
227   $res = sqlStatement($sql, array($pid));
228   for($iter = 0;$row = sqlFetchArray($res);$iter++){
229     $all[$iter] = $row;
230   }
231   return $all;
234 function getPatientNotifications($pid = '', $limit = '', $offset = 0, $search = '')
236   if($limit){
237     $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
238   }
239   $sql = "
240     SELECT
241       pr.id,
242       date_created AS `date`,
243       'Patient Reminders' AS `user`,
244       due_status AS title,
245       CONCAT(lo.title, ':', lo2.title) AS body,
246       '' as message_status,
247       'Notification' as `type`
248     FROM
249       patient_reminders AS pr
250       LEFT JOIN list_options AS lo
251         ON lo.option_id = pr.category
252         AND lo.list_id = 'rule_action_category' AND lo.activity = 1
253       LEFT JOIN list_options AS lo2
254         ON lo2.option_id = pr.item
255         AND lo2.list_id = 'rule_action' AND lo2.activity = 1
256     WHERE pid = ?
257       AND active = 1
258       AND date_created > DATE_SUB(NOW(), INTERVAL 1 MONTH)
259       $search
260     ORDER BY `date` desc
261     $limit
262   ";
263   $res = sqlStatement($sql, array($pid));
264   for($iter = 0;$row = sqlFetchArray($res);$iter++){
265     $all[$iter] = $row;
266   }
267   return $all;
270 function getPatientSentNotes($pid = '', $limit = '', $offset = 0, $search = '')
272   if($limit){
273     $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
274   }
275   $sql = "
276     SELECT
277       p.id,
278       p.date,
279       p.assigned_to,
280       p.title,
281       REPLACE(
282         p.body,
283         '-patient-',
284         CONCAT(pd.lname, ' ', pd.fname)
285       ) AS body,
286       p.activity,
287       p.message_status,
288       'Message' as `type`
289     FROM
290       pnotes AS p
291       LEFT JOIN patient_data AS pd
292         ON pd.id = p.pid
293     WHERE `user` = ?
294       AND p.deleted != 1
295       AND p.pid = ?
296       AND p.message_status != 'Done'
297       $search
298     ORDER BY `date` desc
299     $limit
300   ";
301   $res = sqlStatement($sql, array($pid,$pid));
302   for($iter = 0;$row = sqlFetchArray($res);$iter++){
303     $all[$iter] = $row;
304   }
305   return $all;
308 // activity can be 0, 1, or 'all'
309 function getPnotesByPid ($pid, $activity = "1", $cols = "*", $limit=10, $start=0)
311  if ($activity == '1') {
312   // return only active
313   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
314     "AND activity = '1' ".
315     " AND message_status != 'Done' ".
316     " AND deleted != 1 ".
317     " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid) );
319  else if ($activity == '0') {
320   // return only inactive
321   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
322     "AND (activity = '0' ".
323     " OR message_status = 'Done') ".
324     " AND deleted != 1 ".
325     " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid) );
327  else { // $activity == "all"
328   // return both active and inactive
329   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
330     " AND deleted != 1 ".
331     " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid) );
333   for ($iter = 0; $row = sqlFetchArray($res); $iter++)
334     $all[$iter] = $row;
335   return $all;
338 /** Add a note to a patient's medical record.
340  * @param int $pid the ID of the patient whos medical record this note is going to be attached to.
341  * @param string $newtext the note contents.
342  * @param int $authorized
343  * @param int $activity
344  * @param string $title
345  * @param string $assigned_to
346  * @param string $datetime
347  * @param string $message_status
348  * @param string $background_user if set then the pnote is created by a background-service rather than a user
349  * @return int the ID of the added note.
350  */
351 function addPnote($pid, $newtext, $authorized = '0', $activity = '1',
352   $title= 'Unassigned', $assigned_to = '', $datetime = '',
353   $message_status = 'New', $background_user="")
355   if (empty($datetime)) $datetime = date('Y-m-d H:i:s');
357   // make inactive if set as Done
358   if ($message_status == 'Done') $activity = 0;
360   $user = ($background_user!="" ? $background_user : $_SESSION['authUser']);
361   $body = date('Y-m-d H:i') . ' (' . $user;
362   if ($assigned_to) $body .= " to $assigned_to";
363   $body = $body . ') ' . $newtext;
365   return sqlInsert('INSERT INTO pnotes (date, body, pid, user, groupname, ' .
366     'authorized, activity, title, assigned_to, message_status) VALUES ' .
367     '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
368     array($datetime, $body, $pid, $user, $_SESSION['authProvider'], $authorized, $activity, $title, $assigned_to, $message_status) );
371 function addMailboxPnote($pid, $newtext, $authorized = '0', $activity = '1',
372   $title='Unassigned', $assigned_to = '', $datetime = '', $message_status = "New")
374   if (empty($datetime)) $datetime = date('Y-m-d H:i:s');
376   // make inactive if set as Done
377   if ($message_status == "Done") $activity = 0;
379   $body = date('Y-m-d H:i') . ' (' . $pid;
380   if ($assigned_to) $body .= " to $assigned_to";
381   $body = $body . ') ' . $newtext;
383   return sqlInsert("INSERT INTO pnotes (date, body, pid, user, groupname, " .
384     "authorized, activity, title, assigned_to, message_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
385     array($datetime, $body, $pid, $pid, 'Default', $authorized, $activity, $title, $assigned_to, $message_status) );
388 function updatePnote($id, $newtext, $title, $assigned_to, $message_status = "")
390   $row = getPnoteById($id);
391   if (! $row) die("updatePnote() did not find id '".text($id)."'");
392   $activity = $assigned_to ? '1' : '0';
394   // make inactive if set as Done
395   if ($message_status == "Done") $activity = 0;
397   $body = $row['body'] . "\n" . date('Y-m-d H:i') .
398     ' (' . $_SESSION['authUser'];
399   if ($assigned_to) $body .= " to $assigned_to";
400   $body = $body . ') ' . $newtext;
402   if ($message_status) {
403     sqlStatement("UPDATE pnotes SET " .
404       "body = ?, activity = ?, title= ?, " .
405       "assigned_to = ?, message_status = ? WHERE id = ?",
406       array($body, $activity, $title, $assigned_to, $message_status, $id) );
407   }
408   else {
409     sqlStatement("UPDATE pnotes SET " .
410       "body = ?, activity = ?, title= ?, " .
411       "assigned_to = ? WHERE id = ?",
412       array($body, $activity, $title, $assigned_to, $id) );
413   }
416 function updatePnoteMessageStatus($id, $message_status)
418   if ($message_status == "Done") {
419     sqlStatement("update pnotes set message_status = ?, activity = '0' where id = ?", array($message_status, $id) );
420   }
421   else {
422     sqlStatement("update pnotes set message_status = ?, activity = '1' where id = ?", array($message_status, $id) );
423   }
427  * Set the patient id in an existing message where pid=0
428  * @param $id the id of the existing note
429  * @param $patient_id the patient id to associate with the note
430  * @author EMR Direct <http://www.emrdirect.com/>
431  */
432 function updatePnotePatient($id, $patient_id)
434   $row = getPnoteById($id);
435   if (! $row) die("updatePnotePatient() did not find id '".text($id)."'");
436   $activity = $assigned_to ? '1' : '0';
438   $pid = $row['pid'];
439   if($pid != 0 || (int)$patient_id < 1) die("updatePnotePatient invalid operation");
441   $pid = (int) $patient_id;
442   $newtext = "\n" . date('Y-m-d H:i') . " (patient set by " . $_SESSION['authUser'] .")";
443   $body = $row['body'] . $newtext;
445   sqlStatement("UPDATE pnotes SET pid = ?, body = ? WHERE id = ?", array($pid, $body, $id) );
448 function authorizePnote($id, $authorized = "1")
450   sqlQuery("UPDATE pnotes SET authorized = ? WHERE id = ?", array ($authorized,$id) );
453 function disappearPnote($id)
455   sqlStatement("UPDATE pnotes SET activity = '0', message_status = 'Done' WHERE id=?", array($id) );
456   return true;
459 function reappearPnote ($id)
461   sqlStatement("UPDATE pnotes SET activity = '1', message_status = IF(message_status='Done','New',message_status) WHERE id=?", array($id) );
462   return true;
465 function deletePnote($id)
467   sqlStatement("UPDATE pnotes SET deleted = '1' WHERE id=?", array($id) );
468   return true;