Brought in bootstrap-rtl and validate.js packages via bower for Matrix's patient...
[openemr.git] / myportal / soap_service / server_med_rec.php
bloba7316db38cc1de43fff7d96717cb6e6f62469af5
1 <?php
2 // +-----------------------------------------------------------------------------+
3 // Copyright (C) 2011 Z&H Consultancy Services Private Limited <sam@zhservices.com>
4 //
5 //
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
18 // A copy of the GNU General Public License is included along with this program:
19 // openemr/interface/login/GnuGPL.html
20 // For more information write to the Free Software
21 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 //
23 // Author: Eldho Chacko <eldho@zhservices.com>
24 // Jacob T Paul <jacob@zhservices.com>
26 // +------------------------------------------------------------------------------+
28 //SANITIZE ALL ESCAPES
29 $sanitize_all_escapes=true;
32 //STOP FAKE REGISTER GLOBALS
33 $fake_register_globals=false;
36 require_once("server_audit.php");
37 class Userforms extends UserAudit{
41 public function issue_type($data){
42 if(UserService::valid($data[0])=='existingpatient'){
43 global $ISSUE_TYPES;
44 require_once("../../library/lists.inc");
45 return $ISSUE_TYPES;
47 else{
48 throw new SoapFault("Server", "credentials failed");
54 public function print_report($data){
55 global $pid;
56 if(UserService::valid($data[0])=='existingpatient'){
57 $repArr = $data[1];
58 $type = $data[3];
59 global $ISSUE_TYPES;
60 require_once("../../library/forms.inc");
61 require_once("../../library/billing.inc");
62 require_once("../../library/pnotes.inc");
63 require_once("../../library/patient.inc");
64 require_once("../../library/options.inc.php");
65 require_once("../../library/acl.inc");
66 require_once("../../library/lists.inc");
67 require_once("../../library/report.inc");
68 require_once("../../library/classes/Document.class.php");
69 require_once("../../library/classes/Note.class.php");
70 require_once("../../library/formatting.inc.php");
71 require_once("../../custom/code_types.inc.php");
72 foreach($repArr as $value){
73 ob_start();
74 if($type=="profile"){
75 $this->getIncudes($value);
76 $out .= ob_get_clean();
78 else{
79 if($type=='issue')
80 $this->getIid($value);
81 if($type=='forms')
82 $this->getforms($value);
83 $out .= ob_get_clean();
87 return $out;
89 else{
90 throw new SoapFault("Server", "credentials failed");
97 public function print_ccr_report($data){
98 if(UserService::valid($data[0])=='existingpatient'){
99 $ccraction = $data[1];
100 $raw = $data[2];
101 require_once("../../ccr/createCCR.php");
102 ob_start();
103 createCCR($ccraction,$raw);
104 $html = ob_get_clean();
105 if($ccraction=='viewccd')
108 $html = preg_replace('/<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD HTML 4.01\/\/EN" "http:\/\/www.w3.org\/TR\/html4\/strict.dtd">/','',$html);
109 $pos1 = strpos($html,'body {');
110 $pos2 = strpos($html,'.h1center');
111 $tes = substr("$html",$pos1,($pos2-$pos1));
112 $html = str_replace($tes,'',$html);
113 $html = str_replace('h3>','h2>',$html);
114 $html = base64_encode($html);
116 else{
117 $pos1 = strpos($html,'*{');
118 $pos2 = strpos($html,'h1');
119 $tes = substr("$html",$pos1,($pos2-$pos1));
120 $html = str_replace($tes,'',$html);
122 return $html;
124 else{
125 throw new SoapFault("Server", "credentials failed");
129 //Return the forms requested from Portal.
131 private function getforms($fId){
132 global $pid;
133 $GLOBALS['pid'] = $pid;
134 $inclookupres = sqlStatement("SELECT DISTINCT formdir FROM forms WHERE pid = ? AND deleted=0",array($pid));
135 while($result = sqlFetchArray($inclookupres)) {
136 $formdir = $result['formdir'];
137 if (substr($formdir,0,3) == 'LBF')
138 include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
139 else
140 include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
142 $N = 6;
143 $inclookupres = sqlStatement("SELECT encounter,form_id,formdir,id FROM forms WHERE pid = ? AND deleted=0
144 AND id =? ",array($pid,$fId));
145 while($result = sqlFetchArray($inclookupres)) {
146 $form_encounter=$result['encounter'];
147 $form_id=$result['form_id'];
148 $formdir = $result['formdir'];
149 $id=$result['id'];
150 ob_start();
151 if (substr($formdir,0,3) == 'LBF')
152 call_user_func("lbf_report", $pid, $form_encounter, $N, $form_id, $formdir);
153 else
154 call_user_func($formdir . "_report", $pid, $form_encounter, $N, $form_id);
155 $out=ob_get_clean();
156 ?> <table>
157 <tr class=text>
158 <th><?php echo htmlspecialchars($formdir,ENT_QUOTES);?></th>
159 </tr>
160 </table>
161 <?php echo $out;?>
162 <?php
168 private function getIid($val){
169 global $pid;
170 global $ISSUE_TYPES;
171 $inclookupres = sqlStatement("SELECT DISTINCT formdir FROM forms WHERE pid = ? AND deleted=?",array($pid,0));
172 while($result = sqlFetchArray($inclookupres)) {
173 $formdir = $result['formdir'];
174 if (substr($formdir,0,3) == 'LBF')
175 include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
176 else
177 include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
180 <tr class=text>
181 <td></td>
182 <td>
183 <?php
184 $irow = sqlQuery("SELECT type, title, comments, diagnosis FROM lists WHERE id =? ",array($val));
185 $diagnosis = $irow['diagnosis'];
187 if ($prevIssueType != $irow['type'])
189 $disptype = $ISSUE_TYPES[$irow['type']][0];
191 <div class='issue_type' style='font-weight: bold;'><?php echo htmlspecialchars($disptype,ENT_QUOTES);?>:</div>
192 <?php
193 $prevIssueType = $irow['type'];
196 <div class='text issue'>
197 <span class='issue_title'><?php echo htmlspecialchars($irow['title'],ENT_QUOTES);?>:</span>
198 <span class='issue_comments'><?php echo htmlspecialchars($irow['comments'],ENT_QUOTES);?></span>
199 <?php
200 if ($diagnosis)
203 <div class='text issue_diag'>
204 <span class='bold'>[<?php echo htmlspecialchars(xl('Diagnosis'),ENT_QUOTES);?>]</span><br>
205 <?php
206 $dcodes = explode(";", $diagnosis);
207 foreach ($dcodes as $dcode)
210 <span class='italic'><?php echo htmlspecialchars($dcode,ENT_QUOTES);?></span>:
211 <?php
212 echo htmlspecialchars(lookup_code_descriptions($dcode),ENT_QUOTES);
214 <br>
215 <?php
218 </div>
219 <?php
221 if ($irow['type'] == 'ippf_gcac')
224 <table>
225 <?php
226 display_layout_rows('GCA', sqlQuery("SELECT * FROM lists_ippf_gcac WHERE id = ?",array($rowid)));
229 </table>
230 <?php
232 else if ($irow['type'] == 'contraceptive')
235 <table>
236 <?php
237 display_layout_rows('CON', sqlQuery("SELECT * FROM lists_ippf_con WHERE id = ?",array($rowid)));
239 </table>
240 <?php
243 </div>
244 <?php
246 </td>
247 <?php
253 private function getIncudes($val){
254 global $pid;
255 if ($val == "demographics")
258 <hr />
259 <div class='text demographics' id='DEM'>
260 <?php
261 // printRecDataOne($patient_data_array, getRecPatientData ($pid), $N);
262 $result1 = getPatientData($pid);
263 $result2 = getEmployerData($pid);
265 <table>
266 <tr><td><h6><?php echo htmlspecialchars(xl('Patient Data').":",ENT_QUOTES);?></h6></td></tr>
267 <?php
268 display_layout_rows('DEM', $result1, $result2);
270 </table>
271 </div>
272 <?php
274 elseif ($val == "history")
277 <hr />
278 <div class='text history' id='HIS'>
279 <?php
280 $result1 = getHistoryData($pid);
282 <table>
283 <tr><td><h6><?php echo htmlspecialchars(xl('History Data').":",ENT_QUOTES);?></h6></td></tr>
284 <?php
285 display_layout_rows('HIS', $result1);
287 </table>
288 </div>
289 <?php
291 elseif ($val == "insurance")
294 <hr />
295 <div class='text insurance'>";
296 <h6><?php echo htmlspecialchars(xl('Insurance Data').":",ENT_QUOTES);?></h6>
297 <br><span class=bold><?php echo htmlspecialchars(xl('Primary Insurance Data').":",ENT_QUOTES);?></span><br>
298 <?php
299 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"primary"), $N);
301 <span class=bold><?php echo htmlspecialchars(xl('Secondary Insurance Data').":",ENT_QUOTES);?></span><br>
302 <?php
303 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"secondary"), $N);
305 <span class=bold><?php echo htmlspecialchars(xl('Tertiary Insurance Data').":",ENT_QUOTES);?></span><br>
306 <?php
307 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"tertiary"), $N);
309 </div>
310 <?php
312 elseif ($val == "billing")
315 <hr />
316 <div class='text billing'>
317 <h6><?php echo htmlspecialchars(xl('Billing Information').":",ENT_QUOTES);?></h6>
318 <?php
319 if (count($ar['newpatient']) > 0) {
320 $billings = array();
322 <table>
323 <tr><td width='400' class='bold'><?php echo htmlspecialchars(xl('Code'),ENT_QUOTES);?></td><td class='bold'><?php echo htmlspecialchars(xl('Fee'),ENT_QUOTES);?></td></tr>
324 <?php
325 $total = 0.00;
326 $copays = 0.00;
327 foreach ($ar['newpatient'] as $be) {
328 $ta = split(":",$be);
329 $billing = getPatientBillingEncounter($pid,$ta[1]);
330 $billings[] = $billing;
331 foreach ($billing as $b) {
333 <tr>
334 <td class=text>
335 <?php
336 echo htmlspecialchars($b['code_type'],ENT_QUOTES) . ":\t" .htmlspecialchars( $b['code'],ENT_QUOTES) . "&nbsp;". htmlspecialchars($b['modifier'],ENT_QUOTES) . "&nbsp;&nbsp;&nbsp;" . htmlspecialchars($b['code_text'],ENT_QUOTES) . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
338 </td>
339 <td class=text>
340 <?php
341 echo htmlspecialchars(oeFormatMoney($b['fee']),ENT_QUOTES);
343 </td>
344 </tr>
345 <?php
346 $total += $b['fee'];
347 if ($b['code_type'] == "COPAY") {
348 $copays += $b['fee'];
352 echo "<tr><td>&nbsp;</td></tr>";
353 echo "<tr><td class=bold>".htmlspecialchars(xl('Sub-Total'),ENT_QUOTES)."</td><td class=text>" . htmlspecialchars(oeFormatMoney($total + abs($copays)),ENT_QUOTES) . "</td></tr>";
354 echo "<tr><td class=bold>".htmlspecialchars(xl('Paid'),ENT_QUOTES)."</td><td class=text>" . htmlspecialchars(oeFormatMoney(abs($copays)),ENT_QUOTES) . "</td></tr>";
355 echo "<tr><td class=bold>".htmlspecialchars(xl('Total'),ENT_QUOTES)."</td><td class=text>" .htmlspecialchars(oeFormatMoney($total),ENT_QUOTES) . "</td></tr>";
356 echo "</table>";
357 echo "<pre>";
358 //print_r($billings);
359 echo "</pre>";
360 } else {
361 printPatientBilling($pid);
363 echo "</div>\n"; // end of billing DIV
365 elseif ($val == "immunizations")
369 <hr />
370 <div class='text immunizations'>
371 <h6><?php echo htmlspecialchars(xl('Patient Immunization').":",ENT_QUOTES);?></h6>
372 <?php
373 $sql = "select i1.immunization_id as immunization_id, if(i1.administered_date,concat(i1.administered_date,' - ') ,substring(i1.note,1,20) ) as immunization_data from immunizations i1 where i1.patient_id = ? order by administered_date desc";
374 $result = sqlStatement($sql,array($pid));
375 while ($row=sqlFetchArray($result)) {
376 echo htmlspecialchars($row{'immunization_data'},ENT_QUOTES);
377 echo generate_display_field(array('data_type'=>'1','list_id'=>'immunizations'), $row['immunization_id']);
379 <br>
380 <?php
383 </div>
384 <?php
387 elseif ($val == "batchcom")
390 <hr />
391 <div class='text transactions'>
392 <h6><?php htmlspecialchars(xl('Patient Communication sent').":",ENT_QUOTES);?></h6>
393 <?php
394 $sql="SELECT concat( 'Messsage Type: ', batchcom.msg_type, ', Message Subject: ', batchcom.msg_subject, ', Sent on:', batchcom.msg_date_sent ) AS batchcom_data, batchcom.msg_text, concat( users.fname, users.lname ) AS user_name FROM `batchcom` JOIN `users` ON users.id = batchcom.sent_by WHERE batchcom.patient_id=?";
395 $result = sqlStatement($sql,array($pid));
396 while ($row=sqlFetchArray($result)) {
397 echo htmlspecialchars($row{'batchcom_data'}.", ".xl('By').": ".$row{'user_name'},ENT_QUOTES);
399 <br><?php echo htmlspecialchars(xl('Text'),ENT_QUOTES);?>:<br><?php echo htmlspecialchars($row{'msg_txt'},ENT_QUOTES);?><br>
400 <?php
403 </div>
404 <?php
406 elseif ($val == "notes")
409 <hr />
410 <div class='text notes'>
411 <h6><?php echo htmlspecialchars(xl('Patient Notes').":",ENT_QUOTES);?></h6>
412 <?php
413 printPatientNotes($pid);
415 </div>
416 <?php
418 elseif ($val == "transactions")
421 <hr />
422 <div class='text transactions'>
423 <h6><?php echo htmlspecialchars(xl('Patient Transactions').":",ENT_QUOTES);?></h6>
424 <?php
425 printPatientTransactions($pid);
427 </div>
428 <?php
433 * Method to fetch CCDA
434 * @param type $data
435 * @return type
437 public function ccdaFetching($data)
439 global $pid;
440 global $server_url;
442 if (UserService::valid($data[0])=='existingpatient') {
443 if ($this->checkModuleInstalled($moduleName = 'Carecoordination')) {
444 $site_id = $data[0][0];
445 try {
446 $ch = curl_init();
447 $url = $server_url . "/interface/modules/zend_modules/public/encounterccdadispatch/index?cron=1&pid=$pid&site=$site_id";
449 curl_setopt($ch, CURLOPT_URL, $url);
450 curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
451 curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
452 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
453 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
454 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
455 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
456 $result = curl_exec($ch) or die(curl_error($ch));
457 curl_close($ch);
459 catch (Exception $e) {
463 try {
464 $event = isset ($data['event']) ? $data['event'] : 'patient-record';
465 $menu_item = isset($data['menu_item']) ? $data['menu_item'] : 'Dashboard';
466 newEvent($event, 1, '', 1, '', $pid,$log_from = 'patient-portal', $menu_item );
467 }catch (Exception $e) {
470 return $result;
472 else {
473 return '<?xml version="1.0" encoding="UTF-8"?>
474 <note>
475 <heading>WARNING!</heading>
476 <body>Unable to fetch CCDA Carecoordination module not installed!</body>
477 </note>';
480 else {
481 return '<?xml version="1.0" encoding="UTF-8"?>
482 <note>
483 <heading>WARNING!</heading>
484 <body>Existing patient checking failed!</body>
485 </note>';
487 return '<?xml version="1.0" encoding="UTF-8"?>
488 <note>
489 <heading>WARNING!</heading>
490 <body>Un known error occured</body>
491 </note>';
494 public function checkModuleInstalled($moduleName = 'Carecoordination')
496 $sql = "SELECT mod_id FROM modules WHERE mod_name = ? AND mod_active = '1'";
497 $res = sqlStatement($sql, array($moduleName));
498 $row = sqlFetchArray($res);
499 return !empty($row);
503 * @param mysql_resource - $inputArray - mysql query result
504 * @param string - $rootElementName - root element name
505 * @param string - $childElementName - child element name
507 public function arrayToXml($inputArray, $rootElementName = 'root', $childElementName = 'RowItem')
509 $xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
510 $xmlData .= "<" . $rootElementName . ">";
511 foreach ($inputArray as $rowItem) {
512 $xmlData .= "<" . $childElementName . ">";
513 foreach($rowItem as $fieldName => $fieldValue) {
514 $xmlData .= "<" . $fieldName . ">";
515 $xmlData .= !empty($fieldValue) ? $fieldValue : "null";
516 $xmlData .= "</" . $fieldName . ">";
518 $xmlData .= "</" . $childElementName . ">";
520 $xmlData .= "</" . $rootElementName . ">";
522 return $xmlData;
527 * @param type $data
528 * @return type
530 public function getEventLog($data)
532 global $pid;
533 if (UserService::valid($data[0])=='existingpatient') {
534 $date1 = $data['start_date'];
535 $date2 = $data['end_date'];
536 $keyword = $data['keyword'];
537 $arrBinds = array();
538 $cols = "DISTINCT log.date, event, user, groupname, patient_id, success, comments,checksum,crt_user";
539 $sql = "SELECT $cols, CONCAT(fname, ' ', lname) as patient_ful_name, patient_portal_menu.`menu_name`,
540 patient_portal_menu_group.`menu_group_name`, ccda_doc_id FROM log
541 JOIN patient_data ON log.patient_id = patient_data.pid
542 JOIN patient_access_offsite ON log.patient_id = patient_access_offsite.pid
543 JOIN patient_portal_menu ON patient_portal_menu.`patient_portal_menu_id` = log.menu_item_id
544 JOIN patient_portal_menu_group ON patient_portal_menu_group.`patient_portal_menu_group_id` = patient_portal_menu.`patient_portal_menu_group_id`
545 WHERE log.date >= ? AND log.date <= ?";
547 $sql .= " AND log_from = 'patient-portal'";
548 $sql .= " AND patient_id = ?";
549 $arrBinds = array($date1 . ' 00:00:00', $date2 . ' 23:59:59', $pid);
550 if(!empty($keyword)) {
551 $sql .= " AND (log.date LIKE ?
552 OR LOWER(event) LIKE ?
553 OR LOWER(user) LIKE ?
554 OR LOWER(CONCAT(fname, ' ', lname)) LIKE ?
555 OR LOWER(groupname) LIKE ?
556 OR LOWER(comments) LIKE ?
557 OR LOWER(user) LIKE ?
558 ) ";
559 $arrBinds[] = '%' . $keyword . '%' ;
560 $arrBinds[] = '%' . strtolower($keyword) . '%';
561 $arrBinds[] = '%' . strtolower($keyword) . '%';
562 $arrBinds[] = '%' . strtolower($keyword) . '%';
563 $arrBinds[] = '%' . strtolower($keyword) . '%';
564 $arrBinds[] = '%' . strtolower($keyword) . '%';
565 $arrBinds[] = '%' . strtolower($keyword) . '%';
567 $sql .= " ORDER BY date DESC LIMIT 5000";
569 $res = sqlStatement($sql, $arrBinds);
570 $all = array();
571 for($iter=0; $row=sqlFetchArray($res); $iter++) {
572 $all[$iter] = $row;
575 $responseString = $this->arrayToXml($all );
577 return $responseString;
582 * Connect to a phiMail Direct Messaging server and transmit
583 * a CCD document to the specified recipient. If the message is accepted by the
584 * server, the script will return "SUCCESS", otherwise it will return an error msg.
585 * @param DOMDocument ccd the xml data to transmit, a CCDA document is assumed
586 * @param string recipient the Direct Address of the recipient
587 * @param string requested_by user | patient
588 * @return string result of operation
590 function transmitCCD($data = array()) {
591 $ccd = $data['ccd'];
592 $recipient = $data['recipient'];
593 $requested_by = $data['requested_by'];
594 $xml_type = $data['xml_type'];
596 if (UserService::valid($data[0])=='existingpatient') {
598 try {
599 $_SESSION['authProvider'] = 1;
600 global $pid;
601 //get patient name in Last_First format (used for CCDA filename) and
602 //First Last for the message text.
603 $patientData = getPatientPID(array("pid"=>$pid));
604 if (empty($patientData[0]['lname'])) {
605 $att_filename = "";
606 $patientName2 = "";
607 } else {
608 //spaces are the argument delimiter for the phiMail API calls and must be removed
609 $extension = $xml_type == 'CCDA' ? 'xml' : strtolower($xml_type);
610 $att_filename = " " .
611 str_replace(" ", "_", $xml_type . "_" . $patientData[0]['lname']
612 . "_" . $patientData[0]['fname']) . "." . $extension;
613 $patientName2 = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
616 $config_err = xl("Direct messaging is currently unavailable.")." EC:";
617 if ($GLOBALS['phimail_enable']==false) return("$config_err 1");
619 $fp = phimail_connect($err);
620 if ($fp===false) return("$config_err $err");
622 $phimail_username = $GLOBALS['phimail_username'];
623 $phimail_password = $GLOBALS['phimail_password'];
624 $ret = phimail_write_expect_OK($fp,"AUTH $phimail_username $phimail_password\n");
625 if($ret!==TRUE) return("$config_err 4");
627 $ret = phimail_write_expect_OK($fp,"TO $recipient\n");
628 if($ret!==TRUE) return( xl("Delivery is not allowed to the specified Direct Address.") );
630 $ret=fgets($fp,1024); //ignore extra server data
632 if($requested_by=="patient")
633 $text_out = xl("Delivery of the attached clinical document was requested by the patient") .
634 ($patientName2=="" ? "." : ", " . $patientName2 . ".");
635 else
636 $text_out = xl("A clinical document is attached") .
637 ($patientName2=="" ? "." : " " . xl("for patient") . " " . $patientName2 . ".");
639 $text_len=strlen($text_out);
640 phimail_write($fp,"TEXT $text_len\n");
641 $ret=@fgets($fp,256);
643 if($ret!="BEGIN\n") {
644 phimail_close($fp);
645 return("$config_err 5");
647 $ret=phimail_write_expect_OK($fp,$text_out);
648 if($ret!==TRUE) return("$config_err 6");
650 if(in_array($xml_type, array('CCR', 'CCDA', 'CDA')))
652 $ccd = simplexml_load_string($ccd);
653 $ccd_out = $ccd->saveXml();
654 $ccd_len = strlen($ccd_out);
655 phimail_write($fp,"ADD " . ($xml_type=="CCR" ? $xml_type . ' ' : "CDA ") . $ccd_len . $att_filename . "\n");
656 //phimail_write($fp,"ADD " . (isset($xml_type) ? $xml_type . ' ' : "CDA ") . $ccd_len . $att_filename . "\n");
657 } else if(strtolower($xml_type) == 'html' || strtolower($xml_type) == 'pdf') {
658 $ccd_out = base64_decode($ccd);
659 $message_length = strlen($ccd_out);
660 $add_type = (strtolower($xml_type) == 'html') ? 'TEXT' : 'RAW';
661 phimail_write($fp, "ADD " . $add_type . " " . $message_length . "" . $att_filename . "\n");
665 $ret=fgets($fp,256);
667 if($ret!="BEGIN\n") {
668 phimail_close($fp);
669 return("$config_err 7");
671 $ret=phimail_write_expect_OK($fp,$ccd_out);
673 if($ret!==TRUE) return("$config_err 8");
676 phimail_write($fp,"SEND\n");
677 $ret=fgets($fp,256);
678 phimail_close($fp);
680 if($requested_by=="patient") {
681 $reqBy="portal-user";
682 $sql = "SELECT id FROM users WHERE username='portal-user'";
684 if (($r = sqlStatement($sql)) === FALSE ||
685 ($u = sqlFetchArray($r)) === FALSE) {
686 $reqID = 1; //default if we don't have a service user
687 } else {
688 $reqID = $u['id'];
691 } else {
692 $reqBy=$_SESSION['authUser'];
693 $reqID=$_SESSION['authUserID'];
696 if(substr($ret,5)=="ERROR") {
697 //log the failure
698 newEvent("transmit-ccd",$reqBy,$_SESSION['authProvider'],0,$ret,$pid);
699 return( xl("The message could not be sent at this time."));
703 * If we get here, the message was successfully sent and the return
704 * value $ret is of the form "QUEUED recipient message-id" which
705 * is suitable for logging.
707 $msg_id=explode(" ",trim($ret),4);
708 if($msg_id[0]!="QUEUED" || !isset($msg_id[2])) { //unexpected response
709 $ret = "UNEXPECTED RESPONSE: " . $ret;
710 newEvent("transmit-ccd",$reqBy,$_SESSION['authProvider'],0,$ret,$pid);
711 return( xl("There was a problem sending the message."));
713 newEvent("transmit-".$xml_type,$reqBy,$_SESSION['authProvider'],1,$ret,$pid);
714 $adodb=$GLOBALS['adodb']['db'];
716 // $sql="INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,patient_id,user_id) " .
717 // "VALUES ('S', ?, ?, ?, 'S', NOW(), ?, ?)";
718 // $res=@sqlStatement($sql,array($msg_id[2],$phimail_username,$recipient,$pid,$reqID));
720 return("SUCCESS");
721 }catch (Exception $e) {
722 return 'Error: ' . $e->getMessage();