Security fixes.
[openemr.git] / library / pnotes.inc
blob5b6e265c6ed72e3f5b3df0f81da975b49339fc34
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.
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 ".add_escape_custom($sortby)." ".add_escape_custom($sortorder).
79            " limit ".add_escape_custom($begin).", ".add_escape_custom($listnumber);
80   }
81   $result = sqlStatement($sql, array($usrvar));
83   // return the results
84   if ($count) {
85     if(sqlNumRows($result) != 0) {
86         $total = sqlNumRows($result);
87     }
88     else {
89         $total = 0;
90     }
91     return $total;
92   }
93   else {
94     return $result;
95   }
98 function getPnotesByDate($date, $activity = "1", $cols = "*", $pid = "%",
99   $limit = "all", $start = 0, $username = '', $docid = 0, $status = "")
101 $sqlParameterArray = array();
102   if ($docid) {
103     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
104     "WHERE p.date LIKE ? AND r.type1 = 1 AND " .
105     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid != p.user";
106     array_push($sqlParameterArray, '%'.$date.'%', $docid);
107   }
108   else {
109     $sql = "SELECT $cols FROM pnotes AS p " .
110       "WHERE date LIKE ? AND pid LIKE ? AND p.pid != p.user";
111     array_push($sqlParameterArray, '%'.$date.'%', $pid);
112   }
113   $sql .= " AND deleted != 1"; // exclude ALL deleted notes
114   if ($activity != "all") {
115     if ($activity == '0') {
116       // only return inactive
117       $sql .= " AND (activity = '0' OR message_status = 'Done') ";
118     }
119     else { // $activity == '1'
120       // only return active
121       $sql .= " AND activity = '1' AND message_status != 'Done' ";
122     }
123   }
124   if ($username) {
125     $sql .= " AND assigned_to LIKE ?";
126     array_push($sqlParameterArray, $username);
127   }
128   if ($status)
129     $sql .= " AND message_status IN ('".str_replace(",", "','", add_escape_custom($status) )."')";
130   $sql .= " ORDER BY date DESC";
131   if($limit != "all")
132     $sql .= " LIMIT ".add_escape_custom($start).", ".add_escape_custom($limit);
134   $res = sqlStatement($sql, $sqlParameterArray);
136   $all=array();
137   for ($iter = 0;$row = sqlFetchArray($res);$iter++)
138     $all[$iter] = $row;
139   return $all;
142 // activity can only be 0, 1, or 'all'
143 function getSentPnotesByDate($date, $activity = "1", $cols = "*", $pid = "%",
144   $limit = "all", $start = 0, $username = '', $docid = 0, $status = "")
146 $sqlParameterArray = array();
147   if ($docid) {
148     $sql = "SELECT $cols FROM pnotes AS p, gprelations AS r " .
149     "WHERE p.date LIKE ? AND r.type1 = 1 AND " .
150     "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user";
151     array_push($sqlParameterArray, '%'.$date.'%', $docid);
152   }
153   else {
154     $sql = "SELECT $cols FROM pnotes AS p " .
155       "WHERE date LIKE ? AND pid LIKE ? AND p.pid = p.user";
156     array_push($sqlParameterArray, '%'.$date.'%', $pid);
157   }
158   $sql .= " AND deleted != 1"; // exclude ALL deleted notes
159   if ($activity != "all") {
160     if ($activity == '0') {
161       // only return inactive
162       $sql .= " AND (activity = '0' OR message_status = 'Done') ";
163     }
164     else { // $activity == '1'
165       // only return active
166       $sql .= " AND activity = '1' AND message_status != 'Done' ";
167     }
168   }
169   if ($username) {
170     $sql .= " AND assigned_to LIKE ?";
171     array_push($sqlParameterArray, $username);
172   }
173   if ($status)
174     $sql .= " AND message_status IN ('".str_replace(",", "','", add_escape_custom($status) )."')";
175   $sql .= " ORDER BY date DESC";
176   if($limit != "all")
177     $sql .= " LIMIT ".add_escape_custom($start).", ".$limit;
179   $res = sqlStatement($sql, $sqlParameterArray);
181   $all=array();
182   for ($iter = 0;$row = sqlFetchArray($res);$iter++)
183     $all[$iter] = $row;
184   return $all;
187 function getPatientNotes($pid = '', $limit = '', $offset = 0, $search = '')
189   if($limit){
190     $limit = "LIMIT ".add_escape_custom($offset).", ".add_escape_custom($limit);
191   }
192   $sql = "
193     SELECT
194       p.id,
195       p.date,
196       p.user,
197       p.title,
198       REPLACE(
199         p.body,
200         '-patient-',
201         CONCAT(pd.fname, ' ', pd.lname)
202       ) AS body,
203       p.message_status,
204       'Message' as `type`
205     FROM
206       pnotes AS p 
207       LEFT JOIN patient_data AS pd 
208         ON pd.id = p.pid 
209     WHERE assigned_to = '-patient-' 
210       AND p.deleted != 1 
211       AND p.pid = ?
212       $search
213     ORDER BY `date` desc
214     $limit
215   ";
216   $res = sqlStatement($sql, array($pid));
217   for($iter = 0;$row = sqlFetchArray($res);$iter++){
218     $all[$iter] = $row;
219   }
220   return $all;
223 function getPatientNotifications($pid = '', $limit = '', $offset = 0, $search = '')
225   if($limit){
226     $limit = "LIMIT ".add_escape_custom($offset).", ".add_escape_custom($limit);
227   }
228   $sql = "
229     SELECT
230       pr.id,
231       date_created AS `date`,
232       'Patient Reminders' AS `user`,
233       due_status AS title,
234       CONCAT(lo.title, ':', lo2.title) AS body,
235       '' as message_status,
236       'Notification' as `type`
237     FROM
238       patient_reminders AS pr 
239       LEFT JOIN list_options AS lo 
240         ON lo.option_id = pr.category 
241         AND lo.list_id = 'rule_action_category' 
242       LEFT JOIN list_options AS lo2 
243         ON lo2.option_id = pr.item 
244         AND lo2.list_id = 'rule_action' 
245     WHERE pid = ?
246       AND active = 1
247       AND date_created > DATE_SUB(NOW(), INTERVAL 1 MONTH)
248       $search
249     ORDER BY `date` desc
250     $limit
251   ";
252   $res = sqlStatement($sql, array($pid));
253   for($iter = 0;$row = sqlFetchArray($res);$iter++){
254     $all[$iter] = $row;
255   }
256   return $all;
259 function getPatientSentNotes($pid = '', $limit = '', $offset = 0, $search = '')
261   if($limit){
262     $limit = "LIMIT ".add_escape_custom($offset).", ".add_escape_custom($limit);
263   }
264   $sql = "
265     SELECT
266       p.id,
267       p.date,
268       p.assigned_to,
269       p.title,
270       REPLACE(
271         p.body,
272         '-patient-',
273         CONCAT(pd.lname, ' ', pd.fname)
274       ) AS body,
275       p.activity,
276       p.message_status,
277       'Message' as `type`
278     FROM
279       pnotes AS p 
280       LEFT JOIN patient_data AS pd 
281         ON pd.id = p.pid 
282     WHERE `user` = ?
283       AND p.deleted != 1 
284       AND p.pid = ?
285       AND p.message_status != 'Done'
286       $search
287     ORDER BY `date` desc
288     $limit
289   ";
290   $res = sqlStatement($sql, array($pid,$pid));
291   for($iter = 0;$row = sqlFetchArray($res);$iter++){
292     $all[$iter] = $row;
293   }
294   return $all;
297 // activity can be 0, 1, or 'all'
298 function getPnotesByPid ($pid, $activity = "1", $cols = "*", $limit=10, $start=0)
300  if ($activity == '1') {
301   // return only active
302   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
303     "AND activity = '1' ".
304     " AND message_status != 'Done' ".
305     " AND deleted != 1 ".
306     " ORDER BY date DESC LIMIT ".add_escape_custom($start).",".add_escape_custom($limit), array($pid) );
308  else if ($activity == '0') {
309   // return only inactive
310   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
311     "AND (activity = '0' ".
312     " OR message_status = 'Done') ".
313     " AND deleted != 1 ".
314     " ORDER BY date DESC LIMIT ".add_escape_custom($start).",".add_escape_custom($limit), array($pid) );
316  else { // $activity == "all"
317   // return both active and inactive
318   $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
319     " AND deleted != 1 ".
320     " ORDER BY date DESC LIMIT ".add_escape_custom($start).",".add_escape_custom($limit), array($pid) );
322   for ($iter = 0; $row = sqlFetchArray($res); $iter++)
323     $all[$iter] = $row;
324   return $all;
327 /** Add a note to a patient's medical record.
329  * @param int $pid the ID of the patient whos medical record this note is going to be attached to.
330  * @param string $newtext the note contents.
331  * @param int $authorized
332  * @param int $activity
333  * @param string $title
334  * @param string $assigned_to
335  * @param string $datetime
336  * @param string $message_status
337  * @param string $background_user if set then the pnote is created by a background-service rather than a user
338  * @return int the ID of the added note.
339  */
340 function addPnote($pid, $newtext, $authorized = '0', $activity = '1',
341   $title= 'Unassigned', $assigned_to = '', $datetime = '',
342   $message_status = 'New', $background_user="")
344   if (empty($datetime)) $datetime = date('Y-m-d H:i:s');
346   // make inactive if set as Done
347   if ($message_status == 'Done') $activity = 0;
349   $user = ($background_user!="" ? $background_user : $_SESSION['authUser']);
350   $body = date('Y-m-d H:i') . ' (' . $user;
351   if ($assigned_to) $body .= " to $assigned_to";
352   $body = $body . ') ' . $newtext;
354   return sqlInsert('INSERT INTO pnotes (date, body, pid, user, groupname, ' .
355     'authorized, activity, title, assigned_to, message_status) VALUES ' .
356     '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
357     array($datetime, $body, $pid, $user, $_SESSION['authProvider'], $authorized, $activity, $title, $assigned_to, $message_status) );
360 function addMailboxPnote($pid, $newtext, $authorized = '0', $activity = '1',
361   $title='Unassigned', $assigned_to = '', $datetime = '', $message_status = "New")
363   if (empty($datetime)) $datetime = date('Y-m-d H:i:s');
365   // make inactive if set as Done
366   if ($message_status == "Done") $activity = 0;
368   $body = date('Y-m-d H:i') . ' (' . $pid;
369   if ($assigned_to) $body .= " to $assigned_to";
370   $body = $body . ') ' . $newtext;
372   return sqlInsert("INSERT INTO pnotes (date, body, pid, user, groupname, " .
373     "authorized, activity, title, assigned_to, message_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
374     array($datetime, $body, $pid, $pid, 'Default', $authorized, $activity, $title, $assigned_to, $message_status) );
377 function updatePnote($id, $newtext, $title, $assigned_to, $message_status = "")
379   $row = getPnoteById($id);
380   if (! $row) die("updatePnote() did not find id '".text($id)."'");
381   $activity = $assigned_to ? '1' : '0';
383   // make inactive if set as Done
384   if ($message_status == "Done") $activity = 0;
386   $body = $row['body'] . "\n" . date('Y-m-d H:i') .
387     ' (' . $_SESSION['authUser'];
388   if ($assigned_to) $body .= " to $assigned_to";
389   $body = $body . ') ' . $newtext;
391   if ($message_status) {
392     sqlStatement("UPDATE pnotes SET " .
393       "body = ?, activity = ?, title= ?, " .
394       "assigned_to = ?, message_status = ? WHERE id = ?",
395       array($body, $activity, $title, $assigned_to, $message_status, $id) );
396   }
397   else {
398     sqlStatement("UPDATE pnotes SET " .
399       "body = ?, activity = ?, title= ?, " .
400       "assigned_to = ? WHERE id = ?",
401       array($body, $activity, $title, $assigned_to, $id) );
402   }
405 function updatePnoteMessageStatus($id, $message_status)
407   if ($message_status == "Done") {
408     sqlStatement("update pnotes set message_status = ?, activity = '0' where id = ?", array($message_status, $id) );
409   }
410   else {
411     sqlStatement("update pnotes set message_status = ?, activity = '1' where id = ?", array($message_status, $id) );
412   }
416  * Set the patient id in an existing message where pid=0
417  * @param $id the id of the existing note
418  * @param $patient_id the patient id to associate with the note
419  * @author EMR Direct <http://www.emrdirect.com/>
420  */
421 function updatePnotePatient($id, $patient_id)
423   $row = getPnoteById($id);
424   if (! $row) die("updatePnotePatient() did not find id '".text($id)."'");
425   $activity = $assigned_to ? '1' : '0';
427   $pid = $row['pid'];
428   if($pid != 0 || (int)$patient_id < 1) die("updatePnotePatient invalid operation");
430   $pid = (int) $patient_id;
431   $newtext = "\n" . date('Y-m-d H:i') . " (patient set by " . $_SESSION['authUser'] .")";
432   $body = $row['body'] . $newtext;
434   sqlStatement("UPDATE pnotes SET pid = ?, body = ? WHERE id = ?", array($pid, $body, $id) );
437 function authorizePnote($id, $authorized = "1")
439   sqlQuery("UPDATE pnotes SET authorized = ? WHERE id = ?", array ($authorized,$id) );
442 function disappearPnote($id)
444   sqlStatement("UPDATE pnotes SET activity = '0', message_status = 'Done' WHERE id=?", array($id) );
445   return true;
448 function reappearPnote ($id)
450   sqlStatement("UPDATE pnotes SET activity = '1', message_status = IF(message_status='Done','New',message_status) WHERE id=?", array($id) );
451   return true;
454 function deletePnote($id)
456   sqlStatement("UPDATE pnotes SET deleted = '1' WHERE id=?", array($id) );
457   return true;