quick minor path updates (#1968)
[openemr.git] / library / direct_message_check.inc
blobc5289e8409cdc70bdfcee3d887f374fe5adbb81e
1 <?php
2 /**
3  * Background receive function for phiMail Direct Messaging service.
4  *
5  * This script is called by the background service manager
6  * at /library/ajax/execute_background_services.php
7  *
8  * Copyright (C) 2013 EMR Direct <http://www.emrdirect.com/>
9  *
10  * LICENSE: This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
20  *
21  * @package OpenEMR
22  * @author  EMR Direct <http://www.emrdirect.com/>
23  * @link    http://www.open-emr.org
24  */
26 require_once(dirname(__FILE__) . "/log.inc");
27 require_once(dirname(__FILE__) . "/pnotes.inc");
28 require_once(dirname(__FILE__) . "/documents.php");
29 require_once(dirname(__FILE__) . "/gprelations.inc.php");
31 use PHPMailer\PHPMailer\PHPMailer;
33 /**
34  * Connect to a phiMail Direct Messaging server
35  */
37 function phimail_connect(&$phimail_error)
40     if ($GLOBALS['phimail_enable'] == false) {
41         $phimail_error = 'C1';
42         return false; //for safety
43     }
45     $phimail_server = @parse_url($GLOBALS['phimail_server_address']);
46     $phimail_username = $GLOBALS['phimail_username'];
47     $phimail_password = $GLOBALS['phimail_password'];
48     $phimail_cafile = dirname(__FILE__) . '/../sites/' . $_SESSION['site_id']
49       . '/documents/phimail_server_pem/phimail_server.pem';
50     if (!file_exists($phimail_cafile)) {
51         $phimail_cafile='';
52     }
54     $phimail_secure = true;
55     switch ($phimail_server['scheme']) {
56         case "tcp":
57         case "http":
58             $server = "tcp://".$phimail_server['host'];
59               $phimail_secure = false;
60             break;
61         case "https":
62             $server = "ssl://" . $phimail_server['host']
63                . ':' . $phimail_server['port'];
64             break;
65         case "ssl":
66         case "sslv3":
67         case "tls":
68             $server = $GLOBALS['phimail_server_address'];
69             break;
70         default:
71             $phimail_error = 'C2';
72             return false;
73     }
75     if ($phimail_secure) {
76         $context = stream_context_create();
77         if ($phimail_cafile != '' &&
78             (!stream_context_set_option($context, 'ssl', 'verify_peer', true) ||
79              !stream_context_set_option($context, 'ssl', 'cafile', $phimail_cafile))) {
80             $phimail_error = 'C3';
81             return false;
82         }
84         $socket_tries = 0;
85         $fp = false;
86         while ($socket_tries < 3 && !$fp) {
87             $socket_tries++;
88             $fp = @stream_socket_client(
89                 $server,
90                 $err1,
91                 $err2,
92                 10,
93                 STREAM_CLIENT_CONNECT,
94                 $context
95             );
96         }
98         if (!$fp) {
99             if ($err1 == '111') {
100                 $err2 = xl('Server may be offline');
101             }
103             if ($err2 == '') {
104                 $err2 = xl('Connection error');
105             }
107             $phimail_error = "C4 $err1 ($err2)";
108         }
109     } else {
110         $fp = @fsockopen($server, $phimail_server['port']);
111     }
113     return $fp;
117  * Connect to a phiMail Direct Messaging server and check for any incoming status
118  * messages related to previously transmitted messages or any new messages received.
119  */
121 function phimail_check()
123     $fp = phimail_connect($err);
124     if ($fp===false) {
125         phimail_logit(0, xl('could not connect to server').' '.$err);
126         return;
127     }
129     $phimail_username = $GLOBALS['phimail_username'];
130     $phimail_password = $GLOBALS['phimail_password'];
132     $ret = phimail_write_expect_OK($fp, "AUTH $phimail_username $phimail_password\n");
133     if ($ret!==true) {
134         phimail_logit(0, "authentication error " . $ret);
135         return;
136     }
138     if (!($notifyUsername = $GLOBALS['phimail_notify'])) {
139         $notifyUsername='admin'; //fallback
140     }
142     while (1) {
143         phimail_write($fp, "CHECK\n");
144         $ret=fgets($fp, 512);
146         if ($ret=="NONE\n") { //nothing to process
147             phimail_close($fp);
148             phimail_logit(1, "message check completed");
149             return;
150         } else if (substr($ret, 0, 6)=="STATUS") {
151          //Format STATUS message-id status-code [additional-information]
152             $val=explode(" ", trim($ret), 4);
153             $sql='SELECT * from direct_message_log WHERE msg_id = ?';
154             $res = sqlStatementNoLog($sql, array($val[1]));
155             if ($res===false) { //database problem
156                 phimail_close($fp);
157                 phimail_logit(0, "database problem");
158                 return;
159             }
161             if (($msg=sqlFetchArray($res))===false) {
162                 //no match, so log it and move on (should never happen)
163                 phimail_logit(0, "NO MATCH: ".$ret);
164                 $ret = phimail_write_expect_OK($fp, "OK\n");
165                 if ($ret!==true) {
166                     return;
167                 } else {
168                     continue;
169                 }
170             }
172             //if we get here, $msg contains the matching outgoing message record
173             if ($val[2]=='failed') {
174                 $success=0;
175                 $status='F';
176             } else if ($val[2]=='dispatched') {
177                 $success=1;
178                 $status='D';
179             } else {
180             //unrecognized status, log it and move on (should never happen)
181                 $ret = "UNKNOWN STATUS: ".$ret;
182                 $success=0;
183                 $status='U';
184             }
186             phimail_logit($success, $ret, $msg['patient_id']);
188             if (!isset($val[3])) {
189                 $val[3]="";
190             }
192             $sql = "UPDATE direct_message_log SET status=?, status_ts=NOW(), status_info=? WHERE msg_type='S' AND msg_id=?";
193             $res = sqlStatementNoLog($sql, array($status,$val[3],$val[1]));
194             if ($res===false) { //database problem
195                 phimail_close($fp);
196                 phimail_logit(0, "database problem updating: ".$val[1]);
197                 return;
198             }
200             if (!$success) {
201                    //notify local user of failure
202                    $sql = "SELECT username FROM users WHERE id = ?";
203                    $res2 = sqlStatementNoLog($sql, array($msg['user_id']));
204                    $fail_user = ($res2 === false || ($user_row = sqlFetchArray($res2)) === false) ?
205                 xl('unknown (see log)') : $user_row['username'];
206                    $fail_notice = xl('Sent by:') . ' ' . $fail_user . '(' . $msg['user_id'] . ') ' . xl('on') . ' ' . $msg['create_ts']
207                 . "\n" . xl('Sent to:') . ' ' . $msg['recipient'] . "\n" . xl('Server message:') . ' ' . $ret;
208                 phimail_notify(xl('Direct Messaging Send Failure.'), $fail_notice);
209                    $pnote_id = addPnote(
210                        $msg['patient_id'],
211                        xl("FAILURE NOTICE: Direct Message Send Failed.") . "\n\n$fail_notice\n",
212                        0,
213                        1,
214                        "Unassigned",
215                        $notifyUsername,
216                        "",
217                        "New",
218                        "phimail-service"
219                    );
220             }
222          //done with this status message
223             $ret = phimail_write_expect_OK($fp, "OK\n");
224             if ($ret!==true) {
225                    phimail_close($fp);
226                 return;
227             }
228         } else if (substr($ret, 0, 4)=="MAIL") {
229             $val = explode(" ", trim($ret), 5); // MAIL recipient sender #attachments msg-id
230             $recipient=$val[1];
231             $sender=$val[2];
232             $att=(int)$val[3];
233             $msg_id=$val[4];
235             //request main message
236             $ret2 = phimail_write_expect_OK($fp, "SHOW 0\n");
237             if ($ret2!==true) {
238                 phimail_close($fp);
239                 return;
240             }
242         //get message headers
243             $hdrs="";
244             while (($next_hdr = fgets($fp, 1024)) != "\n") {
245                 $hdrs .= $next_hdr;
246             }
248             $mime_type=fgets($fp, 512);
249             $mime_info=explode(";", $mime_type);
250             $mime_type_main=strtolower($mime_info[0]);
252         //get main message body
253             $body_len=fgets($fp, 256);
254             $body=phimail_read_blob($fp, $body_len);
255             if ($body===false) {
256                    phimail_close($fp);
257                    return;
258             }
260             $att2=fgets($fp, 256);
261             if ($att2!=$att) { //safety for mismatch on attachments
262                    phimail_close($fp);
263                    return;
264             }
266         //get attachment info
267             if ($att>0) {
268                 for ($attnum=0; $attnum<$att; $attnum++) {
269                     if (($attinfo[$attnum]['name']=fgets($fp, 1024)) === false
270                     || ($attinfo[$attnum]['mime']=fgets($fp, 1024)) === false
271                     || ($attinfo[$attnum]['desc']=fgets($fp, 1024)) === false) {
272                              phimail_close($fp);
273                              return;
274                     }
275                 }
276             }
278         //main part gets stored as document if not plain text content
279         //(if plain text it will be the body of the final pnote)
280             $all_doc_ids = array();
281             $doc_id=0;
282             $att_detail="";
283             if ($mime_type_main != "text/plain") {
284                    $name = uniqid("dm-message-") . phimail_extension($mime_type_main);
285                    $doc_id = phimail_store($name, $mime_type_main, $body);
286                 if (!$doc_id) {
287                     phimail_close($fp);
288                     return;
289                 }
291                    $idnum=$doc_id['doc_id'];
292                    $all_doc_ids[] = $idnum;
293                    $url=$doc_id['url'];
294                    $url=substr($url, strrpos($url, "/")+1);
295                    $att_detail = "\n" . xl("Document") . " $idnum (\"$url\"; $mime_type_main; " .
296                   filesize($body) . " bytes) Main message body";
297             }
299         //download and store attachments
300             for ($attnum=0; $attnum<$att; $attnum++) {
301                 $ret2 = phimail_write_expect_OK($fp, "SHOW " . ($attnum+1) . "\n");
302                 if ($ret2!==true) {
303                     phimail_close($fp);
304                     return;
305                 }
307                //we can ignore next two lines (repeat of name and mime-type)
308                 if (($a1=fgets($fp, 512))===false || ($a2=fgets($fp, 512))===false) {
309                     phimail_close($fp);
310                     return;
311                 }
313                 $att_len = fgets($fp, 256); //length of file
314                 $attdata = phimail_read_blob($fp, $att_len);
315                 if ($attdata===false) {
316                     phimail_close($fp);
317                     return;
318                 }
320                 $attinfo[$attnum]['file']=$attdata;
322                 $req_name = trim($attinfo[$attnum]['name']);
323                 $req_name = (empty($req_name) ? $attdata : "dm-") . $req_name;
324                 $attinfo[$attnum]['mime'] = explode(";", trim($attinfo[$attnum]['mime']));
325                 $attmime = strtolower($attinfo[$attnum]['mime'][0]);
326                 $att_doc_id = phimail_store($req_name, $attmime, $attdata);
327                 if (!$att_doc_id) {
328                     phimail_close($fp);
329                     return;
330                 }
332                 $attinfo[$attnum]['doc_id']=$att_doc_id;
333                 $idnum=$att_doc_id['doc_id'];
334                 $all_doc_ids[] = $idnum;
335                 $url=$att_doc_id['url'];
336                 $url=substr($url, strrpos($url, "/")+1);
337                 $att_detail = $att_detail . "\n" . xl("Document") . " $idnum (\"$url\"; $attmime; " .
338                 filesize($attdata) . " bytes) " . trim($attinfo[$attnum]['desc']);
339             }
341             if ($att_detail != "") {
342                 $att_detail = "\n\n" . xl("The following documents were attached to this Direct message:") . $att_detail;
343             }
345             $ret2 = phimail_write_expect_OK($fp, "DONE\n"); //we'll check for failure after logging.
347         //logging only after succesful download, storage, and acknowledgement of message
348             $sql = "INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,user_id) " .
349             "VALUES ('R', ?, ?, ?, 'R', NOW(), ?)";
350             $res = sqlStatementNoLog($sql, array($msg_id,$sender,$recipient,phimail_service_userID()));
352             phimail_logit(1, $ret);
354         //alert appointed user about new message
355             switch ($mime_type_main) {
356                 case "text/plain":
357                     $body_text = @file_get_contents($body); //this was not uploaded as a document
358                     unlink($body);
359                     $pnote_id = addPnote(
360                         0,
361                         xl("Direct Message Received.") . "\n$hdrs\n$body_text$att_detail",
362                         0,
363                         1,
364                         "Unassigned",
365                         $notifyUsername,
366                         "",
367                         "New",
368                         "phimail-service"
369                     );
370                     break;
372                 default:
373                     $note = xl("Direct Message Received.") . "\n$hdrs\n"
374                     . xl("Message content is not plain text so it has been stored as a document.") . $att_detail;
375                     $pnote_id = addPnote(0, $note, 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
376                     break;
377             }
379             foreach ($all_doc_ids as $doc_id) {
380                 setGpRelation(1, $doc_id, 6, $pnote_id);
381             }
383             if ($ret2!==true) {
384                    phimail_close();
385                    return;
386             }
387         } else { //unrecognized or FAIL response
388             phimail_logit(0, "problem checking messages " . $ret);
389             phimail_close($fp);
390             return;
391         }
392     }
396  * Helper functions
397  */
398 function phimail_write($fp, $text)
400     fwrite($fp, $text);
401     fflush($fp);
404 function phimail_write_expect_OK($fp, $text)
406     phimail_write($fp, $text);
407     $ret = fgets($fp, 256);
408     if ($ret!="OK\n") { //unexpected error
409         phimail_close($fp);
410         return $ret;
411     }
413     return true;
416 function phimail_close($fp)
418     fwrite($fp, "BYE\n");
419     fflush($fp);
420     fclose($fp);
423 function phimail_logit($success, $text, $pid = 0, $event = "direct-message-check")
425     newEvent($event, "phimail-service", 0, $success, $text, $pid);
429  * Read a blob of data into a local temporary file
430  * @param $len number of bytes to read
431  * @return the temp filename, or FALSE if failure
432  */
433 function phimail_read_blob($fp, $len)
436     $fpath=$GLOBALS['temporary_files_dir'];
437     if (!@file_exists($fpath)) {
438         return false;
439     }
441     $name = uniqid("direct-");
442     $fn = $fpath . "/" . $name . ".dat";
443     $dup = 1;
444     while (file_exists($fn)) {
445         $fn = $fpath . "/" . $name . "." . $dup++ . ".dat";
446     }
448     $ff = @fopen($fn, "w");
449     if (!$ff) {
450         return false;
451     }
453     $bytes_left=$len;
454     $chunk_size=1024;
455     while (!feof($fp) && $bytes_left>0) {
456         if ($bytes_left < $chunk_size) {
457             $chunk_size = $bytes_left;
458         }
460         $chunk = fread($fp, $chunk_size);
461         if ($chunk===false || @fwrite($ff, $chunk)===false) {
462             @fclose($ff);
463             @unlink($fn);
464             return false;
465         }
467         $bytes_left -= strlen($chunk);
468     }
470     @fclose($ff);
471     return($fn);
475  * Return a suitable filename extension based on MIME-type
476  * (very limited, default is .dat)
477  */
478 function phimail_extension($mime)
480     $m=explode("/", $mime);
481     switch ($mime) {
482         case 'text/plain':
483             return (".txt");
484         default:
485     }
487     switch ($m[1]) {
488         case 'html':
489         case 'xml':
490         case 'pdf':
491             return (".".$m[1]);
492         default:
493             return (".dat");
494     }
497 function phimail_service_userID($name = 'phimail-service')
499     $sql = "SELECT id FROM users WHERE username=?";
500     if (($r = sqlStatementNoLog($sql, array($name))) === false ||
501        ($u = sqlFetchArray($r)) === false) {
502         $user=1; //default if we don't have a service user
503     } else {
504         $user = $u['id'];
505     }
507     return ($user);
512  * Registers an attachment or non-text message file using the existing Document structure
513  * @return Array(doc_id,URL) of the file as stored in documents table, false = failure
514  */
515 function phimail_store($name, $mime_type, $fn)
518     // Collect phimail user id
519     $user = phimail_service_userID();
521     // Import the document
522     $return = addNewDocument($name, $mime_type, $fn, 0, filesize($fn), $user, 'direct');
524     // Remove the temporary file
525     @unlink($fn);
527     // Return the result
528     return $return;
532  * Send an error notification or other alert to the notification address specified in globals.
533  * (notification email function modified from interface/drugs/dispense_drug.php)
534  * @return true if notification successfully sent, false otherwise
535  */
536 function phimail_notify($subj, $body)
538     $recipient = $GLOBALS['practice_return_email_path'];
539     if (empty($recipient)) {
540         return false;
541     }
543     $mail = new PHPMailer();
544     $mail->From = $recipient;
545     $mail->FromName = 'phiMail Gateway';
546     $mail->isMail();
547     $mail->Host = "localhost";
548     $mail->Mailer = "mail";
549     $mail->Body = $body;
550     $mail->Subject = $subj;
551     $mail->AddAddress($recipient);
552     return ($mail->Send());