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