quick minor path updates (#1968)
[openemr.git] / interface / orders / gen_hl7_order.inc.php
blobebcc3659e0a2a23dd10b41bc2e3b07350718442f
1 <?php
2 /**
3 * Functions to support HL7 order generation.
5 * Copyright (C) 2012-2013 Rod Roark <rod@sunsetsystems.com>
7 * LICENSE: This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>.
18 * @package OpenEMR
19 * @author Rod Roark <rod@sunsetsystems.com>
23 * A bit of documentation that will need to go into the manual:
25 * The lab may want a list of your insurances for mapping into their system.
26 * To produce it, go into phpmyadmin and run this query:
28 * SELECT i.id, i.name, a.line1, a.line2, a.city, a.state, a.zip, p.area_code,
29 * p.prefix, p.number FROM insurance_companies AS i
30 * LEFT JOIN addresses AS a ON a.foreign_id = i.id
31 * LEFT JOIN phone_numbers AS p ON p.type = 2 AND p.foreign_id = i.id
32 * ORDER BY i.name, i.id;
34 * Then export as a CSV file and read it into your favorite spreadsheet app.
37 require_once("$webserver_root/custom/code_types.inc.php");
39 function hl7Text($s)
41 // See http://www.interfaceware.com/hl7_escape_protocol.html:
42 $s = str_replace('\\', '\\E\\', $s);
43 $s = str_replace('^', '\\S\\', $s);
44 $s = str_replace('|', '\\F\\', $s);
45 $s = str_replace('~', '\\R\\', $s);
46 $s = str_replace('&', '\\T\\', $s);
47 $s = str_replace("\r", '\\X0d\\', $s);
48 return $s;
51 function hl7Zip($s)
53 return hl7Text(preg_replace('/[-\s]*/', '', $s));
56 function hl7Date($s)
58 return preg_replace('/[^\d]/', '', $s);
61 function hl7Time($s)
63 if (empty($s)) {
64 return '';
67 return date('YmdHis', strtotime($s));
70 function hl7Sex($s)
72 $s = strtoupper(substr($s, 0, 1));
73 if ($s !== 'M' && $s !== 'F') {
74 $s = 'U';
77 return $s;
80 function hl7Phone($s)
82 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
83 return '(' . $tmp[1] . ')' . $tmp[2] . '-' . $tmp[3];
86 if (preg_match("/(\d\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
87 return $tmp[1] . '-' . $tmp[2];
90 return '';
93 function hl7SSN($s)
95 if (preg_match("/(\d\d\d)\D*(\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
96 return $tmp[1] . '-' . $tmp[2] . '-' . $tmp[3];
99 return '';
102 function hl7Priority($s)
104 return strtoupper(substr($s, 0, 1)) == 'H' ? 'S' : 'R';
107 function hl7Relation($s)
109 $tmp = strtolower($s);
110 if ($tmp == 'self' || $tmp == '') {
111 return 'self';
112 } else if ($tmp == 'spouse') {
113 return 'spouse';
114 } else if ($tmp == 'child') {
115 return 'child';
116 } else if ($tmp == 'other') {
117 return 'other';
120 // Should not get here so this will probably get noticed if we do.
121 return $s;
125 * Get array of insurance payers for the specified patient as of the specified
126 * date. If no date is passed then the current date is used.
128 * @param integer $pid Patient ID.
129 * @param date $encounter_date YYYY-MM-DD date.
130 * @return array Array containing an array of data for each payer.
132 function loadPayerInfo($pid, $date = '')
134 if (empty($date)) {
135 $date = date('Y-m-d');
138 $payers = array();
139 $dres = sqlStatement(
140 "SELECT * FROM insurance_data WHERE " .
141 "pid = ? AND date <= ? ORDER BY type ASC, date DESC",
142 array($pid, $date)
144 $prevtype = ''; // type is primary, secondary or tertiary
145 while ($drow = sqlFetchArray($dres)) {
146 if (strcmp($prevtype, $drow['type']) == 0) {
147 continue;
150 $prevtype = $drow['type'];
151 // Very important to check for a missing provider because
152 // that indicates no insurance as of the given date.
153 if (empty($drow['provider'])) {
154 continue;
157 $ins = count($payers);
158 $crow = sqlQuery(
159 "SELECT * FROM insurance_companies WHERE id = ?",
160 array($drow['provider'])
162 $orow = new InsuranceCompany($drow['provider']);
163 $payers[$ins] = array();
164 $payers[$ins]['data'] = $drow;
165 $payers[$ins]['company'] = $crow;
166 $payers[$ins]['object'] = $orow;
169 return $payers;
173 * Generate HL7 for the specified procedure order.
175 * @param integer $orderid Procedure order ID.
176 * @param string &$out Container for target HL7 text.
177 * @return string Error text, or empty if no errors.
179 function gen_hl7_order($orderid, &$out)
182 // Delimiters
183 $d0 = "\r";
184 $d1 = '|';
185 $d2 = '^';
187 $today = time();
188 $out = '';
190 $porow = sqlQuery(
191 "SELECT " .
192 "po.date_collected, po.date_ordered, po.order_priority, " .
193 "pp.*, " .
194 "pd.pid, pd.pubpid, pd.fname, pd.lname, pd.mname, pd.DOB, pd.ss, " .
195 "pd.phone_home, pd.phone_biz, pd.sex, pd.street, pd.city, pd.state, pd.postal_code, " .
196 "f.encounter, u.fname AS docfname, u.lname AS doclname, u.npi AS docnpi " .
197 "FROM procedure_order AS po, procedure_providers AS pp, " .
198 "forms AS f, patient_data AS pd, users AS u " .
199 "WHERE " .
200 "po.procedure_order_id = ? AND " .
201 "pp.ppid = po.lab_id AND " .
202 "f.formdir = 'procedure_order' AND " .
203 "f.form_id = po.procedure_order_id AND " .
204 "pd.pid = f.pid AND " .
205 "u.id = po.provider_id",
206 array($orderid)
208 if (empty($porow)) {
209 return "Procedure order, ordering provider or lab is missing for order ID '$orderid'";
212 $pcres = sqlStatement(
213 "SELECT " .
214 "pc.procedure_code, pc.procedure_name, pc.procedure_order_seq, pc.diagnoses " .
215 "FROM procedure_order_code AS pc " .
216 "WHERE " .
217 "pc.procedure_order_id = ? AND " .
218 "pc.do_not_send = 0 " .
219 "ORDER BY pc.procedure_order_seq",
220 array($orderid)
223 // Message Header
224 $out .= "MSH" .
225 $d1 . "$d2~\\&" . // Encoding Characters (delimiters)
226 $d1 . $porow['send_app_id'] . // Sending Application ID
227 $d1 . $porow['send_fac_id'] . // Sending Facility ID
228 $d1 . $porow['recv_app_id'] . // Receiving Application ID
229 $d1 . $porow['recv_fac_id'] . // Receiving Facility ID
230 $d1 . date('YmdHis', $today) . // Date and time of this message
231 $d1 .
232 $d1 . 'ORM' . $d2 . 'O01' . // Message Type
233 $d1 . $orderid . // Unique Message Number
234 $d1 . $porow['DorP'] . // D=Debugging, P=Production
235 $d1 . '2.3' . // HL7 Version ID
236 $d0;
238 // Patient Identification
239 $out .= "PID" .
240 $d1 . "1" . // Set ID (always just 1 of these)
241 $d1 . $porow['pid'] . // Patient ID (not required)
242 $d1 . $porow['pid'] . // Patient ID (required)
243 $d1 . // Alternate Patient ID (not required)
244 $d1 . hl7Text($porow['lname']) .
245 $d2 . hl7Text($porow['fname']);
246 if ($porow['mname']) {
247 $out .= $d2 . hl7Text($porow['mname']);
250 $out .=
251 $d1 .
252 $d1 . hl7Date($porow['DOB']) . // DOB
253 $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U
254 $d1 . $d1 .
255 $d1 . hl7Text($porow['street']) .
256 $d2 .
257 $d2 . hl7Text($porow['city']) .
258 $d2 . hl7Text($porow['state']) .
259 $d2 . hl7Zip($porow['postal_code']) .
260 $d1 .
261 $d1 . hl7Phone($porow['phone_home']) .
262 $d1 . hl7Phone($porow['phone_biz']) .
263 $d1 . $d1 . $d1 .
264 $d1 . $porow['encounter'] .
265 $d1 . hl7SSN($porow['ss']) .
266 $d1 . $d1 . $d1 .
267 $d0;
269 // NTE segment(s) omitted.
271 // Patient Visit.
272 $out .= "PV1" .
273 $d1 . "1" . // Set ID (always just 1 of these)
274 $d1 . // Patient Class (if required, O for Outpatient)
275 $d1 . // Patient Location (for inpatient only?)
276 $d1 . $d1 . $d1 .
277 $d1 . hl7Text($porow['docnpi']) . // Attending Doctor ID
278 $d2 . hl7Text($porow['doclname']) . // Last Name
279 $d2 . hl7Text($porow['docfname']) . // First Name
280 str_repeat($d1, 11) . // PV1 8 to 18 all empty
281 $d1 . $porow['encounter'] . // Encounter Number
282 str_repeat($d1, 13) . // PV1 20 to 32 all empty
283 $d0;
285 // Insurance stuff.
286 $payers = loadPayerInfo($porow['pid'], $porow['date_ordered']);
287 $setid = 0;
288 foreach ($payers as $payer) {
289 $payer_object = $payer['object'];
290 $payer_address = $payer_object->get_address();
291 $out .= "IN1" .
292 $d1 . ++$setid . // Set ID
293 $d1 . // Insurance Plan Identifier ??
294 $d1 . hl7Text($payer['company']['id']) . // Insurance Company ID
295 $d1 . hl7Text($payer['company']['name']) . // Insurance Company Name
296 $d1 . hl7Text($payer_address->get_line1()) . // Street Address
297 $d2 .
298 $d2 . hl7Text($payer_address->get_city()) . // City
299 $d2 . hl7Text($payer_address->get_state()) . // State
300 $d2 . hl7Zip($payer_address->get_zip()) . // Zip Code
301 $d1 .
302 $d1 . hl7Phone($payer_object->get_phone()) . // Phone Number
303 $d1 . hl7Text($payer['data']['group_number']) . // Insurance Company Group Number
304 str_repeat($d1, 7) . // IN1 9-15 all empty
305 $d1 . hl7Text($payer['data']['subscriber_lname']) . // Insured last name
306 $d2 . hl7Text($payer['data']['subscriber_fname']) . // Insured first name
307 $d2 . hl7Text($payer['data']['subscriber_mname']) . // Insured middle name
308 $d1 . hl7Relation($payer['data']['subscriber_relationship']) .
309 $d1 . hl7Date($payer['data']['subscriber_DOB']) . // Insured DOB
310 $d1 . hl7Date($payer['data']['subscriber_street']) . // Insured Street Address
311 $d2 .
312 $d2 . hl7Text($payer['data']['subscriber_city']) . // City
313 $d2 . hl7Text($payer['data']['subscriber_state']) . // State
314 $d2 . hl7Zip($payer['data']['subscriber_postal_code']) . // Zip
315 $d1 .
316 $d1 .
317 $d1 . $setid . // 1=Primary, 2=Secondary, 3=Tertiary
318 str_repeat($d1, 13) . // IN1-23 to 35 all empty
319 $d1 . hl7Text($payer['data']['policy_number']) . // Policy Number
320 str_repeat($d1, 12) . // IN1-37 to 48 all empty
321 $d0;
323 // IN2 segment omitted.
326 // Guarantor. OpenEMR doesn't have these so use the patient.
327 $out .= "GT1" .
328 $d1 . "1" . // Set ID (always just 1 of these)
329 $d1 .
330 $d1 . hl7Text($porow['lname']) .
331 $d2 . hl7Text($porow['fname']);
332 if ($porow['mname']) {
333 $out .= $d2 . hl7Text($porow['mname']);
336 $out .=
337 $d1 .
338 $d1 . hl7Text($porow['street']) .
339 $d2 .
340 $d2 . hl7Text($porow['city']) .
341 $d2 . hl7Text($porow['state']) .
342 $d2 . hl7Zip($porow['postal_code']) .
343 $d1 . hl7Phone($porow['phone_home']) .
344 $d1 . hl7Phone($porow['phone_biz']) .
345 $d1 . hl7Date($porow['DOB']) . // DOB
346 $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U
347 $d1 .
348 $d1 . 'self' . // Relationship
349 $d1 . hl7SSN($porow['ss']) .
350 $d0;
352 // Common Order.
353 $out .= "ORC" .
354 $d1 . "NW" . // New Order
355 $d1 . $orderid . // Placer Order Number
356 str_repeat($d1, 6) . // ORC 3-8 not used
357 $d1 . date('YmdHis') . // Transaction date/time
358 $d1 . $d1 .
359 $d1 . hl7Text($porow['docnpi']) . // Ordering Provider
360 $d2 . hl7Text($porow['doclname']) . // Last Name
361 $d2 . hl7Text($porow['docfname']) . // First Name
362 str_repeat($d1, 7) . // ORC 13-19 not used
363 $d1 . "2" . // ABN Status: 2 = Notified & Signed, 4 = Unsigned
364 $d0;
366 $setid = 0;
367 while ($pcrow = sqlFetchArray($pcres)) {
368 // Observation Request.
369 $out .= "OBR" .
370 $d1 . ++$setid . // Set ID
371 $d1 . $orderid . // Placer Order Number
372 $d1 .
373 $d1 . hl7Text($pcrow['procedure_code']) .
374 $d2 . hl7Text($pcrow['procedure_name']) .
375 $d1 . hl7Priority($porow['order_priority']) . // S=Stat, R=Routine
376 $d1 .
377 $d1 . hl7Time($porow['date_collected']) . // Observation Date/Time
378 str_repeat($d1, 8) . // OBR 8-15 not used
379 $d1 . hl7Text($porow['docnpi']) . // Physician ID
380 $d2 . hl7Text($porow['doclname']) . // Last Name
381 $d2 . hl7Text($porow['docfname']) . // First Name
382 $d1 .
383 $d1 . (count($payers) ? 'I' : 'P') . // I=Insurance, C=Client, P=Self Pay
384 str_repeat($d1, 8) . // OBR 19-26 not used
385 $d1 . '0' . // ?
386 $d0;
388 // Diagnoses. Currently hard-coded for ICD9 and we'll surely want to make
389 // this more flexible (probably when some lab needs another diagnosis type).
390 $setid2 = 0;
391 if (!empty($pcrow['diagnoses'])) {
392 $relcodes = explode(';', $pcrow['diagnoses']);
393 foreach ($relcodes as $codestring) {
394 if ($codestring === '') {
395 continue;
398 list($codetype, $code) = explode(':', $codestring);
399 if ($codetype !== 'ICD9') {
400 continue;
403 $desc = lookup_code_descriptions($codestring);
404 $out .= "DG1" .
405 $d1 . ++$setid2 . // Set ID
406 $d1 . // Diagnosis Coding Method
407 $d1 . $code . // Diagnosis Code
408 $d1 . hl7Text($desc) . // Diagnosis Description
409 $d0;
413 // Order entry questions and answers.
414 $qres = sqlStatement(
415 "SELECT " .
416 "a.question_code, a.answer, q.fldtype " .
417 "FROM procedure_answers AS a " .
418 "LEFT JOIN procedure_questions AS q ON " .
419 "q.lab_id = ? " .
420 "AND q.procedure_code = ? AND " .
421 "q.question_code = a.question_code " .
422 "WHERE " .
423 "a.procedure_order_id = ? AND " .
424 "a.procedure_order_seq = ? " .
425 "ORDER BY q.seq, a.answer_seq",
426 array($porow['ppid'], $pcrow['procedure_code'], $orderid, $pcrow['procedure_order_seq'])
428 $setid2 = 0;
429 while ($qrow = sqlFetchArray($qres)) {
430 // Formatting of these answer values may be lab-specific and we'll figure
431 // out how to deal with that as more labs are supported.
432 $answer = trim($qrow['answer']);
433 $fldtype = $qrow['fldtype'];
434 $datatype = 'ST';
435 if ($fldtype == 'N') {
436 $datatype = "NM";
437 } else if ($fldtype == 'D') {
438 $answer = hl7Date($answer);
439 } else if ($fldtype == 'G') {
440 $weeks = intval($answer / 7);
441 $days = $answer % 7;
442 $answer = $weeks . 'wks ' . $days . 'days';
445 $out .= "OBX" .
446 $d1 . ++$setid2 . // Set ID
447 $d1 . $datatype . // Structure of observation value
448 $d1 . hl7Text($qrow['question_code']) . // Clinical question code
449 $d1 .
450 $d1 . hl7Text($answer) . // Clinical question answer
451 $d0;
455 return '';
459 * Transmit HL7 for the specified lab.
461 * @param integer $ppid Procedure provider ID.
462 * @param string $out The HL7 text to be sent.
463 * @return string Error text, or empty if no errors.
465 function send_hl7_order($ppid, $out)
467 global $srcdir;
469 $d0 = "\r";
471 $pprow = sqlQuery("SELECT * FROM procedure_providers " .
472 "WHERE ppid = ?", array($ppid));
473 if (empty($pprow)) {
474 return xl('Procedure provider') . " $ppid " . xl('not found');
477 $protocol = $pprow['protocol'];
478 $remote_host = $pprow['remote_host'];
480 // Extract MSH-10 which is the message control ID.
481 $segmsh = explode(substr($out, 3, 1), substr($out, 0, strpos($out, $d0)));
482 $msgid = $segmsh[9];
483 if (empty($msgid)) {
484 return xl('Internal error: Cannot find MSH-10');
487 if ($protocol == 'DL' || $pprow['orders_path'] === '') {
488 header("Pragma: public");
489 header("Expires: 0");
490 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
491 header("Content-Type: application/force-download");
492 header("Content-Disposition: attachment; filename=order_$msgid.hl7");
493 header("Content-Description: File Transfer");
494 echo $out;
495 exit;
496 } else if ($protocol == 'SFTP') {
497 // Compute the target path/file name.
498 $filename = $msgid . '.txt';
499 if ($pprow['orders_path']) {
500 $filename = $pprow['orders_path'] . '/' . $filename;
503 // Connect to the server and write the file.
504 $sftp = new \phpseclib\Net\SFTP($remote_host);
505 if (!$sftp->login($pprow['login'], $pprow['password'])) {
506 return xl('Login to this remote host failed') . ": '$remote_host'";
509 if (!$sftp->put($filename, $out)) {
510 return xl('Creating this file on remote host failed') . ": '$filename'";
512 } else if ($protocol == 'FS') {
513 // Compute the target path/file name.
514 $filename = $msgid . '.txt';
515 if ($pprow['orders_path']) {
516 $filename = $pprow['orders_path'] . '/' . $filename;
519 $fh = fopen("$filename", 'w');
520 if ($fh) {
521 fwrite($fh, $out);
522 fclose($fh);
523 } else {
524 return xl('Cannot create file') . ' "' . "$filename" . '"';
526 } // TBD: Insert "else if ($protocol == '???') {...}" to support other protocols.
528 else {
529 return xl('This protocol is not implemented') . ": '$protocol'";
532 // Falling through to here indicates success.
533 newEvent(
534 "proc_order_xmit",
535 $_SESSION['authUser'],
536 $_SESSION['authProvider'],
538 "ID: $msgid Protocol: $protocol Host: $remote_host"
540 return '';