Centralized formatting.inc.php include
[openemr.git] / myportal / soap_service / server_med_rec.php
blob188f8f9cfa6f41274c43d98a8c4e0051c4b50761
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.
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("../../custom/code_types.inc.php");
69 foreach($repArr as $value){
70 ob_start();
71 if($type=="profile"){
72 $this->getIncudes($value);
73 $out .= ob_get_clean();
75 else{
76 if($type=='issue')
77 $this->getIid($value);
78 if($type=='forms')
79 $this->getforms($value);
80 $out .= ob_get_clean();
84 return $out;
86 else{
87 throw new SoapFault("Server", "credentials failed");
94 public function print_ccr_report($data){
95 if(UserService::valid($data[0])=='existingpatient'){
96 $ccraction = $data[1];
97 $raw = $data[2];
98 require_once("../../ccr/createCCR.php");
99 ob_start();
100 createCCR($ccraction,$raw);
101 $html = ob_get_clean();
102 if($ccraction=='viewccd')
105 $html = preg_replace('/<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD HTML 4.01\/\/EN" "http:\/\/www.w3.org\/TR\/html4\/strict.dtd">/','',$html);
106 $pos1 = strpos($html,'body {');
107 $pos2 = strpos($html,'.h1center');
108 $tes = substr("$html",$pos1,($pos2-$pos1));
109 $html = str_replace($tes,'',$html);
110 $html = str_replace('h3>','h2>',$html);
111 $html = base64_encode($html);
113 else{
114 $pos1 = strpos($html,'*{');
115 $pos2 = strpos($html,'h1');
116 $tes = substr("$html",$pos1,($pos2-$pos1));
117 $html = str_replace($tes,'',$html);
119 return $html;
121 else{
122 throw new SoapFault("Server", "credentials failed");
126 //Return the forms requested from Portal.
128 private function getforms($fId){
129 global $pid;
130 $GLOBALS['pid'] = $pid;
131 $inclookupres = sqlStatement("SELECT DISTINCT formdir FROM forms WHERE pid = ? AND deleted=0",array($pid));
132 while($result = sqlFetchArray($inclookupres)) {
133 $formdir = $result['formdir'];
134 if (substr($formdir,0,3) == 'LBF')
135 include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
136 else
137 include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
139 $N = 6;
140 $inclookupres = sqlStatement("SELECT encounter,form_id,formdir,id FROM forms WHERE pid = ? AND deleted=0
141 AND id =? ",array($pid,$fId));
142 while($result = sqlFetchArray($inclookupres)) {
143 $form_encounter=$result['encounter'];
144 $form_id=$result['form_id'];
145 $formdir = $result['formdir'];
146 $id=$result['id'];
147 ob_start();
148 if (substr($formdir,0,3) == 'LBF')
149 call_user_func("lbf_report", $pid, $form_encounter, $N, $form_id, $formdir);
150 else
151 call_user_func($formdir . "_report", $pid, $form_encounter, $N, $form_id);
152 $out=ob_get_clean();
153 ?> <table>
154 <tr class=text>
155 <th><?php echo htmlspecialchars($formdir,ENT_QUOTES);?></th>
156 </tr>
157 </table>
158 <?php echo $out;?>
159 <?php
165 private function getIid($val){
166 global $pid;
167 global $ISSUE_TYPES;
168 $inclookupres = sqlStatement("SELECT DISTINCT formdir FROM forms WHERE pid = ? AND deleted=?",array($pid,0));
169 while($result = sqlFetchArray($inclookupres)) {
170 $formdir = $result['formdir'];
171 if (substr($formdir,0,3) == 'LBF')
172 include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
173 else
174 include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
177 <tr class=text>
178 <td></td>
179 <td>
180 <?php
181 $irow = sqlQuery("SELECT type, title, comments, diagnosis FROM lists WHERE id =? ",array($val));
182 $diagnosis = $irow['diagnosis'];
184 if ($prevIssueType != $irow['type'])
186 $disptype = $ISSUE_TYPES[$irow['type']][0];
188 <div class='issue_type' style='font-weight: bold;'><?php echo htmlspecialchars($disptype,ENT_QUOTES);?>:</div>
189 <?php
190 $prevIssueType = $irow['type'];
193 <div class='text issue'>
194 <span class='issue_title'><?php echo htmlspecialchars($irow['title'],ENT_QUOTES);?>:</span>
195 <span class='issue_comments'><?php echo htmlspecialchars($irow['comments'],ENT_QUOTES);?></span>
196 <?php
197 if ($diagnosis)
200 <div class='text issue_diag'>
201 <span class='bold'>[<?php echo htmlspecialchars(xl('Diagnosis'),ENT_QUOTES);?>]</span><br>
202 <?php
203 $dcodes = explode(";", $diagnosis);
204 foreach ($dcodes as $dcode)
207 <span class='italic'><?php echo htmlspecialchars($dcode,ENT_QUOTES);?></span>:
208 <?php
209 echo htmlspecialchars(lookup_code_descriptions($dcode),ENT_QUOTES);
211 <br>
212 <?php
215 </div>
216 <?php
218 if ($irow['type'] == 'ippf_gcac')
221 <table>
222 <?php
223 display_layout_rows('GCA', sqlQuery("SELECT * FROM lists_ippf_gcac WHERE id = ?",array($rowid)));
226 </table>
227 <?php
229 else if ($irow['type'] == 'contraceptive')
232 <table>
233 <?php
234 display_layout_rows('CON', sqlQuery("SELECT * FROM lists_ippf_con WHERE id = ?",array($rowid)));
236 </table>
237 <?php
240 </div>
241 <?php
243 </td>
244 <?php
250 private function getIncudes($val){
251 global $pid;
252 if ($val == "demographics")
255 <hr />
256 <div class='text demographics' id='DEM'>
257 <?php
258 // printRecDataOne($patient_data_array, getRecPatientData ($pid), $N);
259 $result1 = getPatientData($pid);
260 $result2 = getEmployerData($pid);
262 <table>
263 <tr><td><h6><?php echo htmlspecialchars(xl('Patient Data').":",ENT_QUOTES);?></h6></td></tr>
264 <?php
265 display_layout_rows('DEM', $result1, $result2);
267 </table>
268 </div>
269 <?php
271 elseif ($val == "history")
274 <hr />
275 <div class='text history' id='HIS'>
276 <?php
277 $result1 = getHistoryData($pid);
279 <table>
280 <tr><td><h6><?php echo htmlspecialchars(xl('History Data').":",ENT_QUOTES);?></h6></td></tr>
281 <?php
282 display_layout_rows('HIS', $result1);
284 </table>
285 </div>
286 <?php
288 elseif ($val == "insurance")
291 <hr />
292 <div class='text insurance'>";
293 <h6><?php echo htmlspecialchars(xl('Insurance Data').":",ENT_QUOTES);?></h6>
294 <br><span class=bold><?php echo htmlspecialchars(xl('Primary Insurance Data').":",ENT_QUOTES);?></span><br>
295 <?php
296 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"primary"), $N);
298 <span class=bold><?php echo htmlspecialchars(xl('Secondary Insurance Data').":",ENT_QUOTES);?></span><br>
299 <?php
300 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"secondary"), $N);
302 <span class=bold><?php echo htmlspecialchars(xl('Tertiary Insurance Data').":",ENT_QUOTES);?></span><br>
303 <?php
304 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"tertiary"), $N);
306 </div>
307 <?php
309 elseif ($val == "billing")
312 <hr />
313 <div class='text billing'>
314 <h6><?php echo htmlspecialchars(xl('Billing Information').":",ENT_QUOTES);?></h6>
315 <?php
316 if (count($ar['newpatient']) > 0) {
317 $billings = array();
319 <table>
320 <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>
321 <?php
322 $total = 0.00;
323 $copays = 0.00;
324 foreach ($ar['newpatient'] as $be) {
325 $ta = split(":",$be);
326 $billing = getPatientBillingEncounter($pid,$ta[1]);
327 $billings[] = $billing;
328 foreach ($billing as $b) {
330 <tr>
331 <td class=text>
332 <?php
333 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;";
335 </td>
336 <td class=text>
337 <?php
338 echo htmlspecialchars(oeFormatMoney($b['fee']),ENT_QUOTES);
340 </td>
341 </tr>
342 <?php
343 $total += $b['fee'];
344 if ($b['code_type'] == "COPAY") {
345 $copays += $b['fee'];
349 echo "<tr><td>&nbsp;</td></tr>";
350 echo "<tr><td class=bold>".htmlspecialchars(xl('Sub-Total'),ENT_QUOTES)."</td><td class=text>" . htmlspecialchars(oeFormatMoney($total + abs($copays)),ENT_QUOTES) . "</td></tr>";
351 echo "<tr><td class=bold>".htmlspecialchars(xl('Paid'),ENT_QUOTES)."</td><td class=text>" . htmlspecialchars(oeFormatMoney(abs($copays)),ENT_QUOTES) . "</td></tr>";
352 echo "<tr><td class=bold>".htmlspecialchars(xl('Total'),ENT_QUOTES)."</td><td class=text>" .htmlspecialchars(oeFormatMoney($total),ENT_QUOTES) . "</td></tr>";
353 echo "</table>";
354 echo "<pre>";
355 //print_r($billings);
356 echo "</pre>";
357 } else {
358 printPatientBilling($pid);
360 echo "</div>\n"; // end of billing DIV
362 elseif ($val == "immunizations")
366 <hr />
367 <div class='text immunizations'>
368 <h6><?php echo htmlspecialchars(xl('Patient Immunization').":",ENT_QUOTES);?></h6>
369 <?php
370 $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";
371 $result = sqlStatement($sql,array($pid));
372 while ($row=sqlFetchArray($result)) {
373 echo htmlspecialchars($row{'immunization_data'},ENT_QUOTES);
374 echo generate_display_field(array('data_type'=>'1','list_id'=>'immunizations'), $row['immunization_id']);
376 <br>
377 <?php
380 </div>
381 <?php
384 elseif ($val == "batchcom")
387 <hr />
388 <div class='text transactions'>
389 <h6><?php htmlspecialchars(xl('Patient Communication sent').":",ENT_QUOTES);?></h6>
390 <?php
391 $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=?";
392 $result = sqlStatement($sql,array($pid));
393 while ($row=sqlFetchArray($result)) {
394 echo htmlspecialchars($row{'batchcom_data'}.", ".xl('By').": ".$row{'user_name'},ENT_QUOTES);
396 <br><?php echo htmlspecialchars(xl('Text'),ENT_QUOTES);?>:<br><?php echo htmlspecialchars($row{'msg_txt'},ENT_QUOTES);?><br>
397 <?php
400 </div>
401 <?php
403 elseif ($val == "notes")
406 <hr />
407 <div class='text notes'>
408 <h6><?php echo htmlspecialchars(xl('Patient Notes').":",ENT_QUOTES);?></h6>
409 <?php
410 printPatientNotes($pid);
412 </div>
413 <?php
415 elseif ($val == "transactions")
418 <hr />
419 <div class='text transactions'>
420 <h6><?php echo htmlspecialchars(xl('Patient Transactions').":",ENT_QUOTES);?></h6>
421 <?php
422 printPatientTransactions($pid);
424 </div>
425 <?php
430 * Method to fetch CCDA
431 * @param type $data
432 * @return type
434 public function ccdaFetching($data)
436 global $pid;
437 global $server_url;
439 if (UserService::valid($data[0])=='existingpatient') {
440 if ($this->checkModuleInstalled($moduleName = 'Carecoordination')) {
441 $site_id = $data[0][0];
442 try {
443 $ch = curl_init();
444 $url = $server_url . "/interface/modules/zend_modules/public/encounterccdadispatch/index?cron=1&pid=$pid&site=$site_id";
446 curl_setopt($ch, CURLOPT_URL, $url);
447 curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
448 curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
449 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
450 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
451 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
452 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
453 $result = curl_exec($ch) or die(curl_error($ch));
454 curl_close($ch);
456 catch (Exception $e) {
460 try {
461 $event = isset ($data['event']) ? $data['event'] : 'patient-record';
462 $menu_item = isset($data['menu_item']) ? $data['menu_item'] : 'Dashboard';
463 newEvent($event, 1, '', 1, '', $pid,$log_from = 'patient-portal', $menu_item );
464 }catch (Exception $e) {
467 return $result;
469 else {
470 return '<?xml version="1.0" encoding="UTF-8"?>
471 <note>
472 <heading>WARNING!</heading>
473 <body>Unable to fetch CCDA Carecoordination module not installed!</body>
474 </note>';
477 else {
478 return '<?xml version="1.0" encoding="UTF-8"?>
479 <note>
480 <heading>WARNING!</heading>
481 <body>Existing patient checking failed!</body>
482 </note>';
484 return '<?xml version="1.0" encoding="UTF-8"?>
485 <note>
486 <heading>WARNING!</heading>
487 <body>Un known error occured</body>
488 </note>';
491 public function checkModuleInstalled($moduleName = 'Carecoordination')
493 $sql = "SELECT mod_id FROM modules WHERE mod_name = ? AND mod_active = '1'";
494 $res = sqlStatement($sql, array($moduleName));
495 $row = sqlFetchArray($res);
496 return !empty($row);
500 * @param mysql_resource - $inputArray - mysql query result
501 * @param string - $rootElementName - root element name
502 * @param string - $childElementName - child element name
504 public function arrayToXml($inputArray, $rootElementName = 'root', $childElementName = 'RowItem')
506 $xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
507 $xmlData .= "<" . $rootElementName . ">";
508 foreach ($inputArray as $rowItem) {
509 $xmlData .= "<" . $childElementName . ">";
510 foreach($rowItem as $fieldName => $fieldValue) {
511 $xmlData .= "<" . $fieldName . ">";
512 $xmlData .= !empty($fieldValue) ? $fieldValue : "null";
513 $xmlData .= "</" . $fieldName . ">";
515 $xmlData .= "</" . $childElementName . ">";
517 $xmlData .= "</" . $rootElementName . ">";
519 return $xmlData;
524 * @param type $data
525 * @return type
527 public function getEventLog($data)
529 global $pid;
530 if (UserService::valid($data[0])=='existingpatient') {
531 $date1 = $data['start_date'];
532 $date2 = $data['end_date'];
533 $keyword = $data['keyword'];
534 $arrBinds = array();
535 $cols = "DISTINCT log.date, event, user, groupname, patient_id, success, comments,checksum,crt_user";
536 $sql = "SELECT $cols, CONCAT(fname, ' ', lname) as patient_ful_name, patient_portal_menu.`menu_name`,
537 patient_portal_menu_group.`menu_group_name`, ccda_doc_id FROM log
538 JOIN patient_data ON log.patient_id = patient_data.pid
539 JOIN patient_access_offsite ON log.patient_id = patient_access_offsite.pid
540 JOIN patient_portal_menu ON patient_portal_menu.`patient_portal_menu_id` = log.menu_item_id
541 JOIN patient_portal_menu_group ON patient_portal_menu_group.`patient_portal_menu_group_id` = patient_portal_menu.`patient_portal_menu_group_id`
542 WHERE log.date >= ? AND log.date <= ?";
544 $sql .= " AND log_from = 'patient-portal'";
545 $sql .= " AND patient_id = ?";
546 $arrBinds = array($date1 . ' 00:00:00', $date2 . ' 23:59:59', $pid);
547 if(!empty($keyword)) {
548 $sql .= " AND (log.date LIKE ?
549 OR LOWER(event) LIKE ?
550 OR LOWER(user) LIKE ?
551 OR LOWER(CONCAT(fname, ' ', lname)) LIKE ?
552 OR LOWER(groupname) LIKE ?
553 OR LOWER(comments) LIKE ?
554 OR LOWER(user) LIKE ?
555 ) ";
556 $arrBinds[] = '%' . $keyword . '%' ;
557 $arrBinds[] = '%' . strtolower($keyword) . '%';
558 $arrBinds[] = '%' . strtolower($keyword) . '%';
559 $arrBinds[] = '%' . strtolower($keyword) . '%';
560 $arrBinds[] = '%' . strtolower($keyword) . '%';
561 $arrBinds[] = '%' . strtolower($keyword) . '%';
562 $arrBinds[] = '%' . strtolower($keyword) . '%';
564 $sql .= " ORDER BY date DESC LIMIT 5000";
566 $res = sqlStatement($sql, $arrBinds);
567 $all = array();
568 for($iter=0; $row=sqlFetchArray($res); $iter++) {
569 $all[$iter] = $row;
572 $responseString = $this->arrayToXml($all );
574 return $responseString;
579 * Connect to a phiMail Direct Messaging server and transmit
580 * a CCD document to the specified recipient. If the message is accepted by the
581 * server, the script will return "SUCCESS", otherwise it will return an error msg.
582 * @param DOMDocument ccd the xml data to transmit, a CCDA document is assumed
583 * @param string recipient the Direct Address of the recipient
584 * @param string requested_by user | patient
585 * @return string result of operation
587 function transmitCCD($data = array()) {
588 $ccd = $data['ccd'];
589 $recipient = $data['recipient'];
590 $requested_by = $data['requested_by'];
591 $xml_type = $data['xml_type'];
593 if (UserService::valid($data[0])=='existingpatient') {
595 try {
596 $_SESSION['authProvider'] = 1;
597 global $pid;
598 //get patient name in Last_First format (used for CCDA filename) and
599 //First Last for the message text.
600 $patientData = getPatientPID(array("pid"=>$pid));
601 if (empty($patientData[0]['lname'])) {
602 $att_filename = "";
603 $patientName2 = "";
604 } else {
605 //spaces are the argument delimiter for the phiMail API calls and must be removed
606 $extension = $xml_type == 'CCDA' ? 'xml' : strtolower($xml_type);
607 $att_filename = " " .
608 str_replace(" ", "_", $xml_type . "_" . $patientData[0]['lname']
609 . "_" . $patientData[0]['fname']) . "." . $extension;
610 $patientName2 = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
613 $config_err = xl("Direct messaging is currently unavailable.")." EC:";
614 if ($GLOBALS['phimail_enable']==false) return("$config_err 1");
616 $fp = phimail_connect($err);
617 if ($fp===false) return("$config_err $err");
619 $phimail_username = $GLOBALS['phimail_username'];
620 $phimail_password = $GLOBALS['phimail_password'];
621 $ret = phimail_write_expect_OK($fp,"AUTH $phimail_username $phimail_password\n");
622 if($ret!==TRUE) return("$config_err 4");
624 $ret = phimail_write_expect_OK($fp,"TO $recipient\n");
625 if($ret!==TRUE) return( xl("Delivery is not allowed to the specified Direct Address.") );
627 $ret=fgets($fp,1024); //ignore extra server data
629 if($requested_by=="patient")
630 $text_out = xl("Delivery of the attached clinical document was requested by the patient") .
631 ($patientName2=="" ? "." : ", " . $patientName2 . ".");
632 else
633 $text_out = xl("A clinical document is attached") .
634 ($patientName2=="" ? "." : " " . xl("for patient") . " " . $patientName2 . ".");
636 $text_len=strlen($text_out);
637 phimail_write($fp,"TEXT $text_len\n");
638 $ret=@fgets($fp,256);
640 if($ret!="BEGIN\n") {
641 phimail_close($fp);
642 return("$config_err 5");
644 $ret=phimail_write_expect_OK($fp,$text_out);
645 if($ret!==TRUE) return("$config_err 6");
647 if(in_array($xml_type, array('CCR', 'CCDA', 'CDA')))
649 $ccd = simplexml_load_string($ccd);
650 $ccd_out = $ccd->saveXml();
651 $ccd_len = strlen($ccd_out);
652 phimail_write($fp,"ADD " . ($xml_type=="CCR" ? $xml_type . ' ' : "CDA ") . $ccd_len . $att_filename . "\n");
653 //phimail_write($fp,"ADD " . (isset($xml_type) ? $xml_type . ' ' : "CDA ") . $ccd_len . $att_filename . "\n");
654 } else if(strtolower($xml_type) == 'html' || strtolower($xml_type) == 'pdf') {
655 $ccd_out = base64_decode($ccd);
656 $message_length = strlen($ccd_out);
657 $add_type = (strtolower($xml_type) == 'html') ? 'TEXT' : 'RAW';
658 phimail_write($fp, "ADD " . $add_type . " " . $message_length . "" . $att_filename . "\n");
662 $ret=fgets($fp,256);
664 if($ret!="BEGIN\n") {
665 phimail_close($fp);
666 return("$config_err 7");
668 $ret=phimail_write_expect_OK($fp,$ccd_out);
670 if($ret!==TRUE) return("$config_err 8");
673 phimail_write($fp,"SEND\n");
674 $ret=fgets($fp,256);
675 phimail_close($fp);
677 if($requested_by=="patient") {
678 $reqBy="portal-user";
679 $sql = "SELECT id FROM users WHERE username='portal-user'";
681 if (($r = sqlStatement($sql)) === FALSE ||
682 ($u = sqlFetchArray($r)) === FALSE) {
683 $reqID = 1; //default if we don't have a service user
684 } else {
685 $reqID = $u['id'];
688 } else {
689 $reqBy=$_SESSION['authUser'];
690 $reqID=$_SESSION['authUserID'];
693 if(substr($ret,5)=="ERROR") {
694 //log the failure
695 newEvent("transmit-ccd",$reqBy,$_SESSION['authProvider'],0,$ret,$pid);
696 return( xl("The message could not be sent at this time."));
700 * If we get here, the message was successfully sent and the return
701 * value $ret is of the form "QUEUED recipient message-id" which
702 * is suitable for logging.
704 $msg_id=explode(" ",trim($ret),4);
705 if($msg_id[0]!="QUEUED" || !isset($msg_id[2])) { //unexpected response
706 $ret = "UNEXPECTED RESPONSE: " . $ret;
707 newEvent("transmit-ccd",$reqBy,$_SESSION['authProvider'],0,$ret,$pid);
708 return( xl("There was a problem sending the message."));
710 newEvent("transmit-".$xml_type,$reqBy,$_SESSION['authProvider'],1,$ret,$pid);
711 $adodb=$GLOBALS['adodb']['db'];
713 // $sql="INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,patient_id,user_id) " .
714 // "VALUES ('S', ?, ?, ?, 'S', NOW(), ?, ?)";
715 // $res=@sqlStatement($sql,array($msg_id[2],$phimail_username,$recipient,$pid,$reqID));
717 return("SUCCESS");
718 }catch (Exception $e) {
719 return 'Error: ' . $e->getMessage();