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__) . "/sql.inc");
28 require_once(dirname(__FILE__) . "/pnotes.inc");
29 require_once(dirname(__FILE__) . "/../controllers/C_Document.class.php");
30 require_once(dirname(__FILE__) . "/documents.php");
33 * Connect to a phiMail Direct Messaging server and check for any incoming status
34 * messages related to previously transmitted messages or any new messages received.
37 function phimail_check() {
38 if ($GLOBALS['phimail_enable']==false) return; //for safety
40 $phimail_server=@parse_url($GLOBALS['phimail_server_address']);
41 $phimail_username=$GLOBALS['phimail_username'];
42 $phimail_password=$GLOBALS['phimail_password'];
43 switch ($phimail_server['scheme']) {
44 case "http": $server="tcp://".$phimail_server['host'];
46 case "https": $server="ssl://".$phimail_server['host'];
50 $fp=@fsockopen($server,$phimail_server['port']);
52 phimail_logit(0,"could not connect to server");
56 $ret = phimail_write_expect_OK($fp,"AUTH $phimail_username $phimail_password\n");
57 if($ret!==TRUE) return; //authentication error
60 phimail_write($fp,"CHECK\n");
63 if($ret=="NONE\n") { //nothing to process
65 phimail_logit(1,"message check completed");
68 else if(substr($ret,0,6)=="STATUS") {
69 //Format STATUS message-id status-code [additional-information]
70 $val=explode(" ",trim($ret),4);
71 $sql='SELECT * from direct_message_log WHERE msg_id = ?';
72 $res = sqlStatementNoLog($sql,array($val[1]));
73 if ($res===FALSE) { //database problem
75 phimail_logit(0,"database problem");
78 if (($msg=sqlFetchArray($res))===FALSE) {
79 //no match, so log it and move on (should never happen)
80 phimail_logit(0,"NO MATCH: ".$ret);
81 $ret = phimail_write_expect_OK($fp,"OK\n");
82 if($ret!==TRUE) return; else continue;
85 //if we get here, $msg contains the matching outgoing message record
86 if($val[2]=='failed') {
89 } else if ($val[2]=='dispatched') {
93 //unrecognized status, log it and move on (should never happen)
94 $ret = "UNKNOWN STATUS: ".$ret;
99 phimail_logit($success,$ret,$msg['patient_id']);
101 if (!isset($val[3])) $val[3]="";
102 $sql = "UPDATE direct_message_log SET status=?, status_ts=NOW(), status_info=? WHERE msg_type='S' AND msg_id=?";
103 $res = sqlStatementNoLog($sql,array($status,$val[3],$val[1]));
104 if ($res===FALSE) { //database problem
106 phimail_logit(0,"database problem updating: ".$val[1]);
111 phimail_notify( xl('Direct Messaging Send Failure.'), $ret);
114 //done with this status message
115 $ret = phimail_write_expect_OK($fp,"OK\n");
123 else if(substr($ret,0,4)=="MAIL") {
125 $val = explode(" ",trim($ret),5); // MAIL recipient sender #attachments msg-id
131 //request main message
132 $ret2 = phimail_write_expect_OK($fp,"SHOW 0\n");
138 //get message headers
140 while (($next_hdr = fgets($fp,1024)) != "\n")
143 $mime_type=fgets($fp,512);
144 $mime_info=explode(";",$mime_type);
145 $mime_type_main=strtolower($mime_info[0]);
147 //get main message body
148 $body_len=fgets($fp,256);
149 $body=phimail_read_blob($fp,$body_len);
155 $att2=fgets($fp,256);
156 if($att2!=$att) { //safety for mismatch on attachments
161 //get attachment info
163 for ($attnum=0;$attnum<$att;$attnum++) {
164 if( ($attinfo[$attnum]['name']=fgets($fp,1024)) === FALSE
165 || ($attinfo[$attnum]['mime']=fgets($fp,1024)) === FALSE
166 || ($attinfo[$attnum]['desc']=fgets($fp,1024)) === FALSE) {
173 //main part gets stored as document if not plain text content
174 //(if plain text it will be the body of the final pnote)
177 if ($mime_type_main != "text/plain") {
178 $name = uniqid("dm-message-") . phimail_extension($mime_type_main);
179 $doc_id = phimail_store($name,$mime_type_main,$body);
184 $idnum=$doc_id['doc_id'];
186 $url=substr($url,strrpos($url,"/")+1);
187 $att_detail = "\n" . xl ("Document") . " $idnum (\"$url\"; $mime_type_main; " .
188 filesize($body) . " bytes) Main message body";
191 //download and store attachments
192 for($attnum=0;$attnum<$att;$attnum++) {
193 $ret2 = phimail_write_expect_OK($fp,"SHOW " . ($attnum+1) . "\n");
199 //we can ignore next two lines (repeat of name and mime-type)
200 if ( ($a1=fgets($fp,512))===FALSE || ($a2=fgets($fp,512))===FALSE ) {
205 $att_len = fgets($fp,256); //length of file
206 $attdata = phimail_read_blob($fp,$att_len);
207 if ($attdata===FALSE) {
211 $attinfo[$attnum]['file']=$attdata;
213 $req_name = trim($attinfo[$attnum]['name']);
214 $req_name = (empty($req_name) ? $attdata : "dm-") . $req_name;
215 $attinfo[$attnum]['mime'] = explode(";",trim($attinfo[$attnum]['mime']));
216 $attmime = strtolower($attinfo[$attnum]['mime'][0]);
217 $att_doc_id = phimail_store($req_name, $attmime, $attdata);
222 $attinfo[$attnum]['doc_id']=$att_doc_id;
223 $idnum=$att_doc_id['doc_id'];
224 $url=$att_doc_id['url'];
225 $url=substr($url,strrpos($url,"/")+1);
226 $att_detail = $att_detail . "\n" . xl ("Document") . " $idnum (\"$url\"; $attmime; " .
227 filesize($attdata) . " bytes) " . trim($attinfo[$attnum]['desc']);
230 if ($att_detail != "")
231 $att_detail = "\n\n" . xl("The following documents were attached to this Direct message:") . $att_detail;
233 $ret2 = phimail_write_expect_OK($fp,"DONE\n"); //we'll check for failure after logging.
235 //logging only after succesful download, storage, and acknowledgement of message
236 $sql = "INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,user_id) " .
237 "VALUES ('R', ?, ?, ?, 'R', NOW(), ?)";
238 $res = sqlStatementNoLog($sql,array($msg_id,$sender,$recipient,phimail_service_userID()));
240 phimail_logit(1,$ret);
242 if(!($notifyUsername = $GLOBALS['phimail_notify'])) $notifyUsername='admin'; //fallback
244 //alert appointed user about new message
245 switch($mime_type_main) {
248 $body_text = @file_get_contents($body); //this was not uploaded as a document
250 $pnote_id = addPnote(0, xl("Direct Message Received.") . "\n$hdrs\n$body_text$att_detail",
251 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
255 $note = xl("Direct Message Received.") . "\n$hdrs\n"
256 . xl("Message content is not plain text so it has been stored as a document.") . $att_detail;
257 $pnote_id = addPnote(0, $note, 0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
268 else { //unrecognized or FAIL response
278 function phimail_write($fp,$text) {
283 function phimail_write_expect_OK($fp,$text) {
284 phimail_write($fp,$text);
285 $ret = fgets($fp,256);
286 if($ret!="OK\n") { //unexpected error
293 function phimail_close($fp) {
299 function phimail_logit($success,$text,$pid=0,$event="direct-message-check") {
300 newEvent($event,"phimail-service",0,$success,$text,$pid);
304 * Read a blob of data into a local temporary file
305 * @param $len number of bytes to read
306 * @return the temp filename, or FALSE if failure
308 function phimail_read_blob($fp,$len) {
310 $fpath=$GLOBALS['temporary_files_dir'];
311 if(!@file_exists($fpath)) {
314 $name = uniqid("direct-");
315 $fn = $fpath . "/" . $name . ".dat";
317 while(file_exists($fn)) {
318 $fn = $fpath . "/" . $name . "." . $dup++ . ".dat";
321 $ff = @fopen ($fn, "w");
322 if(!$ff) return FALSE;
326 while (!feof($fp) && $bytes_left>0) {
327 if ($bytes_left < $chunk_size ) $chunk_size = $bytes_left;
328 $chunk = fread($fp,$chunk_size);
329 if($chunk===FALSE || @fwrite($ff,$chunk)===FALSE) {
334 $bytes_left -= strlen($chunk);
341 * Return a suitable filename extension based on MIME-type
342 * (very limited, default is .dat)
344 function phimail_extension($mime) {
345 $m=explode("/",$mime);
361 function phimail_service_userID($name='phimail-service') {
362 $sql = "SELECT id FROM users WHERE username=?";
363 if (($r = sqlStatementNoLog($sql,array($name))) === FALSE ||
364 ($u = sqlFetchArray($r)) === FALSE) {
365 $user=1; //default if we don't have a service user
374 * Registers an attachment or non-text message file using the existing Document structure
375 * @return Array(doc_id,URL) of the file as stored in documents table, false = failure
377 function phimail_store($name,$mime_type,$fn) {
379 // Collect phimail user id
380 $user = phimail_service_userID();
382 // Import the document
383 $return = addNewDocument($name,$mime_type,$fn,0,filesize($fn),$user,'direct');
385 // Remove the temporary file
393 * Send an error notification or other alert to the notification address specified in globals.
394 * (notification email function modified from interface/drugs/dispense_drug.php)
395 * @return true if notificaiton successfully sent, false otherwise
397 function phimail_notify($subj,$body) {
398 $recipient = $GLOBALS['practice_return_email_path'];
399 if (empty($recipient)) return false;
400 $mail = new PHPMailer();
401 $mail->SetLanguage("en", $GLOBALS['fileroot'] . "/library/" );
402 $mail->From = $recipient;
403 $mail->FromName = 'phiMail Gateway';
405 $mail->Host = "localhost";
406 $mail->Mailer = "mail";
408 $mail->Subject = $subject;
409 $mail->AddAddress($recipient);
410 return ($mail->Send());