PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/myportal/soap_service/server_med_rec.php

https://bitbucket.org/openemr/openemr
PHP | 724 lines | 584 code | 75 blank | 65 comment | 99 complexity | 9c955ba841d0015ca143babc8e28e70f MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0, GPL-2.0, LGPL-3.0, BSD-3-Clause, Unlicense, MPL-2.0, GPL-3.0, LGPL-2.1
  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.
  10. //
  11. //
  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.
  16. //
  17. //
  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>
  25. //
  26. // +------------------------------------------------------------------------------+
  27. require_once("server_audit.php");
  28. use OpenEMR\Common\Crypto\CryptoGen;
  29. use OpenEMR\Common\Logging\EventAuditLogger;
  30. class Userforms extends UserAudit
  31. {
  32. public function issue_type($data)
  33. {
  34. if (UserService::valid($data[0]) == 'existingpatient') {
  35. global $ISSUE_TYPES;
  36. require_once("../../library/lists.inc");
  37. return $ISSUE_TYPES;
  38. } else {
  39. throw new SoapFault("Server", "credentials failed");
  40. }
  41. }
  42. public function print_report($data)
  43. {
  44. global $pid;
  45. if (UserService::valid($data[0]) == 'existingpatient') {
  46. $repArr = $data[1];
  47. $type = $data[3];
  48. global $ISSUE_TYPES;
  49. require_once("../../library/forms.inc");
  50. require_once("../../library/pnotes.inc");
  51. require_once("../../library/patient.inc");
  52. require_once("../../library/options.inc.php");
  53. require_once("../../library/lists.inc");
  54. require_once("../../library/report.inc");
  55. require_once("../../custom/code_types.inc.php");
  56. foreach ($repArr as $value) {
  57. ob_start();
  58. if ($type == "profile") {
  59. $this->getIncudes($value);
  60. $out .= ob_get_clean();
  61. } else {
  62. if ($type == 'issue') {
  63. $this->getIid($value);
  64. }
  65. if ($type == 'forms') {
  66. $this->getforms($value);
  67. }
  68. $out .= ob_get_clean();
  69. }
  70. }
  71. return $out;
  72. } else {
  73. throw new SoapFault("Server", "credentials failed");
  74. }
  75. }
  76. public function print_ccr_report($data)
  77. {
  78. if (UserService::valid($data[0]) == 'existingpatient') {
  79. $ccraction = $data[1];
  80. $raw = $data[2];
  81. require_once("../../ccr/createCCR.php");
  82. ob_start();
  83. createCCR($ccraction, $raw);
  84. $html = ob_get_clean();
  85. if ($ccraction == 'viewccd') {
  86. $html = preg_replace('/<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD HTML 4.01\/\/EN" "http:\/\/www.w3.org\/TR\/html4\/strict.dtd">/', '', $html);
  87. $pos1 = strpos($html, 'body {');
  88. $pos2 = strpos($html, '.h1center');
  89. $tes = substr("$html", $pos1, ($pos2 - $pos1));
  90. $html = str_replace($tes, '', $html);
  91. $html = str_replace('h3>', 'h2>', $html);
  92. $html = base64_encode($html);
  93. } else {
  94. $pos1 = strpos($html, '*{');
  95. $pos2 = strpos($html, 'h1');
  96. $tes = substr("$html", $pos1, ($pos2 - $pos1));
  97. $html = str_replace($tes, '', $html);
  98. }
  99. return $html;
  100. } else {
  101. throw new SoapFault("Server", "credentials failed");
  102. }
  103. }
  104. //Return the forms requested from Portal.
  105. private function getforms($fId)
  106. {
  107. global $pid;
  108. $GLOBALS['pid'] = $pid;
  109. $inclookupres = sqlStatement("SELECT DISTINCT formdir FROM forms WHERE pid = ? AND deleted=0", array($pid));
  110. while ($result = sqlFetchArray($inclookupres)) {
  111. $formdir = $result['formdir'];
  112. if (substr($formdir, 0, 3) == 'LBF') {
  113. include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
  114. } else {
  115. include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
  116. }
  117. }
  118. $N = 6;
  119. $inclookupres = sqlStatement("SELECT encounter,form_id,formdir,id FROM forms WHERE pid = ? AND deleted=0
  120. AND id =? ", array($pid,$fId));
  121. while ($result = sqlFetchArray($inclookupres)) {
  122. $form_encounter = $result['encounter'];
  123. $form_id = $result['form_id'];
  124. $formdir = $result['formdir'];
  125. $id = $result['id'];
  126. ob_start();
  127. if (substr($formdir, 0, 3) == 'LBF') {
  128. call_user_func("lbf_report", $pid, $form_encounter, $N, $form_id, $formdir);
  129. } else {
  130. call_user_func($formdir . "_report", $pid, $form_encounter, $N, $form_id);
  131. }
  132. $out = ob_get_clean();
  133. ?> <table>
  134. <tr class=text>
  135. <th><?php echo htmlspecialchars($formdir, ENT_QUOTES);?></th>
  136. </tr>
  137. </table>
  138. <?php echo $out;?>
  139. <?php
  140. }
  141. }
  142. private function getIid($val)
  143. {
  144. global $pid;
  145. global $ISSUE_TYPES;
  146. $inclookupres = sqlStatement("SELECT DISTINCT formdir FROM forms WHERE pid = ? AND deleted=?", array($pid,0));
  147. while ($result = sqlFetchArray($inclookupres)) {
  148. $formdir = $result['formdir'];
  149. if (substr($formdir, 0, 3) == 'LBF') {
  150. include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
  151. } else {
  152. include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
  153. }
  154. }
  155. ?>
  156. <tr class=text>
  157. <td></td>
  158. <td>
  159. <?php
  160. $irow = sqlQuery("SELECT type, title, comments, diagnosis FROM lists WHERE id =? ", array($val));
  161. $diagnosis = $irow['diagnosis'];
  162. if ($prevIssueType != $irow['type']) {
  163. $disptype = $ISSUE_TYPES[$irow['type']][0];
  164. ?>
  165. <div class='issue_type' style='font-weight: bold;'><?php echo htmlspecialchars($disptype, ENT_QUOTES);?>:</div>
  166. <?php
  167. $prevIssueType = $irow['type'];
  168. }
  169. ?>
  170. <div class='text issue'>
  171. <span class='issue_title'><?php echo htmlspecialchars($irow['title'], ENT_QUOTES);?>:</span>
  172. <span class='issue_comments'><?php echo htmlspecialchars($irow['comments'], ENT_QUOTES);?></span>
  173. <?php
  174. if ($diagnosis) {
  175. ?>
  176. <div class='text issue_diag'>
  177. <span class='bold'>[<?php echo htmlspecialchars(xl('Diagnosis'), ENT_QUOTES);?>]</span><br />
  178. <?php
  179. $dcodes = explode(";", $diagnosis);
  180. foreach ($dcodes as $dcode) {
  181. ?>
  182. <span class='italic'><?php echo htmlspecialchars($dcode, ENT_QUOTES);?></span>:
  183. <?php
  184. echo htmlspecialchars(lookup_code_descriptions($dcode), ENT_QUOTES);
  185. ?>
  186. <br />
  187. <?php
  188. }
  189. ?>
  190. </div>
  191. <?php
  192. }
  193. if ($irow['type'] == 'ippf_gcac') {
  194. ?>
  195. <table>
  196. <?php
  197. display_layout_rows('GCA', sqlQuery("SELECT * FROM lists_ippf_gcac WHERE id = ?", array($rowid)));
  198. ?>
  199. </table>
  200. <?php
  201. } elseif ($irow['type'] == 'contraceptive') {
  202. ?>
  203. <table>
  204. <?php
  205. display_layout_rows('CON', sqlQuery("SELECT * FROM lists_ippf_con WHERE id = ?", array($rowid)));
  206. ?>
  207. </table>
  208. <?php
  209. }
  210. ?>
  211. </div>
  212. <?php
  213. ?>
  214. </td>
  215. <?php
  216. }
  217. private function getIncudes($val)
  218. {
  219. global $pid;
  220. if ($val == "demographics") {
  221. ?>
  222. <hr />
  223. <div class='text demographics' id='DEM'>
  224. <?php
  225. // printRecDataOne($patient_data_array, getRecPatientData ($pid), $N);
  226. $result1 = getPatientData($pid);
  227. $result2 = getEmployerData($pid);
  228. ?>
  229. <table>
  230. <tr><td><h6><?php echo htmlspecialchars(xl('Patient Data') . ":", ENT_QUOTES);?></h6></td></tr>
  231. <?php
  232. display_layout_rows('DEM', $result1, $result2);
  233. ?>
  234. </table>
  235. </div>
  236. <?php
  237. } elseif ($val == "history") {
  238. ?>
  239. <hr />
  240. <div class='text history' id='HIS'>
  241. <?php
  242. $result1 = getHistoryData($pid);
  243. ?>
  244. <table>
  245. <tr><td><h6><?php echo htmlspecialchars(xl('History Data') . ":", ENT_QUOTES);?></h6></td></tr>
  246. <?php
  247. display_layout_rows('HIS', $result1);
  248. ?>
  249. </table>
  250. </div>
  251. <?php
  252. } elseif ($val == "insurance") {
  253. ?>
  254. <hr />
  255. <div class='text insurance'>";
  256. <h6><?php echo htmlspecialchars(xl('Insurance Data') . ":", ENT_QUOTES);?></h6>
  257. <br /><span class=bold><?php echo htmlspecialchars(xl('Primary Insurance Data') . ":", ENT_QUOTES);?></span><br />
  258. <?php
  259. printRecDataOne($insurance_data_array, getRecInsuranceData($pid, "primary"), $N);
  260. ?>
  261. <span class=bold><?php echo htmlspecialchars(xl('Secondary Insurance Data') . ":", ENT_QUOTES);?></span><br />
  262. <?php
  263. printRecDataOne($insurance_data_array, getRecInsuranceData($pid, "secondary"), $N);
  264. ?>
  265. <span class=bold><?php echo htmlspecialchars(xl('Tertiary Insurance Data') . ":", ENT_QUOTES);?></span><br />
  266. <?php
  267. printRecDataOne($insurance_data_array, getRecInsuranceData($pid, "tertiary"), $N);
  268. ?>
  269. </div>
  270. <?php
  271. } elseif ($val == "billing") {
  272. ?>
  273. <hr />
  274. <div class='text billing'>
  275. <h6><?php echo htmlspecialchars(xl('Billing Information') . ":", ENT_QUOTES);?></h6>
  276. <?php
  277. if (count($ar['newpatient']) > 0) {
  278. $billings = array();
  279. ?>
  280. <table>
  281. <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>
  282. <?php
  283. $total = 0.00;
  284. $copays = 0.00;
  285. foreach ($ar['newpatient'] as $be) {
  286. $ta = split(":", $be);
  287. $billing = getPatientBillingEncounter($pid, $ta[1]);
  288. $billings[] = $billing;
  289. foreach ($billing as $b) {
  290. ?>
  291. <tr>
  292. <td class=text>
  293. <?php
  294. 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;";
  295. ?>
  296. </td>
  297. <td class=text>
  298. <?php
  299. echo htmlspecialchars(oeFormatMoney($b['fee']), ENT_QUOTES);
  300. ?>
  301. </td>
  302. </tr>
  303. <?php
  304. $total += $b['fee'];
  305. if ($b['code_type'] == "COPAY") {
  306. $copays += $b['fee'];
  307. }
  308. }
  309. }
  310. echo "<tr><td>&nbsp;</td></tr>";
  311. echo "<tr><td class=bold>" . htmlspecialchars(xl('Sub-Total'), ENT_QUOTES) . "</td><td class=text>" . htmlspecialchars(oeFormatMoney($total + abs($copays)), ENT_QUOTES) . "</td></tr>";
  312. echo "<tr><td class=bold>" . htmlspecialchars(xl('Paid'), ENT_QUOTES) . "</td><td class=text>" . htmlspecialchars(oeFormatMoney(abs($copays)), ENT_QUOTES) . "</td></tr>";
  313. echo "<tr><td class=bold>" . htmlspecialchars(xl('Total'), ENT_QUOTES) . "</td><td class=text>" . htmlspecialchars(oeFormatMoney($total), ENT_QUOTES) . "</td></tr>";
  314. echo "</table>";
  315. echo "<pre>";
  316. //print_r($billings);
  317. echo "</pre>";
  318. } else {
  319. printPatientBilling($pid);
  320. }
  321. echo "</div>\n"; // end of billing DIV
  322. } elseif ($val == "immunizations") {
  323. ?>
  324. <hr />
  325. <div class='text immunizations'>
  326. <h6><?php echo htmlspecialchars(xl('Patient Immunization') . ":", ENT_QUOTES);?></h6>
  327. <?php
  328. $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";
  329. $result = sqlStatement($sql, array($pid));
  330. while ($row = sqlFetchArray($result)) {
  331. echo htmlspecialchars($row['immunization_data'], ENT_QUOTES);
  332. echo generate_display_field(array('data_type' => '1','list_id' => 'immunizations'), $row['immunization_id']);
  333. ?>
  334. <br />
  335. <?php
  336. }
  337. ?>
  338. </div>
  339. <?php
  340. } elseif ($val == "batchcom") {
  341. ?>
  342. <hr />
  343. <div class='text transactions'>
  344. <h6><?php htmlspecialchars(xl('Patient Communication sent') . ":", ENT_QUOTES);?></h6>
  345. <?php
  346. $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=?";
  347. $result = sqlStatement($sql, array($pid));
  348. while ($row = sqlFetchArray($result)) {
  349. echo htmlspecialchars($row['batchcom_data'] . ", " . xl('By') . ": " . $row['user_name'], ENT_QUOTES);
  350. ?>
  351. <br /><?php echo htmlspecialchars(xl('Text'), ENT_QUOTES);?>:<br /><?php echo htmlspecialchars($row['msg_txt'], ENT_QUOTES);?><br />
  352. <?php
  353. }
  354. ?>
  355. </div>
  356. <?php
  357. } elseif ($val == "notes") {
  358. ?>
  359. <hr />
  360. <div class='text notes'>
  361. <h6><?php echo htmlspecialchars(xl('Patient Notes') . ":", ENT_QUOTES);?></h6>
  362. <?php
  363. printPatientNotes($pid);
  364. ?>
  365. </div>
  366. <?php
  367. } elseif ($val == "transactions") {
  368. ?>
  369. <hr />
  370. <div class='text transactions'>
  371. <h6><?php echo htmlspecialchars(xl('Patient Transactions') . ":", ENT_QUOTES);?></h6>
  372. <?php
  373. printPatientTransactions($pid);
  374. ?>
  375. </div>
  376. <?php
  377. }
  378. }
  379. /**
  380. * Method to fetch CCDA
  381. * @param type $data
  382. * @return type
  383. */
  384. public function ccdaFetching($data)
  385. {
  386. global $pid;
  387. global $server_url;
  388. if (UserService::valid($data[0]) == 'existingpatient') {
  389. if ($this->checkModuleInstalled($moduleName = 'Carecoordination')) {
  390. $site_id = $data[0][0];
  391. try {
  392. $ch = curl_init();
  393. $url = $server_url . "/interface/modules/zend_modules/public/encounterccdadispatch/index?cron=1&pid=$pid&site=$site_id";
  394. curl_setopt($ch, CURLOPT_URL, $url);
  395. curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
  396. curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
  397. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  398. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  399. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  400. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  401. $result = curl_exec($ch) or die(curl_error($ch));
  402. curl_close($ch);
  403. } catch (Exception $e) {
  404. }
  405. try {
  406. $event = isset($data['event']) ? $data['event'] : 'patient-record';
  407. $menu_item = isset($data['menu_item']) ? $data['menu_item'] : 'Dashboard';
  408. EventAuditLogger::instance()->newEvent($event, 1, '', 1, '', $pid, $log_from = 'patient-portal', $menu_item);
  409. } catch (Exception $e) {
  410. }
  411. return $result;
  412. } else {
  413. return '<?xml version="1.0" encoding="UTF-8"?>
  414. <note>
  415. <heading>WARNING!</heading>
  416. <body>Unable to fetch CCDA Carecoordination module not installed!</body>
  417. </note>';
  418. }
  419. } else {
  420. return '<?xml version="1.0" encoding="UTF-8"?>
  421. <note>
  422. <heading>WARNING!</heading>
  423. <body>Existing patient checking failed!</body>
  424. </note>';
  425. }
  426. return '<?xml version="1.0" encoding="UTF-8"?>
  427. <note>
  428. <heading>WARNING!</heading>
  429. <body>Un known error occured</body>
  430. </note>';
  431. }
  432. public function checkModuleInstalled($moduleName = 'Carecoordination')
  433. {
  434. $sql = "SELECT mod_id FROM modules WHERE mod_name = ? AND mod_active = '1'";
  435. $res = sqlStatement($sql, array($moduleName));
  436. $row = sqlFetchArray($res);
  437. return !empty($row);
  438. }
  439. /**
  440. * @param mysql_resource - $inputArray - mysql query result
  441. * @param string - $rootElementName - root element name
  442. * @param string - $childElementName - child element name
  443. */
  444. public function arrayToXml($inputArray, $rootElementName = 'root', $childElementName = 'RowItem')
  445. {
  446. $xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
  447. $xmlData .= "<" . $rootElementName . ">";
  448. foreach ($inputArray as $rowItem) {
  449. $xmlData .= "<" . $childElementName . ">";
  450. foreach ($rowItem as $fieldName => $fieldValue) {
  451. $xmlData .= "<" . $fieldName . ">";
  452. $xmlData .= !empty($fieldValue) ? $fieldValue : "null";
  453. $xmlData .= "</" . $fieldName . ">";
  454. }
  455. $xmlData .= "</" . $childElementName . ">";
  456. }
  457. $xmlData .= "</" . $rootElementName . ">";
  458. return $xmlData;
  459. }
  460. /**
  461. *
  462. * @param type $data
  463. * @return type
  464. */
  465. public function getEventLog($data)
  466. {
  467. global $pid;
  468. if (UserService::valid($data[0]) == 'existingpatient') {
  469. $date1 = $data['start_date'];
  470. $date2 = $data['end_date'];
  471. $keyword = $data['keyword'];
  472. $arrBinds = array();
  473. $cols = "DISTINCT log.date, event, user, groupname, patient_id, success, comments,checksum,crt_user";
  474. $sql = "SELECT $cols, CONCAT(fname, ' ', lname) as patient_ful_name, patient_portal_menu.`menu_name`,
  475. patient_portal_menu_group.`menu_group_name`, ccda_doc_id FROM log
  476. JOIN patient_data ON log.patient_id = patient_data.pid
  477. JOIN patient_access_offsite ON log.patient_id = patient_access_offsite.pid
  478. JOIN patient_portal_menu ON patient_portal_menu.`patient_portal_menu_id` = log.menu_item_id
  479. JOIN patient_portal_menu_group ON patient_portal_menu_group.`patient_portal_menu_group_id` = patient_portal_menu.`patient_portal_menu_group_id`
  480. WHERE log.date >= ? AND log.date <= ?";
  481. $sql .= " AND log_from = 'patient-portal'";
  482. $sql .= " AND patient_id = ?";
  483. $arrBinds = array($date1 . ' 00:00:00', $date2 . ' 23:59:59', $pid);
  484. if (!empty($keyword)) {
  485. $sql .= " AND (log.date LIKE ?
  486. OR LOWER(event) LIKE ?
  487. OR LOWER(user) LIKE ?
  488. OR LOWER(CONCAT(fname, ' ', lname)) LIKE ?
  489. OR LOWER(groupname) LIKE ?
  490. OR LOWER(comments) LIKE ?
  491. OR LOWER(user) LIKE ?
  492. ) ";
  493. $arrBinds[] = '%' . $keyword . '%' ;
  494. $arrBinds[] = '%' . strtolower($keyword) . '%';
  495. $arrBinds[] = '%' . strtolower($keyword) . '%';
  496. $arrBinds[] = '%' . strtolower($keyword) . '%';
  497. $arrBinds[] = '%' . strtolower($keyword) . '%';
  498. $arrBinds[] = '%' . strtolower($keyword) . '%';
  499. $arrBinds[] = '%' . strtolower($keyword) . '%';
  500. }
  501. $sql .= " ORDER BY date DESC LIMIT 5000";
  502. $res = sqlStatement($sql, $arrBinds);
  503. $all = array();
  504. for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
  505. $all[$iter] = $row;
  506. }
  507. $responseString = $this->arrayToXml($all);
  508. return $responseString;
  509. }
  510. }
  511. /*
  512. * Connect to a phiMail Direct Messaging server and transmit
  513. * a CCD document to the specified recipient. If the message is accepted by the
  514. * server, the script will return "SUCCESS", otherwise it will return an error msg.
  515. * @param DOMDocument ccd the xml data to transmit, a CCDA document is assumed
  516. * @param string recipient the Direct Address of the recipient
  517. * @param string requested_by user | patient
  518. * @return string result of operation
  519. */
  520. function transmitCCD($data = array())
  521. {
  522. $ccd = $data['ccd'];
  523. $recipient = $data['recipient'];
  524. $requested_by = $data['requested_by'];
  525. $xml_type = $data['xml_type'];
  526. if (UserService::valid($data[0]) == 'existingpatient') {
  527. try {
  528. $_SESSION['authProvider'] = 1;
  529. global $pid;
  530. //get patient name in Last_First format (used for CCDA filename) and
  531. //First Last for the message text.
  532. $patientData = getPatientPID(array("pid" => $pid));
  533. if (empty($patientData[0]['lname'])) {
  534. $att_filename = "";
  535. $patientName2 = "";
  536. } else {
  537. //spaces are the argument delimiter for the phiMail API calls and must be removed
  538. $extension = $xml_type == 'CCDA' ? 'xml' : strtolower($xml_type);
  539. $att_filename = " " .
  540. str_replace(" ", "_", $xml_type . "_" . $patientData[0]['lname']
  541. . "_" . $patientData[0]['fname']) . "." . $extension;
  542. $patientName2 = $patientData[0]['fname'] . " " . $patientData[0]['lname'];
  543. }
  544. $config_err = xl("Direct messaging is currently unavailable.") . " EC:";
  545. if ($GLOBALS['phimail_enable'] == false) {
  546. return("$config_err 1");
  547. }
  548. $fp = phimail_connect($err);
  549. if ($fp === false) {
  550. return("$config_err $err");
  551. }
  552. $phimail_username = $GLOBALS['phimail_username'];
  553. $cryptoGen = new CryptoGen();
  554. $phimail_password = $cryptoGen->decryptStandard($GLOBALS['phimail_password']);
  555. $ret = phimail_write_expect_OK($fp, "AUTH $phimail_username $phimail_password\n");
  556. if ($ret !== true) {
  557. return("$config_err 4");
  558. }
  559. $ret = phimail_write_expect_OK($fp, "TO $recipient\n");
  560. if ($ret !== true) {
  561. return( xl("Delivery is not allowed to the specified Direct Address.") );
  562. }
  563. $ret = fgets($fp, 1024); //ignore extra server data
  564. if ($requested_by == "patient") {
  565. $text_out = xl("Delivery of the attached clinical document was requested by the patient") .
  566. ($patientName2 == "" ? "." : ", " . $patientName2 . ".");
  567. } else {
  568. $text_out = xl("A clinical document is attached") .
  569. ($patientName2 == "" ? "." : " " . xl("for patient") . " " . $patientName2 . ".");
  570. }
  571. $text_len = strlen($text_out);
  572. phimail_write($fp, "TEXT $text_len\n");
  573. $ret = @fgets($fp, 256);
  574. if ($ret != "BEGIN\n") {
  575. phimail_close($fp);
  576. return("$config_err 5");
  577. }
  578. $ret = phimail_write_expect_OK($fp, $text_out);
  579. if ($ret !== true) {
  580. return("$config_err 6");
  581. }
  582. if (in_array($xml_type, array('CCR', 'CCDA', 'CDA'))) {
  583. $ccd = simplexml_load_string($ccd);
  584. $ccd_out = $ccd->saveXml();
  585. $ccd_len = strlen($ccd_out);
  586. phimail_write($fp, "ADD " . ($xml_type == "CCR" ? $xml_type . ' ' : "CDA ") . $ccd_len . $att_filename . "\n");
  587. //phimail_write($fp,"ADD " . (isset($xml_type) ? $xml_type . ' ' : "CDA ") . $ccd_len . $att_filename . "\n");
  588. } elseif (strtolower($xml_type) == 'html' || strtolower($xml_type) == 'pdf') {
  589. $ccd_out = base64_decode($ccd);
  590. $message_length = strlen($ccd_out);
  591. $add_type = (strtolower($xml_type) == 'html') ? 'TEXT' : 'RAW';
  592. phimail_write($fp, "ADD " . $add_type . " " . $message_length . "" . $att_filename . "\n");
  593. }
  594. $ret = fgets($fp, 256);
  595. if ($ret != "BEGIN\n") {
  596. phimail_close($fp);
  597. return("$config_err 7");
  598. }
  599. $ret = phimail_write_expect_OK($fp, $ccd_out);
  600. if ($ret !== true) {
  601. return("$config_err 8");
  602. }
  603. phimail_write($fp, "SEND\n");
  604. $ret = fgets($fp, 256);
  605. phimail_close($fp);
  606. if ($requested_by == "patient") {
  607. $reqBy = "portal-user";
  608. $sql = "SELECT id FROM users WHERE username='portal-user'";
  609. if (
  610. ($r = sqlStatement($sql)) === false ||
  611. ($u = sqlFetchArray($r)) === false
  612. ) {
  613. $reqID = 1; //default if we don't have a service user
  614. } else {
  615. $reqID = $u['id'];
  616. }
  617. } else {
  618. $reqBy = $_SESSION['authUser'];
  619. $reqID = $_SESSION['authUserID'];
  620. }
  621. if (substr($ret, 5) == "ERROR") {
  622. //log the failure
  623. EventAuditLogger::instance()->newEvent("transmit-ccd", $reqBy, $_SESSION['authProvider'], 0, $ret, $pid);
  624. return( xl("The message could not be sent at this time."));
  625. }
  626. /**
  627. * If we get here, the message was successfully sent and the return
  628. * value $ret is of the form "QUEUED recipient message-id" which
  629. * is suitable for logging.
  630. */
  631. $msg_id = explode(" ", trim($ret), 4);
  632. if ($msg_id[0] != "QUEUED" || !isset($msg_id[2])) { //unexpected response
  633. $ret = "UNEXPECTED RESPONSE: " . $ret;
  634. EventAuditLogger::instance()->newEvent("transmit-ccd", $reqBy, $_SESSION['authProvider'], 0, $ret, $pid);
  635. return( xl("There was a problem sending the message."));
  636. }
  637. EventAuditLogger::instance()->newEvent("transmit-" . $xml_type, $reqBy, $_SESSION['authProvider'], 1, $ret, $pid);
  638. $adodb = $GLOBALS['adodb']['db'];
  639. // $sql="INSERT INTO direct_message_log (msg_type,msg_id,sender,recipient,status,status_ts,patient_id,user_id) " .
  640. // "VALUES ('S', ?, ?, ?, 'S', NOW(), ?, ?)";
  641. // $res=@sqlStatement($sql,array($msg_id[2],$phimail_username,$recipient,$pid,$reqID));
  642. return("SUCCESS");
  643. } catch (Exception $e) {
  644. return 'Error: ' . $e->getMessage();
  645. }
  646. }
  647. }
  648. }
  649. ?>