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>.
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
;
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);
57 return hl7Text(preg_replace('/[-\s]*/', '', $s));
62 return preg_replace('/[^\d]/', '', $s);
71 return date('YmdHis', strtotime($s));
76 $s = strtoupper(substr($s, 0, 1));
77 if ($s !== 'M' && $s !== 'F') {
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];
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];
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 == '') {
116 } elseif ($tmp == 'spouse') {
118 } elseif ($tmp == 'child') {
120 } elseif ($tmp == 'other') {
124 // Should not get here so this will probably get noticed if we do.
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 = '')
139 $date = date('Y-m-d');
143 $dres = sqlStatement(
144 "SELECT * FROM insurance_data WHERE " .
145 "pid = ? AND (date <= ? OR date IS NULL) ORDER BY type ASC, date DESC",
148 $prevtype = ''; // type is primary, secondary or tertiary
149 while ($drow = sqlFetchArray($dres)) {
150 if (strcmp($prevtype, $drow['type']) == 0) {
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'])) {
161 $ins = count($payers);
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;
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)
196 "po.date_collected, po.date_ordered, po.order_priority, " .
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 " .
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",
213 return "Procedure order, ordering provider or lab is missing for order ID '$orderid'";
216 $pcres = sqlStatement(
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 " .
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",
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
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
243 // Patient Identification
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']);
257 $d1 . hl7Date($porow['DOB']) . // DOB
258 $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U
260 $d1 . hl7Text($porow['street']) .
262 $d2 . hl7Text($porow['city']) .
263 $d2 . hl7Text($porow['state']) .
264 $d2 . hl7Zip($porow['postal_code']) .
266 $d1 . hl7Phone($porow['phone_home']) .
267 $d1 . hl7Phone($porow['phone_biz']) .
269 $d1 . $porow['encounter'] .
270 $d1 . hl7SSN($porow['ss']) .
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']]);
278 while ($mres = sqlFetchArray($msql)) {
279 $drugs[] = trim($mres['drug']);
281 $med_list = count($drugs) > 0 ?
implode(",", $drugs) : 'NONE';
286 $d1 . "Medications:" . $med_list .
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?)
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
304 $payers = loadPayerInfo($porow['pid'], $porow['date_ordered']);
306 foreach ($payers as $payer) {
307 $payer_object = $payer['object'];
308 $payer_address = $payer_object->get_address();
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
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
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
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
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
341 // IN2 segment omitted.
344 // Guarantor. OpenEMR doesn't have these so use the patient.
346 $d1 . "1" . // Set ID (always just 1 of these)
348 $d1 . hl7Text($porow['lname']) .
349 $d2 . hl7Text($porow['fname']);
350 if ($porow['mname']) {
351 $out .= $d2 . hl7Text($porow['mname']);
356 $d1 . hl7Text($porow['street']) .
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
366 $d1 . 'self' . // Relationship
367 $d1 . hl7SSN($porow['ss']) .
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
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
385 while ($pcrow = sqlFetchArray($pcres)) {
386 // Observation Request.
388 $d1 . ++
$setid . // Set ID
389 $d1 . str_pad((string)$orderid, 4, "0", STR_PAD_LEFT
) . // Placer Order Number
391 $d1 . hl7Text($pcrow['procedure_code']) .
392 $d2 . hl7Text($pcrow['procedure_name']) .
393 $d1 . hl7Priority($porow['order_priority']) . // S=Stat, R=Routine
395 $d1 . hl7Time($porow['date_collected']) . // Observation Date/Time
396 str_repeat($d1, 8) . // OBR 8-15 not used
397 $dl . hl7Text($pcrow['specimen']) . // Specimen source aka OBR-15
398 $d1 . hl7Text($porow['docnpi']) . // Physician ID
399 $d2 . hl7Text($porow['doclname']) . // Last Name
400 $d2 . hl7Text($porow['docfname']) . // First Name
402 $d1 . (count($payers) ?
'I' : 'P') . // I=Insurance, C=Client, P=Self Pay
403 str_repeat($d1, 8) . // OBR 19-26 not used
407 // Diagnoses. Currently hard-coded for ICD9 and we'll surely want to make
408 // this more flexible (probably when some lab needs another diagnosis type).
410 if (!empty($pcrow['diagnoses'])) {
411 $relcodes = explode(';', $pcrow['diagnoses']);
412 foreach ($relcodes as $codestring) {
413 if ($codestring === '') {
417 list($codetype, $code) = explode(':', $codestring);
418 if ($codetype !== 'ICD10') {
422 $desc = lookup_code_descriptions($codestring);
424 $d1 . ++
$setid2 . // Set ID
425 $d1 . // Diagnosis Coding Method
426 $d1 . $code . // Diagnosis Code
427 $d2 . hl7Text($desc) . // Diagnosis Description
428 $d2 . "I10" . // Diagnosis Type
433 // Order entry questions and answers.
434 $qres = sqlStatement(
436 "a.question_code, a.answer, q.fldtype " .
437 "FROM procedure_answers AS a " .
438 "LEFT JOIN procedure_questions AS q ON " .
440 "AND q.procedure_code = ? AND " .
441 "q.question_code = a.question_code " .
443 "a.procedure_order_id = ? AND " .
444 "a.procedure_order_seq = ? " .
445 "ORDER BY q.seq, a.answer_seq",
446 array($porow['ppid'], $pcrow['procedure_code'], $orderid, $pcrow['procedure_order_seq'])
449 while ($qrow = sqlFetchArray($qres)) {
450 // Formatting of these answer values may be lab-specific and we'll figure
451 // out how to deal with that as more labs are supported.
452 $answer = trim($qrow['answer']);
453 $fldtype = $qrow['fldtype'];
455 if ($fldtype == 'N') {
457 } elseif ($fldtype == 'D') {
458 $answer = hl7Date($answer);
459 } elseif ($fldtype == 'G') {
460 $weeks = intval($answer / 7);
462 $answer = $weeks . 'wks ' . $days . 'days';
466 $d1 . ++
$setid2 . // Set ID
467 $d1 . $datatype . // Structure of observation value
468 $d1 . hl7Text($qrow['question_code']) . // Clinical question code
470 $d1 . hl7Text($answer) . // Clinical question answer
479 * Transmit HL7 for the specified lab.
481 * @param integer $ppid Procedure provider ID.
482 * @param string $out The HL7 text to be sent.
483 * @return string Error text, or empty if no errors.
485 function send_hl7_order($ppid, $out)
491 $pprow = sqlQuery("SELECT * FROM procedure_providers " .
492 "WHERE ppid = ?", array($ppid));
494 return xl('Procedure provider') . " $ppid " . xl('not found');
497 $protocol = $pprow['protocol'];
498 $remote_host = $pprow['remote_host'];
500 // Extract MSH-10 which is the message control ID.
501 $segmsh = explode(substr($out, 3, 1), substr($out, 0, strpos($out, $d0)));
504 return xl('Internal error: Cannot find MSH-10');
507 if ($protocol == 'DL' ||
$pprow['orders_path'] === '') {
508 header("Pragma: public");
509 header("Expires: 0");
510 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
511 header("Content-Type: application/force-download");
512 header("Content-Disposition: attachment; filename=order_$msgid.hl7");
513 header("Content-Description: File Transfer");
516 } elseif ($protocol == 'SFTP') {
517 // Compute the target path/file name.
518 $filename = $msgid . '.txt';
519 if ($pprow['orders_path']) {
520 $filename = $pprow['orders_path'] . '/' . $filename;
523 // Connect to the server and write the file.
524 $sftp = new \phpseclib\Net\
SFTP($remote_host);
525 if (!$sftp->login($pprow['login'], $pprow['password'])) {
526 return xl('Login to this remote host failed') . ": '$remote_host'";
529 if (!$sftp->put($filename, $out)) {
530 return xl('Creating this file on remote host failed') . ": '$filename'";
532 } elseif ($protocol == 'FS') {
533 // Compute the target path/file name.
534 $filename = $msgid . '.txt';
535 if ($pprow['orders_path']) {
536 $filename = $pprow['orders_path'] . '/' . $filename;
539 $fh = fopen("$filename", 'w');
544 return xl('Cannot create file') . ' "' . "$filename" . '"';
546 } else { // TBD: Insert "else if ($protocol == '???') {...}" to support other protocols.
547 return xl('This protocol is not implemented') . ": '$protocol'";
550 // Falling through to here indicates success.
551 EventAuditLogger
::instance()->newEvent(
553 $_SESSION['authUser'],
554 $_SESSION['authProvider'],
556 "ID: $msgid Protocol: $protocol Host: $remote_host"