Fix: Revert "Fix: OpenEMR logs sensitive information such as payment details (#7341...
[openemr.git] / interface / orders / gen_hl7_order.inc.php
blob1930db203399b8192f44d8945678594ebc8756c8
1 <?php
3 /**
4 * Functions to support HL7 order generation.
6 * Copyright (C) 2012-2013 Rod Roark <rod@sunsetsystems.com>
8 * LICENSE: This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * 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.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>.
19 * @package OpenEMR
20 * @author Rod Roark <rod@sunsetsystems.com>
21 * @author Jerry Padgett <sjpadgett@gmail.com>
25 * A bit of documentation that will need to go into the manual:
27 * The lab may want a list of your insurances for mapping into their system.
28 * To produce it, go into phpmyadmin and run this query:
30 * SELECT i.id, i.name, a.line1, a.line2, a.city, a.state, a.zip, p.area_code,
31 * p.prefix, p.number FROM insurance_companies AS i
32 * LEFT JOIN addresses AS a ON a.foreign_id = i.id
33 * LEFT JOIN phone_numbers AS p ON p.type = 2 AND p.foreign_id = i.id
34 * ORDER BY i.name, i.id;
36 * Then export as a CSV file and read it into your favorite spreadsheet app.
39 require_once("$webserver_root/custom/code_types.inc.php");
41 use OpenEMR\Common\Logging\EventAuditLogger;
43 function hl7Text($s)
45 // See http://www.interfaceware.com/hl7_escape_protocol.html:
46 $s = str_replace('\\', '\\E\\', $s);
47 $s = str_replace('^', '\\S\\', $s);
48 $s = str_replace('|', '\\F\\', $s);
49 $s = str_replace('~', '\\R\\', $s);
50 $s = str_replace('&', '\\T\\', $s);
51 $s = str_replace("\r", '\\X0d\\', $s);
52 return $s;
55 function hl7Zip($s)
57 return hl7Text(preg_replace('/[-\s]*/', '', $s));
60 function hl7Date($s)
62 return preg_replace('/[^\d]/', '', $s);
65 function hl7Time($s)
67 if (empty($s)) {
68 return '';
71 return date('YmdHis', strtotime($s));
74 function hl7Sex($s)
76 $s = strtoupper(substr($s, 0, 1));
77 if ($s !== 'M' && $s !== 'F') {
78 $s = 'U';
81 return $s;
84 function hl7Phone($s)
86 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
87 return '(' . $tmp[1] . ')' . $tmp[2] . '-' . $tmp[3];
90 if (preg_match("/(\d\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
91 return $tmp[1] . '-' . $tmp[2];
94 return '';
97 function hl7SSN($s)
99 if (preg_match("/(\d\d\d)\D*(\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
100 return $tmp[1] . '-' . $tmp[2] . '-' . $tmp[3];
103 return '';
106 function hl7Priority($s)
108 return strtoupper(substr($s, 0, 1)) == 'H' ? 'S' : 'R';
111 function hl7Relation($s)
113 $tmp = strtolower($s);
114 if ($tmp == 'self' || $tmp == '') {
115 return 'self';
116 } elseif ($tmp == 'spouse') {
117 return 'spouse';
118 } elseif ($tmp == 'child') {
119 return 'child';
120 } elseif ($tmp == 'other') {
121 return 'other';
124 // Should not get here so this will probably get noticed if we do.
125 return $s;
129 * Get array of insurance payers for the specified patient as of the specified
130 * date. If no date is passed then the current date is used.
132 * @param integer $pid Patient ID.
133 * @param date $encounter_date YYYY-MM-DD date.
134 * @return array Array containing an array of data for each payer.
136 function loadPayerInfo($pid, $date = '')
138 if (empty($date)) {
139 $date = date('Y-m-d');
142 $payers = array();
143 $dres = sqlStatement(
144 "SELECT * FROM insurance_data WHERE " .
145 "pid = ? AND (date <= ? OR date IS NULL) ORDER BY type ASC, date DESC",
146 array($pid, $date)
148 $prevtype = ''; // type is primary, secondary or tertiary
149 while ($drow = sqlFetchArray($dres)) {
150 if (strcmp($prevtype, $drow['type']) == 0) {
151 continue;
154 $prevtype = $drow['type'];
155 // Very important to check for a missing provider because
156 // that indicates no insurance as of the given date.
157 if (empty($drow['provider'])) {
158 continue;
161 $ins = count($payers);
162 $crow = sqlQuery(
163 "SELECT * FROM insurance_companies WHERE id = ?",
164 array($drow['provider'])
166 $orow = new InsuranceCompany($drow['provider']);
167 $payers[$ins] = array();
168 $payers[$ins]['data'] = $drow;
169 $payers[$ins]['company'] = $crow;
170 $payers[$ins]['object'] = $orow;
173 return $payers;
177 * Generate HL7 for the specified procedure order.
179 * @param integer $orderid Procedure order ID.
180 * @param string &$out Container for target HL7 text.
181 * @return string Error text, or empty if no errors.
183 function gen_hl7_order($orderid, &$out)
186 // Delimiters
187 $d0 = "\r";
188 $d1 = '|';
189 $d2 = '^';
191 $today = time();
192 $out = '';
194 $porow = sqlQuery(
195 "SELECT " .
196 "po.date_collected, po.date_ordered, po.order_priority, " .
197 "pp.*, " .
198 "pd.pid, pd.pubpid, pd.fname, pd.lname, pd.mname, pd.DOB, pd.ss, " .
199 "pd.phone_home, pd.phone_biz, pd.sex, pd.street, pd.city, pd.state, pd.postal_code, " .
200 "f.encounter, u.fname AS docfname, u.lname AS doclname, u.npi AS docnpi " .
201 "FROM procedure_order AS po, procedure_providers AS pp, " .
202 "forms AS f, patient_data AS pd, users AS u " .
203 "WHERE " .
204 "po.procedure_order_id = ? AND " .
205 "pp.ppid = po.lab_id AND " .
206 "f.formdir = 'procedure_order' AND " .
207 "f.form_id = po.procedure_order_id AND " .
208 "pd.pid = f.pid AND " .
209 "u.id = po.provider_id",
210 array($orderid)
212 if (empty($porow)) {
213 return "Procedure order, ordering provider or lab is missing for order ID '$orderid'";
216 $pcres = sqlStatement(
217 "SELECT " .
218 "pc.procedure_code, pc.procedure_name, pc.procedure_order_seq, pc.diagnoses, pt.specimen " .
219 "FROM procedure_order_code AS pc, procedure_type as pt " .
220 "WHERE " .
221 "pc.procedure_order_id = ? AND " .
222 "pc.procedure_name = pt.name AND " .
223 "pc.do_not_send = 0 " .
224 "ORDER BY pc.procedure_order_seq",
225 array($orderid)
228 // Message Header
229 $out .= "MSH" .
230 $d1 . "$d2~\\&" . // Encoding Characters (delimiters)
231 $d1 . $porow['send_app_id'] . // Sending Application ID
232 $d1 . $porow['send_fac_id'] . // Sending Facility ID
233 $d1 . $porow['recv_app_id'] . // Receiving Application ID
234 $d1 . $porow['recv_fac_id'] . // Receiving Facility ID
235 $d1 . date('YmdHis', $today) . // Date and time of this message
236 $d1 .
237 $d1 . 'ORM' . $d2 . 'O01' . // Message Type
238 $d1 . str_pad((string)$orderid, 4, "0", STR_PAD_LEFT) . // Unique Message Number
239 $d1 . $porow['DorP'] . // D=Debugging, P=Production
240 $d1 . '2.3' . // HL7 Version ID
241 $d0;
243 // Patient Identification
244 $out .= "PID" .
245 $d1 . "1" . // Set ID (always just 1 of these)
246 $d1 . $porow['pid'] . // Patient ID (not required)
247 $d1 . $porow['pid'] . // Patient ID (required)
248 $d1 . // Alternate Patient ID (not required)
249 $d1 . hl7Text($porow['lname']) .
250 $d2 . hl7Text($porow['fname']);
251 if ($porow['mname']) {
252 $out .= $d2 . hl7Text($porow['mname']);
255 $out .=
256 $d1 .
257 $d1 . hl7Date($porow['DOB']) . // DOB
258 $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U
259 $d1 . $d1 .
260 $d1 . hl7Text($porow['street']) .
261 $d2 .
262 $d2 . hl7Text($porow['city']) .
263 $d2 . hl7Text($porow['state']) .
264 $d2 . hl7Zip($porow['postal_code']) .
265 $d1 .
266 $d1 . hl7Phone($porow['phone_home']) .
267 $d1 . hl7Phone($porow['phone_biz']) .
268 $d1 . $d1 . $d1 .
269 $d1 . $porow['encounter'] .
270 $d1 . hl7SSN($porow['ss']) .
271 $d1 . $d1 . $d1 .
272 $d0;
274 // NTE segment(s).
275 //$msql = sqlStatement("SELECT title FROM lists WHERE type='medication' AND pid='".$porow['pid']."'");
276 $msql = sqlStatement("SELECT drug FROM prescriptions WHERE active=1 AND patient_id=?", [$porow['pid']]);
277 $drugs = array();
278 while ($mres = sqlFetchArray($msql)) {
279 $drugs[] = trim($mres['drug']);
281 $med_list = count($drugs) > 0 ? implode(",", $drugs) : 'NONE';
283 $out .= "NTE" .
284 $d1 . "1" .
285 $d1 . "L" .
286 $d1 . "Medications:" . $med_list .
287 $d0;
289 // Patient Visit.
290 $out .= "PV1" .
291 $d1 . "1" . // Set ID (always just 1 of these)
292 $d1 . // Patient Class (if required, O for Outpatient)
293 $d1 . // Patient Location (for inpatient only?)
294 $d1 . $d1 . $d1 .
295 $d1 . hl7Text($porow['docnpi']) . // Attending Doctor ID
296 $d2 . hl7Text($porow['doclname']) . // Last Name
297 $d2 . hl7Text($porow['docfname']) . // First Name
298 str_repeat($d1, 11) . // PV1 8 to 18 all empty
299 $d1 . $porow['encounter'] . // Encounter Number
300 str_repeat($d1, 13) . // PV1 20 to 32 all empty
301 $d0;
303 // Insurance stuff.
304 $payers = loadPayerInfo($porow['pid'], $porow['date_ordered']);
305 $setid = 0;
306 foreach ($payers as $payer) {
307 $payer_object = $payer['object'];
308 $payer_address = $payer_object->get_address();
309 $out .= "IN1" .
310 $d1 . ++$setid . // Set ID
311 $d1 . // Insurance Plan Identifier ??
312 $d1 . hl7Text($payer['company']['id']) . // Insurance Company ID
313 $d1 . hl7Text($payer['company']['name']) . // Insurance Company Name
314 $d1 . hl7Text($payer_address->get_line1()) . // Street Address
315 $d2 .
316 $d2 . hl7Text($payer_address->get_city()) . // City
317 $d2 . hl7Text($payer_address->get_state()) . // State
318 $d2 . hl7Zip($payer_address->get_zip()) . // Zip Code
319 $d1 .
320 $d1 . hl7Phone($payer_object->get_phone()) . // Phone Number
321 $d1 . hl7Text($payer['data']['group_number']) . // Insurance Company Group Number
322 str_repeat($d1, 7) . // IN1 9-15 all empty
323 $d1 . hl7Text($payer['data']['subscriber_lname']) . // Insured last name
324 $d2 . hl7Text($payer['data']['subscriber_fname']) . // Insured first name
325 $d2 . hl7Text($payer['data']['subscriber_mname']) . // Insured middle name
326 $d1 . hl7Relation($payer['data']['subscriber_relationship']) .
327 $d1 . hl7Date($payer['data']['subscriber_DOB']) . // Insured DOB
328 $d1 . hl7Date($payer['data']['subscriber_street']) . // Insured Street Address
329 $d2 .
330 $d2 . hl7Text($payer['data']['subscriber_city']) . // City
331 $d2 . hl7Text($payer['data']['subscriber_state']) . // State
332 $d2 . hl7Zip($payer['data']['subscriber_postal_code']) . // Zip
333 $d1 .
334 $d1 .
335 $d1 . $setid . // 1=Primary, 2=Secondary, 3=Tertiary
336 str_repeat($d1, 13) . // IN1-23 to 35 all empty
337 $d1 . hl7Text($payer['data']['policy_number']) . // Policy Number
338 str_repeat($d1, 12) . // IN1-37 to 48 all empty
339 $d0;
341 // IN2 segment omitted.
344 // Guarantor. OpenEMR doesn't have these so use the patient.
345 $out .= "GT1" .
346 $d1 . "1" . // Set ID (always just 1 of these)
347 $d1 .
348 $d1 . hl7Text($porow['lname']) .
349 $d2 . hl7Text($porow['fname']);
350 if ($porow['mname']) {
351 $out .= $d2 . hl7Text($porow['mname']);
354 $out .=
355 $d1 .
356 $d1 . hl7Text($porow['street']) .
357 $d2 .
358 $d2 . hl7Text($porow['city']) .
359 $d2 . hl7Text($porow['state']) .
360 $d2 . hl7Zip($porow['postal_code']) .
361 $d1 . hl7Phone($porow['phone_home']) .
362 $d1 . hl7Phone($porow['phone_biz']) .
363 $d1 . hl7Date($porow['DOB']) . // DOB
364 $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U
365 $d1 .
366 $d1 . 'self' . // Relationship
367 $d1 . hl7SSN($porow['ss']) .
368 $d0;
370 // Common Order.
371 $out .= "ORC" .
372 $d1 . "NW" . // New Order
373 $d1 . str_pad((string)$orderid, 4, "0", STR_PAD_LEFT) . // Placer Order Number
374 str_repeat($d1, 6) . // ORC 3-8 not used
375 $d1 . date('YmdHis') . // Transaction date/time
376 $d1 . $d1 .
377 $d1 . hl7Text($porow['docnpi']) . // Ordering Provider
378 $d2 . hl7Text($porow['doclname']) . // Last Name
379 $d2 . hl7Text($porow['docfname']) . // First Name
380 str_repeat($d1, 7) . // ORC 13-19 not used
381 $d1 . "2" . // ABN Status: 2 = Notified & Signed, 4 = Unsigned
382 $d0;
384 $setid = 0;
385 while ($pcrow = sqlFetchArray($pcres)) {
386 // Observation Request.
388 $dl = '';
389 $out .= "OBR" .
390 $d1 . ++$setid . // Set ID
391 $d1 . str_pad((string)$orderid, 4, "0", STR_PAD_LEFT) . // Placer Order Number
392 $d1 .
393 $d1 . hl7Text($pcrow['procedure_code']) .
394 $d2 . hl7Text($pcrow['procedure_name']) .
395 $d1 . hl7Priority($porow['order_priority']) . // S=Stat, R=Routine
396 $d1 .
397 $d1 . hl7Time($porow['date_collected']) . // Observation Date/Time
398 str_repeat($d1, 8) . // OBR 8-15 not used
399 $dl . hl7Text($pcrow['specimen']) . // Specimen source aka OBR-15
400 $d1 . hl7Text($porow['docnpi']) . // Physician ID
401 $d2 . hl7Text($porow['doclname']) . // Last Name
402 $d2 . hl7Text($porow['docfname']) . // First Name
403 $d1 .
404 $d1 . (count($payers) ? 'I' : 'P') . // I=Insurance, C=Client, P=Self Pay
405 str_repeat($d1, 8) . // OBR 19-26 not used
406 $d1 . '0' . // ?
407 $d0;
409 // Diagnoses. Currently hard-coded for ICD9 and we'll surely want to make
410 // this more flexible (probably when some lab needs another diagnosis type).
411 $setid2 = 0;
412 if (!empty($pcrow['diagnoses'])) {
413 $relcodes = explode(';', $pcrow['diagnoses']);
414 foreach ($relcodes as $codestring) {
415 if ($codestring === '') {
416 continue;
419 list($codetype, $code) = explode(':', $codestring);
420 if ($codetype !== 'ICD10') {
421 continue;
424 $desc = lookup_code_descriptions($codestring);
425 $out .= "DG1" .
426 $d1 . ++$setid2 . // Set ID
427 $d1 . // Diagnosis Coding Method
428 $d1 . $code . // Diagnosis Code
429 $d2 . hl7Text($desc) . // Diagnosis Description
430 $d2 . "I10" . // Diagnosis Type
431 $d1 . $d0;
435 // Order entry questions and answers.
436 $qres = sqlStatement(
437 "SELECT " .
438 "a.question_code, a.answer, q.fldtype " .
439 "FROM procedure_answers AS a " .
440 "LEFT JOIN procedure_questions AS q ON " .
441 "q.lab_id = ? " .
442 "AND q.procedure_code = ? AND " .
443 "q.question_code = a.question_code " .
444 "WHERE " .
445 "a.procedure_order_id = ? AND " .
446 "a.procedure_order_seq = ? " .
447 "ORDER BY q.seq, a.answer_seq",
448 array($porow['ppid'], $pcrow['procedure_code'], $orderid, $pcrow['procedure_order_seq'])
450 $setid2 = 0;
451 while ($qrow = sqlFetchArray($qres)) {
452 // Formatting of these answer values may be lab-specific and we'll figure
453 // out how to deal with that as more labs are supported.
454 $answer = trim($qrow['answer']);
455 $fldtype = $qrow['fldtype'];
456 $datatype = 'ST';
457 if ($fldtype == 'N') {
458 $datatype = "NM";
459 } elseif ($fldtype == 'D') {
460 $answer = hl7Date($answer);
461 } elseif ($fldtype == 'G') {
462 $weeks = intval($answer / 7);
463 $days = $answer % 7;
464 $answer = $weeks . 'wks ' . $days . 'days';
467 $out .= "OBX" .
468 $d1 . ++$setid2 . // Set ID
469 $d1 . $datatype . // Structure of observation value
470 $d1 . hl7Text($qrow['question_code']) . // Clinical question code
471 $d1 .
472 $d1 . hl7Text($answer) . // Clinical question answer
473 $d0;
477 return '';
481 * Transmit HL7 for the specified lab.
483 * @param integer $ppid Procedure provider ID.
484 * @param string $out The HL7 text to be sent.
485 * @return string Error text, or empty if no errors.
487 function send_hl7_order($ppid, $out)
489 global $srcdir;
491 $d0 = "\r";
493 $pprow = sqlQuery("SELECT * FROM procedure_providers " .
494 "WHERE ppid = ?", array($ppid));
495 if (empty($pprow)) {
496 return xl('Procedure provider') . " $ppid " . xl('not found');
499 $protocol = $pprow['protocol'];
500 $remote_host = $pprow['remote_host'];
502 // Extract MSH-10 which is the message control ID.
503 $segmsh = explode(substr($out, 3, 1), substr($out, 0, strpos($out, $d0)));
504 $msgid = $segmsh[9];
505 if (empty($msgid)) {
506 return xl('Internal error: Cannot find MSH-10');
509 if ($protocol == 'DL' || $pprow['orders_path'] === '') {
510 header("Pragma: public");
511 header("Expires: 0");
512 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
513 header("Content-Type: application/force-download");
514 header("Content-Disposition: attachment; filename=order_$msgid.hl7");
515 header("Content-Description: File Transfer");
516 echo $out;
517 exit;
518 } elseif ($protocol == 'SFTP') {
519 // Compute the target path/file name.
520 $filename = $msgid . '.txt';
521 if ($pprow['orders_path']) {
522 $filename = $pprow['orders_path'] . '/' . $filename;
525 // Connect to the server and write the file.
526 $sftp = new \phpseclib3\Net\SFTP($remote_host);
527 if (!$sftp->login($pprow['login'], $pprow['password'])) {
528 return xl('Login to this remote host failed') . ": '$remote_host'";
531 if (!$sftp->put($filename, $out)) {
532 return xl('Creating this file on remote host failed') . ": '$filename'";
534 } elseif ($protocol == 'FS') {
535 // Compute the target path/file name.
536 $filename = $msgid . '.txt';
537 if ($pprow['orders_path']) {
538 $filename = $pprow['orders_path'] . '/' . $filename;
541 $fh = fopen("$filename", 'w');
542 if ($fh) {
543 fwrite($fh, $out);
544 fclose($fh);
545 } else {
546 return xl('Cannot create file') . ' "' . "$filename" . '"';
548 } else { // TBD: Insert "else if ($protocol == '???') {...}" to support other protocols.
549 return xl('This protocol is not implemented') . ": '$protocol'";
552 // Falling through to here indicates success.
553 EventAuditLogger::instance()->newEvent(
554 "proc_order_xmit",
555 $_SESSION['authUser'],
556 $_SESSION['authProvider'],
558 "ID: $msgid Protocol: $protocol Host: $remote_host"
560 return '';