Fully responsive globals.php with vertical menu (#2460)
[openemr.git] / library / pnotes.inc
blob2099a04d9fa8ef5d0494d41be438b949653e04df
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 "  . escape_sql_column_name(process_cols_escape($cols), array('pnotes')) . " 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     } else if ($activity=='0') {
52         $activity_query = " (pnotes.message_status = 'Done' OR pnotes.activity = 0) AND ";
53     } else { //$activity=='all'
54         $activity_query = " ";
55     }
57   // Set whether to show chosen user or all users
58     if ($show_all == 'yes') {
59         $usrvar='_%';
60     } else {
61         $usrvar=$user;
62     }
64   // run the query
65   // 2013-02-08 EMR Direct: minor changes to query so notes with pid=0 don't disappear
66     $sql = "SELECT pnotes.id, pnotes.user, pnotes.pid, pnotes.title, pnotes.date, pnotes.message_status, pnotes.activity,
67           IF(pnotes.pid = 0 OR pnotes.user != pnotes.pid,users.fname,patient_data.fname) as users_fname,
68           IF(pnotes.pid = 0 OR pnotes.user != pnotes.pid,users.lname,patient_data.lname) as users_lname,
69           patient_data.fname as patient_data_fname, patient_data.lname as patient_data_lname
70           FROM ((pnotes LEFT JOIN users ON pnotes.user = users.username)
71           LEFT JOIN patient_data ON pnotes.pid = patient_data.pid) WHERE $activity_query
72           pnotes.deleted != '1' AND pnotes.assigned_to LIKE ?";
73     if (!empty($sortby) || !empty($sortorder)  || !empty($begin) || !empty($listnumber)) {
74         $sql .= " order by ".escape_sql_column_name($sortby, array('users','patient_data','pnotes'), true).
75             " ".escape_sort_order($sortorder).
76             " limit ".escape_limit($begin).", ".escape_limit($listnumber);
77     }
79     $result = sqlStatement($sql, array($usrvar));
81   // return the results
82     if ($count) {
83         if (sqlNumRows($result) != 0) {
84             $total = sqlNumRows($result);
85         } else {
86             $total = 0;
87         }
89         return $total;
90     } else {
91         return $result;
92     }
95 function getPnotesByDate(
96     $date,
97     $activity = "1",
98     $cols = "*",
99     $pid = "%",
100     $limit = "all",
101     $start = 0,
102     $username = '',
103     $docid = 0,
104     $status = "",
105     $orderid = 0
106 ) {
108     $sqlParameterArray = array();
109     if ($docid) {
110         $sql = "SELECT " . escape_sql_column_name(process_cols_escape($cols), array('pnotes', 'gprelations')) . " FROM pnotes AS p, gprelations AS r " .
111         "WHERE p.date LIKE ? AND r.type1 = 1 AND " .
112         "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid != p.user";
113         array_push($sqlParameterArray, '%'.$date.'%', $docid);
114     } else if ($orderid) {
115         $sql = "SELECT " . escape_sql_column_name(process_cols_escape($cols), array('pnotes', 'gprelations')) . " FROM pnotes AS p, gprelations AS r " .
116         "WHERE p.date LIKE ? AND r.type1 = 2 AND " .
117         "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid != p.user";
118         array_push($sqlParameterArray, '%'.$date.'%', $orderid);
119     } else {
120         $sql = "SELECT "  . escape_sql_column_name(process_cols_escape($cols), array('pnotes')) . " FROM pnotes AS p " .
121         "WHERE date LIKE ? AND pid LIKE ? AND p.pid != p.user";
122         array_push($sqlParameterArray, '%'.$date.'%', $pid);
123     }
125     $sql .= " AND deleted != 1"; // exclude ALL deleted notes
126     if ($activity != "all") {
127         if ($activity == '0') {
128             // only return inactive
129             $sql .= " AND (activity = '0' OR message_status = 'Done') ";
130         } else { // $activity == '1'
131             // only return active
132             $sql .= " AND activity = '1' AND message_status != 'Done' ";
133         }
134     }
136     if ($username) {
137         $sql .= " AND assigned_to LIKE ?";
138         array_push($sqlParameterArray, $username);
139     }
141     if ($status) {
142         $sql .= " AND message_status IN ('".str_replace(",", "','", add_escape_custom($status))."')";
143     }
145     $sql .= " ORDER BY date DESC";
146     if ($limit != "all") {
147         $sql .= " LIMIT ".escape_limit($start).", ".escape_limit($limit);
148     }
150     $res = sqlStatement($sql, $sqlParameterArray);
152     $all=array();
153     for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
154         $all[$iter] = $row;
155     }
157     return $all;
160 // activity can only be 0, 1, or 'all'
161 function getSentPnotesByDate(
162     $date,
163     $activity = "1",
164     $cols = "*",
165     $pid = "%",
166     $limit = "all",
167     $start = 0,
168     $username = '',
169     $docid = 0,
170     $status = "",
171     $orderid = 0
172 ) {
174     $sqlParameterArray = array();
175     if ($docid) {
176         $sql = "SELECT " . escape_sql_column_name(process_cols_escape($cols), array('pnotes', 'gprelations')) . " FROM pnotes AS p, gprelations AS r " .
177         "WHERE p.date LIKE ? AND r.type1 = 1 AND " .
178         "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user";
179         array_push($sqlParameterArray, '%'.$date.'%', $docid);
180     } else if ($orderid) {
181         $sql = "SELECT " . escape_sql_column_name(process_cols_escape($cols), array('pnotes','gprelations')) . " FROM pnotes AS p, gprelations AS r " .
182         "WHERE p.date LIKE ? AND r.type1 = 2 AND " .
183         "r.id1 = ? AND r.type2 = 6 AND p.id = r.id2 AND p.pid = p.user";
184         array_push($sqlParameterArray, '%'.$date.'%', $orderid);
185     } else {
186         $sql = "SELECT " . escape_sql_column_name(process_cols_escape($cols), array('pnotes')) . " FROM pnotes AS p " .
187         "WHERE date LIKE ? AND pid LIKE ? AND p.pid = p.user";
188         array_push($sqlParameterArray, '%'.$date.'%', $pid);
189     }
191     $sql .= " AND deleted != 1"; // exclude ALL deleted notes
192     if ($activity != "all") {
193         if ($activity == '0') {
194             // only return inactive
195             $sql .= " AND (activity = '0' OR message_status = 'Done') ";
196         } else { // $activity == '1'
197             // only return active
198             $sql .= " AND activity = '1' AND message_status != 'Done' ";
199         }
200     }
202     if ($username) {
203         $sql .= " AND assigned_to LIKE ?";
204         array_push($sqlParameterArray, $username);
205     }
207     if ($status) {
208         $sql .= " AND message_status IN ('".str_replace(",", "','", add_escape_custom($status))."')";
209     }
211     $sql .= " ORDER BY date DESC";
212     if ($limit != "all") {
213         $sql .= " LIMIT ".escape_limit($start).", ".escape_limit($limit);
214     }
216     $res = sqlStatement($sql, $sqlParameterArray);
218     $all=array();
219     for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
220         $all[$iter] = $row;
221     }
223     return $all;
226 function getPatientNotes($pid = '', $limit = '', $offset = 0, $search = '')
228     if ($limit) {
229         $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
230     }
232     $sql = "
233     SELECT
234       p.id,
235       p.date,
236       p.user,
237       p.title,
238       REPLACE(
239         p.body,
240         '-patient-',
241         CONCAT(pd.fname, ' ', pd.lname)
242       ) AS body,
243       p.message_status,
244       'Message' as `type`,
245       p.activity
246     FROM
247       pnotes AS p
248       LEFT JOIN patient_data AS pd
249         ON pd.id = p.pid
250     WHERE assigned_to = '-patient-'
251       AND p.deleted != 1
252       AND p.pid = ?
253       $search
254     ORDER BY `date` desc
255     $limit
256   ";
257     $res = sqlStatement($sql, array($pid));
258     for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
259         $all[$iter] = $row;
260     }
262     return $all;
265 function getPatientNotifications($pid = '', $limit = '', $offset = 0, $search = '')
267     if ($limit) {
268         $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
269     }
271     $sql = "
272     SELECT
273       pr.id,
274       date_created AS `date`,
275       'Patient Reminders' AS `user`,
276       due_status AS title,
277       CONCAT(lo.title, ':', lo2.title) AS body,
278       '' as message_status,
279       'Notification' as `type`
280     FROM
281       patient_reminders AS pr
282       LEFT JOIN list_options AS lo
283         ON lo.option_id = pr.category
284         AND lo.list_id = 'rule_action_category' AND lo.activity = 1
285       LEFT JOIN list_options AS lo2
286         ON lo2.option_id = pr.item
287         AND lo2.list_id = 'rule_action' AND lo2.activity = 1
288     WHERE pid = ?
289       AND active = 1
290       AND date_created > DATE_SUB(NOW(), INTERVAL 1 MONTH)
291       $search
292     ORDER BY `date` desc
293     $limit
294   ";
295     $res = sqlStatement($sql, array($pid));
296     for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
297         $all[$iter] = $row;
298     }
300     return $all;
303 function getPatientSentNotes($pid = '', $limit = '', $offset = 0, $search = '')
305     if ($limit) {
306         $limit = "LIMIT ".escape_limit($offset).", ".escape_limit($limit);
307     }
309     $sql = "
310     SELECT
311       p.id,
312       p.date,
313       p.assigned_to,
314       p.title,
315       REPLACE(
316         p.body,
317         '-patient-',
318         CONCAT(pd.lname, ' ', pd.fname)
319       ) AS body,
320       p.activity,
321       p.message_status,
322       'Message' as `type`
323     FROM
324       pnotes AS p
325       LEFT JOIN patient_data AS pd
326         ON pd.id = p.pid
327     WHERE `user` = ?
328       AND p.deleted != 1
329       AND p.pid = ?
330       AND p.message_status != 'Done'
331       $search
332     ORDER BY `date` desc
333     $limit
334   ";
335     $res = sqlStatement($sql, array($pid,$pid));
336     for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
337         $all[$iter] = $row;
338     }
340     return $all;
345 /** Add a note to a patient's medical record.
347  * @param int $pid the ID of the patient whos medical record this note is going to be attached to.
348  * @param string $newtext the note contents.
349  * @param int $authorized
350  * @param int $activity
351  * @param string $title
352  * @param string $assigned_to
353  * @param string $datetime
354  * @param string $message_status
355  * @param string $background_user if set then the pnote is created by a background-service rather than a user
356  * @return int the ID of the added note.
357  */
358 function addPnote(
359     $pid,
360     $newtext,
361     $authorized = '0',
362     $activity = '1',
363     $title = 'Unassigned',
364     $assigned_to = '',
365     $datetime = '',
366     $message_status = 'New',
367     $background_user = ""
368 ) {
370     if (empty($datetime)) {
371         $datetime = date('Y-m-d H:i:s');
372     }
374   // make inactive if set as Done
375     if ($message_status == 'Done') {
376         $activity = 0;
377     }
378     $user = ($background_user!="" ? $background_user : $_SESSION['authUser']);
379     $body = date('Y-m-d H:i') . ' (' . $user;
380     if ($assigned_to) {
381         $body .= " to $assigned_to";
382     }
384     $body = $body . ') ' . $newtext;
386     return sqlInsert(
387         'INSERT INTO pnotes (date, body, pid, user, groupname, ' .
388         'authorized, activity, title, assigned_to, message_status, update_by, update_date) VALUES ' .
389         '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())',
390         array($datetime, $body, $pid, $user, $_SESSION['authProvider'], $authorized, $activity, $title, $assigned_to, $message_status, $_SESSION['authUserID'])
391     );
394 function addMailboxPnote(
395     $pid,
396     $newtext,
397     $authorized = '0',
398     $activity = '1',
399     $title = 'Unassigned',
400     $assigned_to = '',
401     $datetime = '',
402     $message_status = "New"
403 ) {
405     if (empty($datetime)) {
406         $datetime = date('Y-m-d H:i:s');
407     }
409   // make inactive if set as Done
410     if ($message_status == "Done") {
411         $activity = 0;
412     }
414     $body = date('Y-m-d H:i') . ' (' . $pid;
415     if ($assigned_to) {
416         $body .= " to $assigned_to";
417     }
419     $body = $body . ') ' . $newtext;
421     return sqlInsert(
422         "INSERT INTO pnotes (date, body, pid, user, groupname, " .
423         "authorized, activity, title, assigned_to, message_status, update_by, update_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())",
424         array($datetime, $body, $pid, $pid, 'Default', $authorized, $activity, $title, $assigned_to, $message_status, $_SESSION['authUserID'])
425     );
428 function updatePnote($id, $newtext, $title, $assigned_to, $message_status = "", $datetime = "")
430     $row = getPnoteById($id);
431     if (! $row) {
432         die("updatePnote() did not find id '".text($id)."'");
433     }
435     if (empty($datetime)) {
436         $datetime = date('Y-m-d H:i:s');
437     }
439     $activity = $assigned_to ? '1' : '0';
441   // make inactive if set as Done
442     if ($message_status == "Done") {
443         $activity = 0;
444     }
446     $body = $row['body'] . "\n" . date('Y-m-d H:i') .
447     ' (' . $_SESSION['authUser'];
448     if ($assigned_to) {
449         $body .= " to $assigned_to";
450     }
452     $body = $body . ') ' . $newtext;
455     $sql = "UPDATE pnotes SET " .
456         "body = ?, activity = ?, title= ?, " .
457         "assigned_to = ?, update_by = ?, update_date = NOW()";
458     $bindingParams =  array($body, $activity, $title, $assigned_to, $_SESSION['authUserID']);
459     if ($message_status) {
460         $sql .= " ,message_status = ?";
461         $bindingParams[] = $message_status;
462     }
463     if ($GLOBALS['messages_due_date']) {
464         $sql .= " ,date = ?";
465         $bindingParams[] = $datetime;
466     }
467     $sql .= " WHERE id = ?";
468     $bindingParams[] = $id;
469     sqlStatement($sql, $bindingParams);
472 function updatePnoteMessageStatus($id, $message_status)
474     if ($message_status == "Done") {
475         sqlStatement("update pnotes set message_status = ?, activity = '0', update_by = ?, update_date = NOW() where id = ?", array($message_status, $_SESSION['authUserID'], $id));
476     } else {
477         sqlStatement("update pnotes set message_status = ?, activity = '1', update_by = ?, update_date = NOW() where id = ?", array($message_status, $_SESSION['authUserID'], $id));
478     }
482  * Set the patient id in an existing message where pid=0
483  * @param $id the id of the existing note
484  * @param $patient_id the patient id to associate with the note
485  * @author EMR Direct <http://www.emrdirect.com/>
486  */
487 function updatePnotePatient($id, $patient_id)
489     $row = getPnoteById($id);
490     if (! $row) {
491         die("updatePnotePatient() did not find id '".text($id)."'");
492     }
494     $activity = $assigned_to ? '1' : '0';
496     $pid = $row['pid'];
497     if ($pid != 0 || (int)$patient_id < 1) {
498         die("updatePnotePatient invalid operation");
499     }
501     $pid = (int) $patient_id;
502     $newtext = "\n" . date('Y-m-d H:i') . " (patient set by " . $_SESSION['authUser'] .")";
503     $body = $row['body'] . $newtext;
505     sqlStatement("UPDATE pnotes SET pid = ?, body = ?, update_by = ?, update_date = NOW() WHERE id = ?", array($pid, $body, $_SESSION['authUserID'], $id));
508 function authorizePnote($id, $authorized = "1")
510     sqlQuery("UPDATE pnotes SET authorized = ? , update_by = ?, update_date = NOW() WHERE id = ?", array ($authorized, $_SESSION['authUserID'], $id));
513 function disappearPnote($id)
515     sqlStatement("UPDATE pnotes SET activity = '0', message_status = 'Done', update_by = ?, update_date = NOW()  WHERE id=?", array($_SESSION['authUserID'], $id));
516     return true;
519 function reappearPnote($id)
521     sqlStatement("UPDATE pnotes SET activity = '1', message_status = IF(message_status='Done','New',message_status), update_by = ?, update_date = NOW() WHERE id=?", array($_SESSION['authUserID'], $id));
522     return true;
525 function deletePnote($id)
527     sqlStatement("UPDATE pnotes SET deleted = '1', update_by = ?, update_date = NOW() WHERE id=?", array($_SESSION['authUserID'], $id));
528     return true;