Merge pull request #1761 from sjpadgett/PP2-appointment
[openemr.git] / library / pnotes.inc
blob0f43ae5652c365b4ec63556690ba4941df033c57
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     } 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 $cols 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 $cols 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 $cols 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 $cols 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 $cols 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 $cols 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;
343 // activity can be 0, 1, or 'all'
344 function getPnotesByPid($pid, $activity = "1", $cols = "*", $limit = 10, $start = 0)
346     if ($activity == '1') {
347         // return only active
348         $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
349           "AND activity = '1' ".
350           " AND message_status != 'Done' ".
351           " AND deleted != 1 ".
352           " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid));
353     } else if ($activity == '0') {
354         // return only inactive
355         $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
356           "AND (activity = '0' ".
357           " OR message_status = 'Done') ".
358           " AND deleted != 1 ".
359           " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid));
360     } else { // $activity == "all"
361         // return both active and inactive
362         $res = sqlStatement("SELECT $cols FROM pnotes WHERE pid LIKE ? " .
363           " AND deleted != 1 ".
364           " ORDER BY date DESC LIMIT ".escape_limit($start).",".escape_limit($limit), array($pid));
365     }
367     for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
368         $all[$iter] = $row;
369     }
371     return $all;
374 /** Add a note to a patient's medical record.
376  * @param int $pid the ID of the patient whos medical record this note is going to be attached to.
377  * @param string $newtext the note contents.
378  * @param int $authorized
379  * @param int $activity
380  * @param string $title
381  * @param string $assigned_to
382  * @param string $datetime
383  * @param string $message_status
384  * @param string $background_user if set then the pnote is created by a background-service rather than a user
385  * @return int the ID of the added note.
386  */
387 function addPnote(
388     $pid,
389     $newtext,
390     $authorized = '0',
391     $activity = '1',
392     $title = 'Unassigned',
393     $assigned_to = '',
394     $datetime = '',
395     $message_status = 'New',
396     $background_user = ""
397 ) {
399     if (empty($datetime)) {
400         $datetime = date('Y-m-d H:i:s');
401     }
403   // make inactive if set as Done
404     if ($message_status == 'Done') {
405         $activity = 0;
406     }
408     $user = ($background_user!="" ? $background_user : $_SESSION['authUser']);
409     $body = date('Y-m-d H:i') . ' (' . $user;
410     if ($assigned_to) {
411         $body .= " to $assigned_to";
412     }
414     $body = $body . ') ' . $newtext;
416     return sqlInsert(
417         'INSERT INTO pnotes (date, body, pid, user, groupname, ' .
418         'authorized, activity, title, assigned_to, message_status) VALUES ' .
419         '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
420         array($datetime, $body, $pid, $user, $_SESSION['authProvider'], $authorized, $activity, $title, $assigned_to, $message_status)
421     );
424 function addMailboxPnote(
425     $pid,
426     $newtext,
427     $authorized = '0',
428     $activity = '1',
429     $title = 'Unassigned',
430     $assigned_to = '',
431     $datetime = '',
432     $message_status = "New"
433 ) {
435     if (empty($datetime)) {
436         $datetime = date('Y-m-d H:i:s');
437     }
439   // make inactive if set as Done
440     if ($message_status == "Done") {
441         $activity = 0;
442     }
444     $body = date('Y-m-d H:i') . ' (' . $pid;
445     if ($assigned_to) {
446         $body .= " to $assigned_to";
447     }
449     $body = $body . ') ' . $newtext;
451     return sqlInsert(
452         "INSERT INTO pnotes (date, body, pid, user, groupname, " .
453         "authorized, activity, title, assigned_to, message_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
454         array($datetime, $body, $pid, $pid, 'Default', $authorized, $activity, $title, $assigned_to, $message_status)
455     );
458 function updatePnote($id, $newtext, $title, $assigned_to, $message_status = "")
460     $row = getPnoteById($id);
461     if (! $row) {
462         die("updatePnote() did not find id '".text($id)."'");
463     }
465     $activity = $assigned_to ? '1' : '0';
467   // make inactive if set as Done
468     if ($message_status == "Done") {
469         $activity = 0;
470     }
472     $body = $row['body'] . "\n" . date('Y-m-d H:i') .
473     ' (' . $_SESSION['authUser'];
474     if ($assigned_to) {
475         $body .= " to $assigned_to";
476     }
478     $body = $body . ') ' . $newtext;
480     if ($message_status) {
481         sqlStatement(
482             "UPDATE pnotes SET " .
483             "body = ?, activity = ?, title= ?, " .
484             "assigned_to = ?, message_status = ? WHERE id = ?",
485             array($body, $activity, $title, $assigned_to, $message_status, $id)
486         );
487     } else {
488         sqlStatement(
489             "UPDATE pnotes SET " .
490             "body = ?, activity = ?, title= ?, " .
491             "assigned_to = ? WHERE id = ?",
492             array($body, $activity, $title, $assigned_to, $id)
493         );
494     }
497 function updatePnoteMessageStatus($id, $message_status)
499     if ($message_status == "Done") {
500         sqlStatement("update pnotes set message_status = ?, activity = '0' where id = ?", array($message_status, $id));
501     } else {
502         sqlStatement("update pnotes set message_status = ?, activity = '1' where id = ?", array($message_status, $id));
503     }
507  * Set the patient id in an existing message where pid=0
508  * @param $id the id of the existing note
509  * @param $patient_id the patient id to associate with the note
510  * @author EMR Direct <http://www.emrdirect.com/>
511  */
512 function updatePnotePatient($id, $patient_id)
514     $row = getPnoteById($id);
515     if (! $row) {
516         die("updatePnotePatient() did not find id '".text($id)."'");
517     }
519     $activity = $assigned_to ? '1' : '0';
521     $pid = $row['pid'];
522     if ($pid != 0 || (int)$patient_id < 1) {
523         die("updatePnotePatient invalid operation");
524     }
526     $pid = (int) $patient_id;
527     $newtext = "\n" . date('Y-m-d H:i') . " (patient set by " . $_SESSION['authUser'] .")";
528     $body = $row['body'] . $newtext;
530     sqlStatement("UPDATE pnotes SET pid = ?, body = ? WHERE id = ?", array($pid, $body, $id));
533 function authorizePnote($id, $authorized = "1")
535     sqlQuery("UPDATE pnotes SET authorized = ? WHERE id = ?", array ($authorized,$id));
538 function disappearPnote($id)
540     sqlStatement("UPDATE pnotes SET activity = '0', message_status = 'Done' WHERE id=?", array($id));
541     return true;
544 function reappearPnote($id)
546     sqlStatement("UPDATE pnotes SET activity = '1', message_status = IF(message_status='Done','New',message_status) WHERE id=?", array($id));
547     return true;
550 function deletePnote($id)
552     sqlStatement("UPDATE pnotes SET deleted = '1' WHERE id=?", array($id));
553     return true;