Ubuntu Package modification - Added configuration of max_input_vars setting
[openemr.git] / library / direct_message_check.inc
blob968b32460e6f858533ae11f340ef432a22e64bf1
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");
32 /**
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.
35  */
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'];
45                break;
46        case "https": $server="ssl://".$phimail_server['host'];
47                break;
48        default: return;
49    }
50    $fp=@fsockopen($server,$phimail_server['port']);
51    if ($fp===false) {
52       phimail_logit(0,"could not connect to server");
53       return;
54    }
56    $ret = phimail_write_expect_OK($fp,"AUTH $phimail_username $phimail_password\n");
57    if($ret!==TRUE) return; //authentication error
59    while (1) {
60       phimail_write($fp,"CHECK\n");
61       $ret=fgets($fp,512);
63       if($ret=="NONE\n") { //nothing to process
64           phimail_close($fp);
65           phimail_logit(1,"message check completed");
66           return;
67       }
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
74              phimail_close($fp);
75              phimail_logit(0,"database problem");
76              return;
77           }
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; 
83           }
85           //if we get here, $msg contains the matching outgoing message record
86           if($val[2]=='failed') {
87              $success=0;
88              $status='F';
89           } else if ($val[2]=='dispatched') {
90              $success=1;
91              $status='D';
92           } else {
93              //unrecognized status, log it and move on (should never happen)
94              $ret = "UNKNOWN STATUS: ".$ret;
95              $success=0;
96              $status='U';
97           }
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
105              phimail_close($fp);
106              phimail_logit(0,"database problem updating: ".$val[1]);
107              return;
108           }
110           if(!$success) {
111              phimail_notify( xl('Direct Messaging Send Failure.'), $ret);
112           }
114           //done with this status message
115           $ret = phimail_write_expect_OK($fp,"OK\n");
116           if($ret!==TRUE) {
117              phimail_close($fp);
118              return;
119           } 
121       }
123       else if(substr($ret,0,4)=="MAIL") {
125          $val = explode(" ",trim($ret),5); // MAIL recipient sender #attachments msg-id
126          $recipient=$val[1];
127          $sender=$val[2];
128          $att=(int)$val[3];
129          $msg_id=$val[4];
131          //request main message
132          $ret2 = phimail_write_expect_OK($fp,"SHOW 0\n");
133          if($ret2!==TRUE) {
134             phimail_close($fp);
135             return;
136          }
138          //get message headers
139          $hdrs="";
140          while (($next_hdr = fgets($fp,1024)) != "\n") 
141             $hdrs .= $next_hdr;
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);
150          if ($body===FALSE) {
151            phimail_close($fp);
152            return;
153          }
155          $att2=fgets($fp,256);
156          if($att2!=$att) { //safety for mismatch on attachments
157             phimail_close($fp);
158             return;
159          }
161          //get attachment info
162          if($att>0) {
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) {
167                      phimail_close($fp);
168                      return;
169                 }
170              }
171           }
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)
175           $doc_id=0;
176           $att_detail="";
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);
180              if (!$doc_id) { 
181                 phimail_close($fp);
182                 return;
183              }
184              $idnum=$doc_id['doc_id']; 
185              $url=$doc_id['url']; 
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";
189           }
191           //download and store attachments
192           for($attnum=0;$attnum<$att;$attnum++) {
193              $ret2 = phimail_write_expect_OK($fp,"SHOW " . ($attnum+1) . "\n");
194              if ($ret2!==TRUE) {
195                 phimail_close($fp);
196                 return;
197              }
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 ) {
201                 phimail_close($fp);
202                 return;
203              }
205              $att_len = fgets($fp,256); //length of file
206              $attdata = phimail_read_blob($fp,$att_len);
207              if ($attdata===FALSE) {
208                 phimail_close($fp);
209                 return;
210              }
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);
218              if (!$att_doc_id) { 
219                 phimail_close($fp);
220                 return;
221              }
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']);
228          }
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
243          
244          //alert appointed user about new message
245          switch($mime_type_main) {
247            case "text/plain":
248              $body_text = @file_get_contents($body); //this was not uploaded as a document
249              unlink($body);
250              $pnote_id = addPnote(0, xl("Direct Message Received.") . "\n$hdrs\n$body_text$att_detail",
251                0, 1, "Unassigned", $notifyUsername, "", "New", "phimail-service");
252              break;
254            default:
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");
258              break;
260          }
262          if ($ret2!==TRUE) { 
263             phimail_close();
264             return; 
265          }
267       }
268       else { //unrecognized or FAIL response
269           phimail_close($fp);
270           return;
271       } 
272    }
276  * Helper functions
277  */
278 function phimail_write($fp,$text) {
279    fwrite($fp,$text);
280    fflush($fp);
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
287       phimail_close($fp);
288       return $ret;
289    }
290    return TRUE;
293 function phimail_close($fp) {
294    fwrite($fp,"BYE\n");
295    fflush($fp);
296    fclose($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
307  */
308 function phimail_read_blob($fp,$len) {
310    $fpath=$GLOBALS['temporary_files_dir'];
311    if(!@file_exists($fpath)) {
312      return FALSE;
313    }
314    $name = uniqid("direct-");
315    $fn = $fpath . "/" . $name . ".dat";
316    $dup = 1;
317    while(file_exists($fn)) {
318      $fn = $fpath . "/" . $name . "." . $dup++ . ".dat";
319    }
321    $ff = @fopen ($fn, "w");
322    if(!$ff) return FALSE;
324    $bytes_left=$len;
325    $chunk_size=1024;
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) {
330          @fclose($ff);
331          @unlink($fn);
332          return FALSE;
333       }
334       $bytes_left -= strlen($chunk);
335    }
336    @fclose($ff);
337    return($fn);
341  * Return a suitable filename extension based on MIME-type
342  * (very limited, default is .dat)
343  */
344 function phimail_extension($mime) {
345   $m=explode("/",$mime);
346   switch($mime) {
347         case 'text/plain': 
348                 return (".txt");
349         default:
350   }
351   switch($m[1]) {
352         case 'html':
353         case 'xml':
354         case 'pdf':
355                 return (".".$m[1]);
356         default:
357                 return (".dat");
358   }
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
366    } else {
367       $user = $u['id'];
368    }
369    return ($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
376  */
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
386     @unlink($fn);
388     // Return the result
389     return $return;
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
396  */
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';
404   $mail->isMail();
405   $mail->Host = "localhost";
406   $mail->Mailer = "mail";
407   $mail->Body = $body;
408   $mail->Subject = $subject;
409   $mail->AddAddress($recipient);
410   return ($mail->Send());