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__) . "/../controllers/C_Document.class.php");
29 require_once(dirname(__FILE__) . "/documents.php");
30 require_once(dirname(__FILE__) . "/gprelations.inc.php");
33 * Connect to a phiMail Direct Messaging server
36 function phimail_connect(&$phimail_error) {
38 if ($GLOBALS['phimail_enable'] == false) {
39 $phimail_error = 'C1';
40 return false; //for safety
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']) {
53 case "http": $server = "tcp://".$phimail_server['host'];
54 $phimail_secure = false;
56 case "https": $server = "ssl://" . $phimail_server['host']
57 . ':' . $phimail_server['port'];
61 case "tls": $server = $GLOBALS['phimail_server_address'];
63 default: $phimail_error = 'C2';
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';
76 while ($socket_tries < 3 && !$fp) {
78 $fp = @stream_socket_client($server, $err1, $err2, 10,
79 STREAM_CLIENT_CONNECT, $context);
82 if ($err1 == '111') $err2 = xl('Server may be offline');
83 if ($err2 == '') $err2 = xl('Connection error');
84 $phimail_error = "C4 $err1 ($err2)";
87 $fp = @fsockopen($server,$phimail_server['port']);
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.
97 function phimail_check() {
98 $fp = phimail_connect($err);
100 phimail_logit(0,xl('could not connect to server').' '.$err);
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");
108 phimail_logit(0, "authentication error " . $ret);
112 if(!($notifyUsername = $GLOBALS['phimail_notify'])) $notifyUsername='admin'; //fallback
115 phimail_write($fp,"CHECK\n");
118 if($ret=="NONE\n") { //nothing to process
120 phimail_logit(1,"message check completed");
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
130 phimail_logit(0,"database problem");
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;
140 //if we get here, $msg contains the matching outgoing message record
141 if($val[2]=='failed') {
144 } else if ($val[2]=='dispatched') {
148 //unrecognized status, log it and move on (should never happen)
149 $ret = "UNKNOWN STATUS: ".$ret;
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
161 phimail_logit(0,"database problem updating: ".$val[1]);
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");
179 //done with this status message
180 $ret = phimail_write_expect_OK($fp,"OK\n");
188 else if(substr($ret,0,4)=="MAIL") {
190 $val = explode(" ",trim($ret),5); // MAIL recipient sender #attachments msg-id
196 //request main message
197 $ret2 = phimail_write_expect_OK($fp,"SHOW 0\n");
203 //get message headers
205 while (($next_hdr = fgets($fp,1024)) != "\n")
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);
220 $att2=fgets($fp,256);
221 if($att2!=$att) { //safety for mismatch on attachments
226 //get attachment info
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) {
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();
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);
250 $idnum=$doc_id['doc_id'];
251 $all_doc_ids[] = $idnum;
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";
258 //download and store attachments
259 for($attnum=0;$attnum<$att;$attnum++) {
260 $ret2 = phimail_write_expect_OK($fp,"SHOW " . ($attnum+1) . "\n");
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 ) {
272 $att_len = fgets($fp,256); //length of file
273 $attdata = phimail_read_blob($fp,$att_len);
274 if ($attdata===FALSE) {
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);
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']);
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) {
314 $body_text = @file_get_contents($body); //this was not uploaded as a document
316 $pnote_id = addPnote(0, xl("Direct Message Received.") . "\n$hdrs\n$body_text$att_detail",
317 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
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");
328 foreach ($all_doc_ids as $doc_id) setGpRelation(1, $doc_id, 6, $pnote_id);
336 else { //unrecognized or FAIL response
337 phimail_logit(0, "problem checking messages " . $ret);
347 function phimail_write($fp,$text) {
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
362 function phimail_close($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
377 function phimail_read_blob($fp,$len) {
379 $fpath=$GLOBALS['temporary_files_dir'];
380 if(!@file_exists($fpath)) {
383 $name = uniqid("direct-");
384 $fn = $fpath . "/" . $name . ".dat";
386 while(file_exists($fn)) {
387 $fn = $fpath . "/" . $name . "." . $dup++ . ".dat";
390 $ff = @fopen ($fn, "w");
391 if(!$ff) return FALSE;
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) {
403 $bytes_left -= strlen($chunk);
410 * Return a suitable filename extension based on MIME-type
411 * (very limited, default is .dat)
413 function phimail_extension($mime) {
414 $m=explode("/",$mime);
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
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
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
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
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';
473 $mail->Host = "localhost";
474 $mail->Mailer = "mail";
476 $mail->Subject = $subj;
477 $mail->AddAddress($recipient);
478 return ($mail->Send());