more organization of autoloaded files (#424)
[openemr.git] / library / direct_message_check.inc
blob4c9d1860b5420f512743bd6f78f726a2247576a0
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__) . "/../controllers/C_Document.class.php");
29 require_once(dirname(__FILE__) . "/documents.php");
30 require_once(dirname(__FILE__) . "/gprelations.inc.php");
32 /**
33  * Connect to a phiMail Direct Messaging server
34  */
36 function phimail_connect(&$phimail_error) {
38    if ($GLOBALS['phimail_enable'] == false) {
39       $phimail_error = 'C1';
40       return false; //for safety
41    }
43    $phimail_server = @parse_url($GLOBALS['phimail_server_address']);
44    $phimail_username = $GLOBALS['phimail_username'];
45    $phimail_password = $GLOBALS['phimail_password'];
46    $phimail_cafile = dirname(__FILE__) . '/../sites/' . $_SESSION['site_id']
47       . '/documents/phimail_server_pem/phimail_server.pem';
48    if (!file_exists($phimail_cafile)) $phimail_cafile='';
50    $phimail_secure = true;
51    switch ($phimail_server['scheme']) {
52        case "tcp":
53        case "http": $server = "tcp://".$phimail_server['host'];
54                $phimail_secure = false;
55                break;
56        case "https": $server = "ssl://" . $phimail_server['host']
57                . ':' . $phimail_server['port'];
58                break;
59        case "ssl":
60        case "sslv3":
61        case "tls": $server = $GLOBALS['phimail_server_address'];
62                break;
63        default: $phimail_error = 'C2';
64                return false;
65    }
66    if ($phimail_secure) {
67       $context = stream_context_create();
68       if ($phimail_cafile != '' &&
69             (!stream_context_set_option($context, 'ssl', 'verify_peer', true) ||
70              !stream_context_set_option($context, 'ssl', 'cafile', $phimail_cafile))) {
71          $phimail_error = 'C3';
72          return false;
73       }
74       $socket_tries = 0;
75       $fp = false;
76       while ($socket_tries < 3 && !$fp) {
77          $socket_tries++;
78          $fp = @stream_socket_client($server, $err1, $err2, 10,
79             STREAM_CLIENT_CONNECT, $context);
80       }
81       if (!$fp) {
82          if ($err1 == '111') $err2 = xl('Server may be offline');
83          if ($err2 == '') $err2 = xl('Connection error');
84          $phimail_error = "C4 $err1 ($err2)";
85       }
86    } else {
87       $fp = @fsockopen($server,$phimail_server['port']);
88    }
89    return $fp;
92 /**
93  * Connect to a phiMail Direct Messaging server and check for any incoming status
94  * messages related to previously transmitted messages or any new messages received.
95  */
97 function phimail_check() {
98    $fp = phimail_connect($err);
99    if ($fp===false) {
100       phimail_logit(0,xl('could not connect to server').' '.$err);
101       return;
102    }
103    $phimail_username = $GLOBALS['phimail_username'];
104    $phimail_password = $GLOBALS['phimail_password'];
106    $ret = phimail_write_expect_OK($fp,"AUTH $phimail_username $phimail_password\n");
107    if($ret!==TRUE) {
108       phimail_logit(0, "authentication error " . $ret);
109       return;
110    }
112    if(!($notifyUsername = $GLOBALS['phimail_notify'])) $notifyUsername='admin'; //fallback
114    while (1) {
115       phimail_write($fp,"CHECK\n");
116       $ret=fgets($fp,512);
118       if($ret=="NONE\n") { //nothing to process
119           phimail_close($fp);
120           phimail_logit(1,"message check completed");
121           return;
122       }
123       else if(substr($ret,0,6)=="STATUS") {
124           //Format STATUS message-id status-code [additional-information]
125           $val=explode(" ",trim($ret),4);
126           $sql='SELECT * from direct_message_log WHERE msg_id = ?';
127           $res = sqlStatementNoLog($sql,array($val[1]));
128           if ($res===FALSE) { //database problem
129              phimail_close($fp);
130              phimail_logit(0,"database problem");
131              return;
132           }
133           if (($msg=sqlFetchArray($res))===FALSE) {
134              //no match, so log it and move on (should never happen)
135              phimail_logit(0,"NO MATCH: ".$ret);
136              $ret = phimail_write_expect_OK($fp,"OK\n");
137              if($ret!==TRUE) return; else continue;
138           }
140           //if we get here, $msg contains the matching outgoing message record
141           if($val[2]=='failed') {
142              $success=0;
143              $status='F';
144           } else if ($val[2]=='dispatched') {
145              $success=1;
146              $status='D';
147           } else {
148              //unrecognized status, log it and move on (should never happen)
149              $ret = "UNKNOWN STATUS: ".$ret;
150              $success=0;
151              $status='U';
152           }
154           phimail_logit($success,$ret,$msg['patient_id']);
156           if (!isset($val[3])) $val[3]="";
157           $sql = "UPDATE direct_message_log SET status=?, status_ts=NOW(), status_info=? WHERE msg_type='S' AND msg_id=?";
158           $res = sqlStatementNoLog($sql,array($status,$val[3],$val[1]));
159           if ($res===FALSE) { //database problem
160              phimail_close($fp);
161              phimail_logit(0,"database problem updating: ".$val[1]);
162              return;
163           }
165           if (!$success) {
166              //notify local user of failure
167              $sql = "SELECT username FROM users WHERE id = ?";
168              $res2 = sqlStatementNoLog($sql, array($msg['user_id']));
169              $fail_user = ($res2 === FALSE || ($user_row = sqlFetchArray($res2)) === FALSE) ?
170                 xl('unknown (see log)') : $user_row['username'];
171              $fail_notice = xl('Sent by:') . ' ' . $fail_user . '(' . $msg['user_id'] . ') ' . xl('on') . ' ' . $msg['create_ts']
172                 . "\n" . xl('Sent to:') . ' ' . $msg['recipient'] . "\n" . xl('Server message:') . ' ' . $ret;
173              phimail_notify( xl('Direct Messaging Send Failure.'), $fail_notice);
174              $pnote_id = addPnote($msg['patient_id'],
175                 xl("FAILURE NOTICE: Direct Message Send Failed.") . "\n\n$fail_notice\n",
176                 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
177           }
179           //done with this status message
180           $ret = phimail_write_expect_OK($fp,"OK\n");
181           if($ret!==TRUE) {
182              phimail_close($fp);
183              return;
184           }
186       }
188       else if(substr($ret,0,4)=="MAIL") {
190          $val = explode(" ",trim($ret),5); // MAIL recipient sender #attachments msg-id
191          $recipient=$val[1];
192          $sender=$val[2];
193          $att=(int)$val[3];
194          $msg_id=$val[4];
196          //request main message
197          $ret2 = phimail_write_expect_OK($fp,"SHOW 0\n");
198          if($ret2!==TRUE) {
199             phimail_close($fp);
200             return;
201          }
203          //get message headers
204          $hdrs="";
205          while (($next_hdr = fgets($fp,1024)) != "\n")
206             $hdrs .= $next_hdr;
208          $mime_type=fgets($fp,512);
209          $mime_info=explode(";",$mime_type);
210          $mime_type_main=strtolower($mime_info[0]);
212          //get main message body
213          $body_len=fgets($fp,256);
214          $body=phimail_read_blob($fp,$body_len);
215          if ($body===FALSE) {
216            phimail_close($fp);
217            return;
218          }
220          $att2=fgets($fp,256);
221          if($att2!=$att) { //safety for mismatch on attachments
222             phimail_close($fp);
223             return;
224          }
226          //get attachment info
227          if($att>0) {
228             for ($attnum=0;$attnum<$att;$attnum++) {
229                 if(  ($attinfo[$attnum]['name']=fgets($fp,1024)) === FALSE
230                   || ($attinfo[$attnum]['mime']=fgets($fp,1024)) === FALSE
231                   || ($attinfo[$attnum]['desc']=fgets($fp,1024)) === FALSE) {
232                      phimail_close($fp);
233                      return;
234                 }
235              }
236           }
238           //main part gets stored as document if not plain text content
239           //(if plain text it will be the body of the final pnote)
240           $all_doc_ids = array();
241           $doc_id=0;
242           $att_detail="";
243           if ($mime_type_main != "text/plain") {
244              $name = uniqid("dm-message-") . phimail_extension($mime_type_main);
245              $doc_id = phimail_store($name,$mime_type_main,$body);
246              if (!$doc_id) {
247                 phimail_close($fp);
248                 return;
249              }
250              $idnum=$doc_id['doc_id'];
251              $all_doc_ids[] = $idnum;
252              $url=$doc_id['url'];
253              $url=substr($url,strrpos($url,"/")+1);
254              $att_detail = "\n" . xl ("Document") . " $idnum (\"$url\"; $mime_type_main; " .
255                 filesize($body) . " bytes) Main message body";
256           }
258           //download and store attachments
259           for($attnum=0;$attnum<$att;$attnum++) {
260              $ret2 = phimail_write_expect_OK($fp,"SHOW " . ($attnum+1) . "\n");
261              if ($ret2!==TRUE) {
262                 phimail_close($fp);
263                 return;
264              }
266              //we can ignore next two lines (repeat of name and mime-type)
267              if ( ($a1=fgets($fp,512))===FALSE || ($a2=fgets($fp,512))===FALSE ) {
268                 phimail_close($fp);
269                 return;
270              }
272              $att_len = fgets($fp,256); //length of file
273              $attdata = phimail_read_blob($fp,$att_len);
274              if ($attdata===FALSE) {
275                 phimail_close($fp);
276                 return;
277              }
278              $attinfo[$attnum]['file']=$attdata;
280              $req_name = trim($attinfo[$attnum]['name']);
281              $req_name = (empty($req_name) ? $attdata : "dm-") . $req_name;
282              $attinfo[$attnum]['mime'] = explode(";",trim($attinfo[$attnum]['mime']));
283              $attmime = strtolower($attinfo[$attnum]['mime'][0]);
284              $att_doc_id = phimail_store($req_name, $attmime, $attdata);
285              if (!$att_doc_id) {
286                 phimail_close($fp);
287                 return;
288              }
289              $attinfo[$attnum]['doc_id']=$att_doc_id;
290              $idnum=$att_doc_id['doc_id'];
291              $all_doc_ids[] = $idnum;
292              $url=$att_doc_id['url'];
293              $url=substr($url,strrpos($url,"/")+1);
294              $att_detail = $att_detail . "\n" . xl ("Document") . " $idnum (\"$url\"; $attmime; " .
295                  filesize($attdata) . " bytes) " . trim($attinfo[$attnum]['desc']);
296          }
298          if ($att_detail != "")
299            $att_detail = "\n\n" . xl("The following documents were attached to this Direct message:") . $att_detail;
301          $ret2 = phimail_write_expect_OK($fp,"DONE\n"); //we'll check for failure after logging.
303          //logging only after succesful download, storage, and acknowledgement of message
304          $sql = "INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,user_id) " .
305             "VALUES ('R', ?, ?, ?, 'R', NOW(), ?)";
306          $res = sqlStatementNoLog($sql,array($msg_id,$sender,$recipient,phimail_service_userID()));
308          phimail_logit(1,$ret);
310          //alert appointed user about new message
311          switch($mime_type_main) {
313            case "text/plain":
314              $body_text = @file_get_contents($body); //this was not uploaded as a document
315              unlink($body);
316              $pnote_id = addPnote(0, xl("Direct Message Received.") . "\n$hdrs\n$body_text$att_detail",
317                0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
318              break;
320            default:
321              $note = xl("Direct Message Received.") . "\n$hdrs\n"
322                 . xl("Message content is not plain text so it has been stored as a document.") . $att_detail;
323              $pnote_id = addPnote(0, $note, 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
324              break;
326          }
328          foreach ($all_doc_ids as $doc_id) setGpRelation(1, $doc_id, 6, $pnote_id);
330          if ($ret2!==TRUE) {
331             phimail_close();
332             return;
333          }
335       }
336       else { //unrecognized or FAIL response
337           phimail_logit(0, "problem checking messages " . $ret);
338           phimail_close($fp);
339           return;
340       }
341    }
345  * Helper functions
346  */
347 function phimail_write($fp,$text) {
348    fwrite($fp,$text);
349    fflush($fp);
352 function phimail_write_expect_OK($fp,$text) {
353    phimail_write($fp,$text);
354    $ret = fgets($fp,256);
355    if($ret!="OK\n") { //unexpected error
356       phimail_close($fp);
357       return $ret;
358    }
359    return TRUE;
362 function phimail_close($fp) {
363    fwrite($fp,"BYE\n");
364    fflush($fp);
365    fclose($fp);
368 function phimail_logit($success,$text,$pid=0,$event="direct-message-check") {
369    newEvent($event,"phimail-service",0,$success,$text,$pid);
373  * Read a blob of data into a local temporary file
374  * @param $len number of bytes to read
375  * @return the temp filename, or FALSE if failure
376  */
377 function phimail_read_blob($fp,$len) {
379    $fpath=$GLOBALS['temporary_files_dir'];
380    if(!@file_exists($fpath)) {
381      return FALSE;
382    }
383    $name = uniqid("direct-");
384    $fn = $fpath . "/" . $name . ".dat";
385    $dup = 1;
386    while(file_exists($fn)) {
387      $fn = $fpath . "/" . $name . "." . $dup++ . ".dat";
388    }
390    $ff = @fopen ($fn, "w");
391    if(!$ff) return FALSE;
393    $bytes_left=$len;
394    $chunk_size=1024;
395    while (!feof($fp) && $bytes_left>0) {
396       if ($bytes_left < $chunk_size ) $chunk_size = $bytes_left;
397       $chunk = fread($fp,$chunk_size);
398       if($chunk===FALSE || @fwrite($ff,$chunk)===FALSE) {
399          @fclose($ff);
400          @unlink($fn);
401          return FALSE;
402       }
403       $bytes_left -= strlen($chunk);
404    }
405    @fclose($ff);
406    return($fn);
410  * Return a suitable filename extension based on MIME-type
411  * (very limited, default is .dat)
412  */
413 function phimail_extension($mime) {
414   $m=explode("/",$mime);
415   switch($mime) {
416         case 'text/plain':
417                 return (".txt");
418         default:
419   }
420   switch($m[1]) {
421         case 'html':
422         case 'xml':
423         case 'pdf':
424                 return (".".$m[1]);
425         default:
426                 return (".dat");
427   }
430 function phimail_service_userID($name='phimail-service') {
431    $sql = "SELECT id FROM users WHERE username=?";
432    if (($r = sqlStatementNoLog($sql,array($name))) === FALSE ||
433        ($u = sqlFetchArray($r)) === FALSE) {
434       $user=1; //default if we don't have a service user
435    } else {
436       $user = $u['id'];
437    }
438    return ($user);
443  * Registers an attachment or non-text message file using the existing Document structure
444  * @return Array(doc_id,URL) of the file as stored in documents table, false = failure
445  */
446 function phimail_store($name,$mime_type,$fn) {
448     // Collect phimail user id
449     $user = phimail_service_userID();
451     // Import the document
452     $return = addNewDocument($name,$mime_type,$fn,0,filesize($fn),$user,'direct');
454     // Remove the temporary file
455     @unlink($fn);
457     // Return the result
458     return $return;
462  * Send an error notification or other alert to the notification address specified in globals.
463  * (notification email function modified from interface/drugs/dispense_drug.php)
464  * @return true if notification successfully sent, false otherwise
465  */
466 function phimail_notify($subj,$body) {
467   $recipient = $GLOBALS['practice_return_email_path'];
468   if (empty($recipient)) return false;
469   $mail = new PHPMailer();
470   $mail->From = $recipient;
471   $mail->FromName = 'phiMail Gateway';
472   $mail->isMail();
473   $mail->Host = "localhost";
474   $mail->Mailer = "mail";
475   $mail->Body = $body;
476   $mail->Subject = $subj;
477   $mail->AddAddress($recipient);
478   return ($mail->Send());