3 * Background receive function for phiMail Direct Messaging service.
5 * This script is called by the background service manager
6 * at /library/ajax/execute_background_services.php
8 * Copyright (C) 2013 EMR Direct <http://www.emrdirect.com/>
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>;.
22 * @author EMR Direct <http://www.emrdirect.com/>
23 * @link http://www.open-emr.org
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");
32 * Connect to a phiMail Direct Messaging server
35 function phimail_connect(&$phimail_error) {
37 if ($GLOBALS['phimail_enable'] == false) {
38 $phimail_error = 'C1';
39 return false; //for safety
42 $phimail_server = @parse_url($GLOBALS['phimail_server_address']);
43 $phimail_username = $GLOBALS['phimail_username'];
44 $phimail_password = $GLOBALS['phimail_password'];
45 $phimail_cafile = dirname(__FILE__) . '/../sites/' . $_SESSION['site_id']
46 . '/documents/phimail_server_pem/phimail_server.pem';
47 if (!file_exists($phimail_cafile)) $phimail_cafile='';
49 $phimail_secure = true;
50 switch ($phimail_server['scheme']) {
52 case "http": $server = "tcp://".$phimail_server['host'];
53 $phimail_secure = false;
55 case "https": $server = "ssl://" . $phimail_server['host']
56 . ':' . $phimail_server['port'];
60 case "tls": $server = $GLOBALS['phimail_server_address'];
62 default: $phimail_error = 'C2';
65 if ($phimail_secure) {
66 $context = stream_context_create();
67 if ($phimail_cafile != '' &&
68 (!stream_context_set_option($context, 'ssl', 'verify_peer', true) ||
69 !stream_context_set_option($context, 'ssl', 'cafile', $phimail_cafile))) {
70 $phimail_error = 'C3';
75 while ($socket_tries < 3 && !$fp) {
77 $fp = @stream_socket_client($server, $err1, $err2, 10,
78 STREAM_CLIENT_CONNECT, $context);
81 if ($err1 == '111') $err2 = xl('Server may be offline');
82 if ($err2 == '') $err2 = xl('Connection error');
83 $phimail_error = "C4 $err1 ($err2)";
86 $fp = @fsockopen($server,$phimail_server['port']);
92 * Connect to a phiMail Direct Messaging server and check for any incoming status
93 * messages related to previously transmitted messages or any new messages received.
96 function phimail_check() {
97 $fp = phimail_connect($err);
99 phimail_logit(0,xl('could not connect to server').' '.$err);
102 $phimail_username = $GLOBALS['phimail_username'];
103 $phimail_password = $GLOBALS['phimail_password'];
105 $ret = phimail_write_expect_OK($fp,"AUTH $phimail_username $phimail_password\n");
107 phimail_logit(0, "authentication error " . $ret);
111 if(!($notifyUsername = $GLOBALS['phimail_notify'])) $notifyUsername='admin'; //fallback
114 phimail_write($fp,"CHECK\n");
117 if($ret=="NONE\n") { //nothing to process
119 phimail_logit(1,"message check completed");
122 else if(substr($ret,0,6)=="STATUS") {
123 //Format STATUS message-id status-code [additional-information]
124 $val=explode(" ",trim($ret),4);
125 $sql='SELECT * from direct_message_log WHERE msg_id = ?';
126 $res = sqlStatementNoLog($sql,array($val[1]));
127 if ($res===FALSE) { //database problem
129 phimail_logit(0,"database problem");
132 if (($msg=sqlFetchArray($res))===FALSE) {
133 //no match, so log it and move on (should never happen)
134 phimail_logit(0,"NO MATCH: ".$ret);
135 $ret = phimail_write_expect_OK($fp,"OK\n");
136 if($ret!==TRUE) return; else continue;
139 //if we get here, $msg contains the matching outgoing message record
140 if($val[2]=='failed') {
143 } else if ($val[2]=='dispatched') {
147 //unrecognized status, log it and move on (should never happen)
148 $ret = "UNKNOWN STATUS: ".$ret;
153 phimail_logit($success,$ret,$msg['patient_id']);
155 if (!isset($val[3])) $val[3]="";
156 $sql = "UPDATE direct_message_log SET status=?, status_ts=NOW(), status_info=? WHERE msg_type='S' AND msg_id=?";
157 $res = sqlStatementNoLog($sql,array($status,$val[3],$val[1]));
158 if ($res===FALSE) { //database problem
160 phimail_logit(0,"database problem updating: ".$val[1]);
165 //notify local user of failure
166 $sql = "SELECT username FROM users WHERE id = ?";
167 $res2 = sqlStatementNoLog($sql, array($msg['user_id']));
168 $fail_user = ($res2 === FALSE || ($user_row = sqlFetchArray($res2)) === FALSE) ?
169 xl('unknown (see log)') : $user_row['username'];
170 $fail_notice = xl('Sent by:') . ' ' . $fail_user . '(' . $msg['user_id'] . ') ' . xl('on') . ' ' . $msg['create_ts']
171 . "\n" . xl('Sent to:') . ' ' . $msg['recipient'] . "\n" . xl('Server message:') . ' ' . $ret;
172 phimail_notify( xl('Direct Messaging Send Failure.'), $fail_notice);
173 $pnote_id = addPnote($msg['patient_id'],
174 xl("FAILURE NOTICE: Direct Message Send Failed.") . "\n\n$fail_notice\n",
175 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
178 //done with this status message
179 $ret = phimail_write_expect_OK($fp,"OK\n");
187 else if(substr($ret,0,4)=="MAIL") {
189 $val = explode(" ",trim($ret),5); // MAIL recipient sender #attachments msg-id
195 //request main message
196 $ret2 = phimail_write_expect_OK($fp,"SHOW 0\n");
202 //get message headers
204 while (($next_hdr = fgets($fp,1024)) != "\n")
207 $mime_type=fgets($fp,512);
208 $mime_info=explode(";",$mime_type);
209 $mime_type_main=strtolower($mime_info[0]);
211 //get main message body
212 $body_len=fgets($fp,256);
213 $body=phimail_read_blob($fp,$body_len);
219 $att2=fgets($fp,256);
220 if($att2!=$att) { //safety for mismatch on attachments
225 //get attachment info
227 for ($attnum=0;$attnum<$att;$attnum++) {
228 if( ($attinfo[$attnum]['name']=fgets($fp,1024)) === FALSE
229 || ($attinfo[$attnum]['mime']=fgets($fp,1024)) === FALSE
230 || ($attinfo[$attnum]['desc']=fgets($fp,1024)) === FALSE) {
237 //main part gets stored as document if not plain text content
238 //(if plain text it will be the body of the final pnote)
239 $all_doc_ids = array();
242 if ($mime_type_main != "text/plain") {
243 $name = uniqid("dm-message-") . phimail_extension($mime_type_main);
244 $doc_id = phimail_store($name,$mime_type_main,$body);
249 $idnum=$doc_id['doc_id'];
250 $all_doc_ids[] = $idnum;
252 $url=substr($url,strrpos($url,"/")+1);
253 $att_detail = "\n" . xl ("Document") . " $idnum (\"$url\"; $mime_type_main; " .
254 filesize($body) . " bytes) Main message body";
257 //download and store attachments
258 for($attnum=0;$attnum<$att;$attnum++) {
259 $ret2 = phimail_write_expect_OK($fp,"SHOW " . ($attnum+1) . "\n");
265 //we can ignore next two lines (repeat of name and mime-type)
266 if ( ($a1=fgets($fp,512))===FALSE || ($a2=fgets($fp,512))===FALSE ) {
271 $att_len = fgets($fp,256); //length of file
272 $attdata = phimail_read_blob($fp,$att_len);
273 if ($attdata===FALSE) {
277 $attinfo[$attnum]['file']=$attdata;
279 $req_name = trim($attinfo[$attnum]['name']);
280 $req_name = (empty($req_name) ? $attdata : "dm-") . $req_name;
281 $attinfo[$attnum]['mime'] = explode(";",trim($attinfo[$attnum]['mime']));
282 $attmime = strtolower($attinfo[$attnum]['mime'][0]);
283 $att_doc_id = phimail_store($req_name, $attmime, $attdata);
288 $attinfo[$attnum]['doc_id']=$att_doc_id;
289 $idnum=$att_doc_id['doc_id'];
290 $all_doc_ids[] = $idnum;
291 $url=$att_doc_id['url'];
292 $url=substr($url,strrpos($url,"/")+1);
293 $att_detail = $att_detail . "\n" . xl ("Document") . " $idnum (\"$url\"; $attmime; " .
294 filesize($attdata) . " bytes) " . trim($attinfo[$attnum]['desc']);
297 if ($att_detail != "")
298 $att_detail = "\n\n" . xl("The following documents were attached to this Direct message:") . $att_detail;
300 $ret2 = phimail_write_expect_OK($fp,"DONE\n"); //we'll check for failure after logging.
302 //logging only after succesful download, storage, and acknowledgement of message
303 $sql = "INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,user_id) " .
304 "VALUES ('R', ?, ?, ?, 'R', NOW(), ?)";
305 $res = sqlStatementNoLog($sql,array($msg_id,$sender,$recipient,phimail_service_userID()));
307 phimail_logit(1,$ret);
309 //alert appointed user about new message
310 switch($mime_type_main) {
313 $body_text = @file_get_contents($body); //this was not uploaded as a document
315 $pnote_id = addPnote(0, xl("Direct Message Received.") . "\n$hdrs\n$body_text$att_detail",
316 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
320 $note = xl("Direct Message Received.") . "\n$hdrs\n"
321 . xl("Message content is not plain text so it has been stored as a document.") . $att_detail;
322 $pnote_id = addPnote(0, $note, 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
327 foreach ($all_doc_ids as $doc_id) setGpRelation(1, $doc_id, 6, $pnote_id);
335 else { //unrecognized or FAIL response
336 phimail_logit(0, "problem checking messages " . $ret);
346 function phimail_write($fp,$text) {
351 function phimail_write_expect_OK($fp,$text) {
352 phimail_write($fp,$text);
353 $ret = fgets($fp,256);
354 if($ret!="OK\n") { //unexpected error
361 function phimail_close($fp) {
367 function phimail_logit($success,$text,$pid=0,$event="direct-message-check") {
368 newEvent($event,"phimail-service",0,$success,$text,$pid);
372 * Read a blob of data into a local temporary file
373 * @param $len number of bytes to read
374 * @return the temp filename, or FALSE if failure
376 function phimail_read_blob($fp,$len) {
378 $fpath=$GLOBALS['temporary_files_dir'];
379 if(!@file_exists($fpath)) {
382 $name = uniqid("direct-");
383 $fn = $fpath . "/" . $name . ".dat";
385 while(file_exists($fn)) {
386 $fn = $fpath . "/" . $name . "." . $dup++ . ".dat";
389 $ff = @fopen ($fn, "w");
390 if(!$ff) return FALSE;
394 while (!feof($fp) && $bytes_left>0) {
395 if ($bytes_left < $chunk_size ) $chunk_size = $bytes_left;
396 $chunk = fread($fp,$chunk_size);
397 if($chunk===FALSE || @fwrite($ff,$chunk)===FALSE) {
402 $bytes_left -= strlen($chunk);
409 * Return a suitable filename extension based on MIME-type
410 * (very limited, default is .dat)
412 function phimail_extension($mime) {
413 $m=explode("/",$mime);
429 function phimail_service_userID($name='phimail-service') {
430 $sql = "SELECT id FROM users WHERE username=?";
431 if (($r = sqlStatementNoLog($sql,array($name))) === FALSE ||
432 ($u = sqlFetchArray($r)) === FALSE) {
433 $user=1; //default if we don't have a service user
442 * Registers an attachment or non-text message file using the existing Document structure
443 * @return Array(doc_id,URL) of the file as stored in documents table, false = failure
445 function phimail_store($name,$mime_type,$fn) {
447 // Collect phimail user id
448 $user = phimail_service_userID();
450 // Import the document
451 $return = addNewDocument($name,$mime_type,$fn,0,filesize($fn),$user,'direct');
453 // Remove the temporary file
461 * Send an error notification or other alert to the notification address specified in globals.
462 * (notification email function modified from interface/drugs/dispense_drug.php)
463 * @return true if notification successfully sent, false otherwise
465 function phimail_notify($subj,$body) {
466 $recipient = $GLOBALS['practice_return_email_path'];
467 if (empty($recipient)) return false;
468 $mail = new PHPMailer();
469 $mail->From = $recipient;
470 $mail->FromName = 'phiMail Gateway';
472 $mail->Host = "localhost";
473 $mail->Mailer = "mail";
475 $mail->Subject = $subj;
476 $mail->AddAddress($recipient);
477 return ($mail->Send());