RTL fixes, take 2:
[openemr.git] / interface / patient_file / report / custom_report.php
blob12447f97d555410f20df328f8814dc0fa05dcf9b
1 <?php
2 use ESign\Api;
3 /**
5 * Patient custom report.
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 3
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 Brady Miller <brady@sparmy.com>
20 * @author Ken Chapple <ken@mi-squared.com>
21 * @author Tony McCormick <tony@mi-squared.com>
22 * @link http://www.open-emr.org
25 require_once("../../globals.php");
26 require_once("$srcdir/forms.inc");
27 require_once("$srcdir/billing.inc");
28 require_once("$srcdir/pnotes.inc");
29 require_once("$srcdir/patient.inc");
30 require_once("$srcdir/options.inc.php");
31 require_once("$srcdir/acl.inc");
32 require_once("$srcdir/lists.inc");
33 require_once("$srcdir/report.inc");
34 require_once("$srcdir/classes/Document.class.php");
35 require_once("$srcdir/classes/Note.class.php");
36 require_once("$srcdir/formatting.inc.php");
37 require_once("$srcdir/htmlspecialchars.inc.php");
38 require_once("$srcdir/formdata.inc.php");
39 require_once(dirname(__file__) . "/../../../custom/code_types.inc.php");
40 require_once $GLOBALS['srcdir'].'/ESign/Api.php';
41 require_once($GLOBALS["include_root"] . "/orders/single_order_results.inc.php");
42 if ($GLOBALS['gbl_portal_cms_enable']) {
43 require_once($GLOBALS["include_root"] . "/cmsportal/portal.inc.php");
46 // For those who care that this is the patient report.
47 $GLOBALS['PATIENT_REPORT_ACTIVE'] = true;
49 $PDF_OUTPUT = empty($_POST['pdf']) ? 0 : intval($_POST['pdf']);
51 if ($PDF_OUTPUT) {
52 require_once("$srcdir/html2pdf/vendor/autoload.php");
53 $pdf = new HTML2PDF ($GLOBALS['pdf_layout'],
54 $GLOBALS['pdf_size'],
55 $GLOBALS['pdf_language'],
56 true, // default unicode setting is true
57 'UTF-8', // default encoding setting is UTF-8
58 array($GLOBALS['pdf_left_margin'],$GLOBALS['pdf_top_margin'],$GLOBALS['pdf_right_margin'],$GLOBALS['pdf_bottom_margin']),
59 $_SESSION['language_direction'] == 'rtl' ? true : false
61 //set 'dejavusans' for now. which is supported by a lot of languages - http://dejavu-fonts.org/wiki/Main_Page
62 //TODO: can have this selected as setting in globals after we have more experience with this to fully support internationalization.
63 $pdf->setDefaultFont('dejavusans');
65 ob_start();
68 // get various authorization levels
69 $auth_notes_a = acl_check('encounters', 'notes_a');
70 $auth_notes = acl_check('encounters', 'notes');
71 $auth_coding_a = acl_check('encounters', 'coding_a');
72 $auth_coding = acl_check('encounters', 'coding');
73 $auth_relaxed = acl_check('encounters', 'relaxed');
74 $auth_med = acl_check('patients' , 'med');
75 $auth_demo = acl_check('patients' , 'demo');
77 $esignApi = new Api();
79 $printable = empty($_GET['printable']) ? false : true;
80 if ($PDF_OUTPUT) { $printable = true; }
81 unset($_GET['printable']);
83 // Number of columns in tables for insurance and encounter forms.
84 $N = $PDF_OUTPUT ? 4 : 6;
86 $first_issue = 1;
88 function getContent() {
89 global $web_root, $webserver_root;
90 $content = ob_get_clean();
91 // Fix a nasty html2pdf bug - it ignores document root!
92 $i = 0;
93 $wrlen = strlen($web_root);
94 $wsrlen = strlen($webserver_root);
95 while (true) {
96 $i = stripos($content, " src='/", $i + 1);
97 if ($i === false) break;
98 if (substr($content, $i+6, $wrlen) === $web_root &&
99 substr($content, $i+6, $wsrlen) !== $webserver_root)
101 $content = substr($content, 0, $i + 6) . $webserver_root . substr($content, $i + 6 + $wrlen);
104 return $content;
107 function postToGet($arin) {
108 $getstring="";
109 foreach ($arin as $key => $val) {
110 if (is_array($val)) {
111 foreach ($val as $k => $v) {
112 $getstring .= urlencode($key . "[]") . "=" . urlencode($v) . "&";
115 else {
116 $getstring .= urlencode($key) . "=" . urlencode($val) . "&";
119 return $getstring;
123 <?php if ($PDF_OUTPUT) { ?>
124 <link rel="stylesheet" href="<?php echo $webserver_root . '/interface/themes/style_pdf.css' ?>" type="text/css">
125 <link rel="stylesheet" type="text/css" href="<?php echo $webserver_root; ?>/library/ESign/css/esign_report.css" />
126 <?php } else {?>
127 <html>
128 <head>
129 <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css">
130 <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/library/ESign/css/esign_report.css" />
131 <?php } ?>
133 <?php // do not show stuff from report.php in forms that is encaspulated
134 // by div of navigateLink class. Specifically used for CAMOS, but
135 // can also be used by other forms that require output in the
136 // encounter listings output, but not in the custom report. ?>
137 <style>
138 div.navigateLink {display:none;}
139 .hilite {background-color: #FFFF00;}
140 .hilite2 {background-color: transparent;}
141 mark {background-color: #FFFF00;}
142 .css_button{cursor:pointer;}
143 .next {background-color: #FFFF00;}
144 #search_options{
145 position:fixed;
146 left:0px;
147 top:0px;
148 z-index:10;
149 border-bottom: solid thin #6D6D6D;
150 padding:0% 2% 0% 2.5%;
152 </style>
154 <?php if (!$PDF_OUTPUT) { ?>
156 <script type="text/javascript" src="<?php echo $GLOBALS['web_root']?>/library/js/jquery-1.5.js"></script>
157 <script type="text/javascript" src="<?php echo $GLOBALS['web_root']?>/library/js/SearchHighlight.js"></script>
158 <script type="text/javascript">var $j = jQuery.noConflict();</script>
160 <?php // if the track_anything form exists, then include the styling
161 if (file_exists(dirname(__FILE__) . "/../../forms/track_anything/style.css")) { ?>
162 <link rel="stylesheet" href="<?php echo $GLOBALS['web_root']?>/interface/forms/track_anything/style.css" type="text/css">
163 <?php } ?>
165 <script type="text/javascript">
167 // Code for search & Highlight
168 function reset_highlight(form_id,form_dir,class_name) { // Removes <span class='hilite' id=''>VAL</span> with VAL
169 $j("."+class_name).each(function(){
170 val = document.getElementById(this.id).innerHTML;
171 $j("#"+this.id).replaceWith(val);
175 var res_id = 0;
176 function doSearch(form_id,form_dir,exact,class_name,keys,case_sensitive) { // Uses jquery SearchHighlight Plug in
177 var options ={};
178 var keys = keys.replace(/^\s+|\s+$/g, '') ;
179 options = {
180 exact :exact,
181 style_name :class_name,
182 style_name_suffix:false,
183 highlight:'#search_div_'+form_id+'_'+form_dir,
184 keys :keys,
185 set_case_sensitive:case_sensitive
187 $j(document).SearchHighlight(options);
188 $j('.'+class_name).each(function(){
189 res_id = res_id+1;
190 $j(this).attr("id",'result_'+res_id);
194 function remove_mark(form_id,form_dir){ // Removes all <mark> and </mark> tags
195 var match1 = null;
196 var src_str = document.getElementById('search_div_'+form_id+'_'+form_dir).innerHTML;
197 var re = new RegExp('<mark>',"gi");
198 var match2 = src_str.match(re);
199 if(match2){
200 src_str = src_str.replace(re,'');
202 var match2 = null;
203 re = new RegExp('</mark>',"gi");
204 if(match2){
205 src_str = src_str.replace(re,'');
207 document.getElementById('search_div_'+form_id+'_'+form_dir).innerHTML=src_str;
209 function mark_hilight(form_id,form_dir,keys,case_sensitive){ // Adds <mark>match_val</mark> tags
210 keys = keys.replace(/^\s+|\s+$/g, '') ;
211 if(keys == '') return;
212 var src_str = $j('#search_div_'+form_id+'_'+form_dir).html();
213 var term = keys;
214 if((/\s+/).test(term) == true || (/['""-]{1,}/).test(term) == true){
215 term = term.replace(/(\s+)/g,"(<[^>]+>)*$1(<[^>]+>)*");
216 if(case_sensitive == true){
217 var pattern = new RegExp("("+term+")", "g");
219 else{
220 var pattern = new RegExp("("+term+")", "ig");
222 src_str = src_str.replace(/[\s\r\n]{1,}/g, ' '); // Replace text area newline or multiple spaces with single space
223 src_str = src_str.replace(pattern, "<mark class='hilite'>$1</mark>");
224 src_str = src_str.replace(/(<mark class=\'hilite\'>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/g,"$1</mark>$2<mark class='hilite'>$4");
225 $j('#search_div_'+form_id+'_'+form_dir).html(src_str);
226 $j('.hilite').each(function(){
227 res_id = res_id+1;
228 $j(this).attr("id",'result_'+res_id);
230 }else{
231 if(case_sensitive == true)
232 doSearch(form_id,form_dir,'partial','hilite',keys,'true');
233 else
234 doSearch(form_id,form_dir,'partial','hilite',keys,'false');
238 var forms_array;
239 var res_array = Array();
240 function find_all(){ // for each report the function mark_hilight() is called
241 case_sensitive = false;
242 if ($j('#search_case').attr('checked')) {
243 case_sensitive = true;
245 var keys = document.getElementById('search_element').value;
246 var match = null;
247 match = keys.match(/[\^\$\.\|\?\+\(\)\\~`\!@#%&\+={}<>]{1,}/);
248 if(match){
249 document.getElementById('alert_msg').innerHTML='<?php echo xla('Special characters are not allowed');?>..!';
250 return;
252 else{
253 document.getElementById('alert_msg').innerHTML='';
256 forms_arr = document.getElementById('forms_to_search');
257 for (var i = 0; i < forms_arr.options.length; i++) {
258 if(forms_arr.options[i].selected ==true){
259 $j('.class_'+forms_arr.options[i].value).each(function(){
260 id_arr = this.id.split('search_div_');
261 var re = new RegExp('_','i');
262 new_id = id_arr[1].replace(re, "|");
263 new_id_arr = new_id.split('|');
264 form_id = new_id_arr[0];
265 form_dir = new_id_arr[1];
266 mark_hilight(form_id,form_dir,keys,case_sensitive);
271 if($j('.hilite').length <1){
272 if(keys != '')
273 document.getElementById('alert_msg').innerHTML='<?php echo xla('No results found');?>..!';
275 else{
276 document.getElementById('alert_msg').innerHTML='';
277 f_id = $j('.hilite:first').attr('id');
278 element = document.getElementById(f_id);
279 element.scrollIntoView(false);
284 function remove_mark_all(){ // clears previous search results if exists
285 $j('.report_search_div').each(function(){
286 var id_arr = this.id.split('search_div_');
287 var re = new RegExp('_','i');
288 var new_id = id_arr[1].replace(re, "|");
289 var new_id_arr = new_id.split('|');
290 var form_id = new_id_arr[0];
291 var form_dir = new_id_arr[1];
292 reset_highlight(form_id,form_dir,'hilite');
293 reset_highlight(form_id,form_dir,'hilite2');
294 remove_mark(form_id,form_dir);
295 res_id = 0;
296 res_array =[];
300 var last_visited = -1;
301 var last_clicked = "";
302 var cur_res =0;
303 function next(w_count){
304 cur_res++;
305 remove_mark_all();
306 find_all();
307 var index = -1;
308 if(!($j(".hilite")[0])) {
309 return;
311 $j('.hilite').each(function(){
312 if($j(this).is(":visible")){
313 index = index+1;
314 res_array[index] = this.id;
317 $j('.hilite').addClass("hilite2");
318 $j('.hilite').removeClass("hilite");
319 var array_count = res_array.length;
320 if(last_clicked == "prev"){
321 last_visited = last_visited + (w_count-1);
323 last_clicked = "next";
324 for(k=0;k<w_count;k++){
325 last_visited ++;
326 if(last_visited == array_count){
327 cur_res = 0;
328 last_visited = -1;
329 next(w_count);
330 return;
332 $j("#"+res_array[last_visited]).addClass("next");
334 element = document.getElementById(res_array[last_visited]);
335 element.scrollIntoView(false);
339 function prev(w_count){
340 cur_res--;
341 remove_mark_all();
342 find_all();
343 var index = -1;
344 if(!($j(".hilite")[0])) {
345 return;
347 $j('.hilite').each(function(){
348 if($j(this).is(":visible")){
349 index = index+1;
350 res_array[index] = this.id;
353 $j('.hilite').addClass("hilite2");
354 $j('.hilite').removeClass("hilite");
355 var array_count = res_array.length;
356 if(last_clicked == "next"){
357 last_visited = last_visited - (w_count-1);
359 last_clicked = "prev";
360 for(k=0;k<w_count;k++){
361 last_visited --;
362 if(last_visited < 0){
363 cur_res = (array_count/w_count) + 1;
364 last_visited = array_count;
365 prev(w_count);
366 return;
368 $j("#"+res_array[last_visited]).addClass("next");
372 element = document.getElementById(res_array[last_visited]);
373 element.scrollIntoView(false);
375 function clear_last_visit(){
376 last_visited = -1;
377 cur_res = 0;
378 res_array = [];
379 last_clicked = "";
382 function get_word_count(form_id,form_dir,keys,case_sensitive){
383 keys = keys.replace(/^\s+|\s+$/g, '') ;
384 if(keys == '') return;
385 var src_str = $j('#search_div_'+form_id+'_'+form_dir).html();
386 var term = keys;
387 if((/\s+/).test(term) == true){
388 term = term.replace(/(\s+)/g,"(<[^>]+>)*$1(<[^>]+>)*");
389 if(case_sensitive == true){
390 var pattern = new RegExp("("+term+")", "");
392 else{
393 var pattern = new RegExp("("+term+")", "i");
395 src_str = src_str.replace(/[\s\r\n]{1,}/g, ' '); // Replace text area newline or multiple spaces with single space
396 src_str = src_str.replace(pattern, "<mark class='hilite'>$1</mark>");
397 src_str = src_str.replace(/(<mark class=\'hilite\'>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark class='hilite'>$4");
398 var res =[];
399 res = src_str.match(/<mark class=\'hilite\'>/g);
400 if(res != null){
401 return res.length;
403 }else{
404 return 1;
408 function next_prev(action){
409 var w_count =0;
410 case_sensitive = false;
411 if ($j('#search_case').attr('checked')) {
412 case_sensitive = true;
414 var keys = document.getElementById('search_element').value;
415 var match = null;
416 match = keys.match(/[\^\$\.\|\?\+\(\)\\~`\!@#%&\+={}<>]{1,}/);
417 if(match){
418 document.getElementById('alert_msg').innerHTML='<?php echo xla('Special characters are not allowed');?>..!';
419 return;
421 else{
422 document.getElementById('alert_msg').innerHTML='';
424 forms_arr = document.getElementById('forms_to_search');
425 for (var i = 0; i < forms_arr.options.length; i++) {
426 if(forms_arr.options[i].selected ==true){
427 $j('.class_'+forms_arr.options[i].value).each(function(){
428 id_arr = this.id.split('search_div_');
429 var re = new RegExp('_','i');
430 new_id = id_arr[1].replace(re, "|");
431 new_id_arr = new_id.split('|');
432 form_id = new_id_arr[0];
433 form_dir = new_id_arr[1];
434 w_count = get_word_count(form_id,form_dir,keys,case_sensitive);
436 if(!isNaN(w_count)){
437 break;
441 if(w_count <1){
442 if(keys != '')
443 document.getElementById('alert_msg').innerHTML='<?php echo xla('No results found');?>..!';
445 else{
446 document.getElementById('alert_msg').innerHTML='';
447 if(action == 'next'){
448 next(w_count);
450 else if (action == 'prev'){
451 prev(w_count);
453 var tot_res = res_array.length/w_count;
454 if(tot_res > 0){
455 document.getElementById('alert_msg').innerHTML='<?php echo xla('Showing result');?> '+cur_res+' <?php echo xla('of');?> '+tot_res;
460 </script>
461 </head>
462 <body class="body_top" style="padding-top:95px;">
463 <?php } ?>
464 <div id="report_custom" style="width:100%;"> <!-- large outer DIV -->
466 <?php
467 if (sizeof($_GET) > 0) { $ar = $_GET; }
468 else { $ar = $_POST; }
470 if ($printable) {
471 /*******************************************************************
472 $titleres = getPatientData($pid, "fname,lname,providerID");
473 $sql = "SELECT * FROM facility ORDER BY billing_location DESC LIMIT 1";
474 *******************************************************************/
475 $titleres = getPatientData($pid, "fname,lname,providerID,DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS");
476 if ($_SESSION['pc_facility']) {
477 $sql = "select * from facility where id=" . $_SESSION['pc_facility'];
478 } else {
479 $sql = "SELECT * FROM facility ORDER BY billing_location DESC LIMIT 1";
481 /******************************************************************/
482 $db = $GLOBALS['adodb']['db'];
483 $results = $db->Execute($sql);
484 $facility = array();
485 if (!$results->EOF) {
486 $facility = $results->fields;
488 // Setup Headers and Footers for html2PDF only Download
489 // in HTML view it's just one line at the top of page 1
490 echo '<page_header style="text-align:right;" class="custom-tag"> ' . xlt("PATIENT") . ':' . text($titleres['lname']) . ', ' . text($titleres['fname']) . ' - ' . $titleres['DOB_TS'] . '</page_header> ';
491 echo '<page_footer style="text-align:right;" class="custom-tag">' . xlt('Generated on') . ' ' . oeFormatShortDate() . ' - ' . text($facility['name']) . ' ' . text($facility['phone']) . '</page_footer>';
493 // Use logo if it exists as 'practice_logo.gif' in the site dir
494 // old code used the global custom dir which is no longer a valid
495 $practice_logo = "$OE_SITE_DIR/images/practice_logo.gif";
496 if (file_exists($practice_logo)) {
497 echo "<img src='$practice_logo' align='left'><br />\n";
500 <h2><?php echo $facility['name'] ?></h2>
501 <?php echo $facility['street'] ?><br>
502 <?php echo $facility['city'] ?>, <?php echo $facility['state'] ?> <?php echo $facility['postal_code'] ?><br clear='all'>
503 <?php echo $facility['phone'] ?><br>
505 <a href="javascript:window.close();"><span class='title'><?php echo $titleres['fname'] . " " . $titleres['lname']; ?></span></a><br>
506 <span class='text'><?php xl('Generated on','e'); ?>: <?php echo oeFormatShortDate(); ?></span>
507 <br><br>
509 <?php
512 else { // not printable
515 <a href="patient_report.php" onclick='top.restoreSession()'>
516 <span class='title'><?php xl('Patient Report','e'); ?></span>
517 <span class='back'><?php echo $tback;?></span>
518 </a><br><br>
519 <a href="custom_report.php?printable=1&<?php print postToGet($ar); ?>" class='link_submit' target='new' onclick='top.restoreSession()'>
520 [<?php xl('Printable Version','e'); ?>]
521 </a><br>
522 <div class="report_search_bar" style="width:100%;" id="search_options">
523 <table style="width:100%;">
524 <tr>
525 <td>
526 <input type="text" onKeyUp="clear_last_visit();remove_mark_all();find_all();" name="search_element" id="search_element" style="width:180px;"/>
527 </td>
528 <td>
529 <a class="css_button" onClick="clear_last_visit();remove_mark_all();find_all();" ><span><?php echo xlt('Find'); ?></span></a>
530 </td>
531 <td>
532 <a class="css_button" onClick="next_prev('prev');" ><span><?php echo xlt('Prev'); ?></span></a>
533 </td>
534 <td>
535 <a class="css_button" onClick="next_prev('next');" ><span><?php echo xlt('Next'); ?></span></a>
536 </td>
537 <td>
538 <input type="checkbox" onClick="clear_last_visit();remove_mark_all();find_all();" name="search_case" id="search_case" />
539 </td>
540 <td>
541 <span><?php echo xlt('Match case'); ?></span>
542 </td>
543 <td style="padding-left:10px;">
544 <span class="text"><b><?php echo xlt('Search In'); ?>:</b></span>
545 <br>
546 <?php
547 $form_id_arr = array();
548 $form_dir_arr = array();
549 $last_key ='';
550 //ksort($ar);
551 foreach ($ar as $key_search => $val_search) {
552 if ($key_search == 'pdf' || $key_search == '' ) continue;
553 if (($auth_notes_a || $auth_notes || $auth_coding_a || $auth_coding || $auth_med || $auth_relaxed)) {
554 preg_match('/^(.*)_(\d+)$/', $key_search, $res_search);
555 $form_id_arr[] = add_escape_custom($res_search[2]);
556 $form_dir_arr[] = add_escape_custom($res_search[1]);
559 //echo json_encode(json_encode($array_key_id));
560 if(sizeof($form_id_arr)>0){
561 $query = "SELECT DISTINCT(form_name),formdir FROM forms WHERE form_id IN ( '".implode("','",$form_id_arr)."') AND formdir IN ( '".implode("','",$form_dir_arr)."')";
562 $arr = sqlStatement($query);
563 echo "<select multiple size='4' style='width:300px;' id='forms_to_search' onchange='clear_last_visit();remove_mark_all();find_all();' >";
564 while($res_forms_ids = sqlFetchArray($arr)){
565 echo "<option value='".attr($res_forms_ids['formdir'])."' selected>".text($res_forms_ids['form_name'])."</option>";
567 echo "</select>";
570 </td>
571 <td style="padding-left:10px;;width:30%;">
572 <span id ='alert_msg' style='color:red;'></span>
573 </td>
574 </tr>
575 </table>
576 </div>
577 <?php
578 } // end not printable ?>
580 <?php
582 // include ALL form's report.php files
583 $inclookupres = sqlStatement("select distinct formdir from forms where pid = '$pid' AND deleted=0");
584 while($result = sqlFetchArray($inclookupres)) {
585 // include_once("{$GLOBALS['incdir']}/forms/" . $result{"formdir"} . "/report.php");
586 $formdir = $result['formdir'];
587 if (substr($formdir,0,3) == 'LBF')
588 include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
589 else
590 include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
593 // For each form field from patient_report.php...
595 foreach ($ar as $key => $val) {
596 if ($key == 'pdf') continue;
598 // These are the top checkboxes (demographics, allergies, etc.).
600 if (stristr($key,"include_")) {
602 if ($val == "demographics") {
604 echo "<hr />";
605 echo "<div class='text demographics' id='DEM'>\n";
606 print "<h1>".xl('Patient Data').":</h1>";
607 // printRecDataOne($patient_data_array, getRecPatientData ($pid), $N);
608 $result1 = getPatientData($pid);
609 $result2 = getEmployerData($pid);
610 echo " <table>\n";
611 display_layout_rows('DEM', $result1, $result2);
612 echo " </table>\n";
613 echo "</div>\n";
615 } elseif ($val == "history") {
617 echo "<hr />";
618 echo "<div class='text history' id='HIS'>\n";
619 if (acl_check('patients', 'med')) {
620 print "<h1>".xl('History Data').":</h1>";
621 // printRecDataOne($history_data_array, getRecHistoryData ($pid), $N);
622 $result1 = getHistoryData($pid);
623 echo " <table>\n";
624 display_layout_rows('HIS', $result1);
625 echo " </table>\n";
627 echo "</div>";
629 // } elseif ($val == "employer") {
630 // print "<br><span class='bold'>".xl('Employer Data').":</span><br>";
631 // printRecDataOne($employer_data_array, getRecEmployerData ($pid), $N);
633 } elseif ($val == "insurance") {
635 echo "<hr />";
636 echo "<div class='text insurance'>";
637 echo "<h1>".xl('Insurance Data').":</h1>";
638 print "<br><span class=bold>".xl('Primary Insurance Data').":</span><br>";
639 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"primary"), $N);
640 print "<span class=bold>".xl('Secondary Insurance Data').":</span><br>";
641 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"secondary"), $N);
642 print "<span class=bold>".xl('Tertiary Insurance Data').":</span><br>";
643 printRecDataOne($insurance_data_array, getRecInsuranceData ($pid,"tertiary"), $N);
644 echo "</div>";
646 } elseif ($val == "billing") {
648 echo "<hr />";
649 echo "<div class='text billing'>";
650 print "<h1>".xl('Billing Information').":</h1>";
651 if (count($ar['newpatient']) > 0) {
652 $billings = array();
653 echo "<table>";
654 echo "<tr><td width='400' class='bold'>Code</td><td class='bold'>".xl('Fee')."</td></tr>\n";
655 $total = 0.00;
656 $copays = 0.00;
657 foreach ($ar['newpatient'] as $be) {
658 $ta = explode(":",$be);
659 $billing = getPatientBillingEncounter($pid,$ta[1]);
660 $billings[] = $billing;
661 foreach ($billing as $b) {
662 echo "<tr>\n";
663 echo "<td class=text>";
664 echo $b['code_type'] . ":\t" . $b['code'] . "&nbsp;". $b['modifier'] . "&nbsp;&nbsp;&nbsp;" . $b['code_text'] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
665 echo "</td>\n";
666 echo "<td class=text>";
667 echo oeFormatMoney($b['fee']);
668 echo "</td>\n";
669 echo "</tr>\n";
670 $total += $b['fee'];
671 if ($b['code_type'] == "COPAY") {
672 $copays += $b['fee'];
676 echo "<tr><td>&nbsp;</td></tr>";
677 echo "<tr><td class=bold>".xl('Sub-Total')."</td><td class=text>" . oeFormatMoney($total + abs($copays)) . "</td></tr>";
678 echo "<tr><td class=bold>".xl('Paid')."</td><td class=text>" . oeFormatMoney(abs($copays)) . "</td></tr>";
679 echo "<tr><td class=bold>".xl('Total')."</td><td class=text>" . oeFormatMoney($total) . "</td></tr>";
680 echo "</table>";
681 echo "<pre>";
682 //print_r($billings);
683 echo "</pre>";
684 } else {
685 printPatientBilling($pid);
687 echo "</div>\n"; // end of billing DIV
689 /****
691 } elseif ($val == "allergies") {
693 print "<span class=bold>Patient Allergies:</span><br>";
694 printListData($pid, "allergy", "1");
696 } elseif ($val == "medications") {
698 print "<span class=bold>Patient Medications:</span><br>";
699 printListData($pid, "medication", "1");
701 } elseif ($val == "medical_problems") {
703 print "<span class=bold>Patient Medical Problems:</span><br>";
704 printListData($pid, "medical_problem", "1");
706 ****/
708 } elseif ($val == "immunizations") {
710 if (acl_check('patients', 'med')) {
711 echo "<hr />";
712 echo "<div class='text immunizations'>\n";
713 print "<h1>".xl('Patient Immunization').":</h1>";
714 $sql = "select i1.immunization_id, i1.administered_date, substring(i1.note,1,20) as immunization_note, c.code_text_short ".
715 " from immunizations i1 ".
716 " left join code_types ct on ct.ct_key = 'CVX' ".
717 " left join codes c on c.code_type = ct.ct_id AND i1.cvx_code = c.code ".
718 " where i1.patient_id = '$pid' and i1.added_erroneously = 0 ".
719 " order by administered_date desc";
720 $result = sqlStatement($sql);
721 while ($row=sqlFetchArray($result)) {
722 // Figure out which name to use (ie. from cvx list or from the custom list)
723 if ($GLOBALS['use_custom_immun_list']) {
724 $vaccine_display = generate_display_field(array('data_type'=>'1','list_id'=>'immunizations'), $row['immunization_id']);
726 else {
727 if (!empty($row['code_text_short'])) {
728 $vaccine_display = htmlspecialchars( xl($row['code_text_short']), ENT_NOQUOTES);
730 else {
731 $vaccine_display = generate_display_field(array('data_type'=>'1','list_id'=>'immunizations'), $row['immunization_id']);
734 echo $row['administered_date'] . " - " . $vaccine_display;
735 if ($row['immunization_note']) {
736 echo " - " . $row['immunization_note'];
738 echo "<br>\n";
740 echo "</div>\n";
743 // communication report
744 } elseif ($val == "batchcom") {
746 echo "<hr />";
747 echo "<div class='text transactions'>\n";
748 print "<h1>".xl('Patient Communication sent').":</h1>";
749 $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='$pid'";
750 // echo $sql;
751 $result = sqlStatement($sql);
752 while ($row=sqlFetchArray($result)) {
753 echo $row{'batchcom_data'}.", By: ".$row{'user_name'}."<br>Text:<br> ".$row{'msg_txt'}."<br>\n";
755 echo "</div>\n";
757 } elseif ($val == "notes") {
759 echo "<hr />";
760 echo "<div class='text notes'>\n";
761 print "<h1>".xl('Patient Notes').":</h1>";
762 printPatientNotes($pid);
763 echo "</div>";
765 } elseif ($val == "transactions") {
767 echo "<hr />";
768 echo "<div class='text transactions'>\n";
769 print "<h1>".xl('Patient Transactions').":</h1>";
770 printPatientTransactions($pid);
771 echo "</div>";
775 } else {
777 // Documents is an array of checkboxes whose values are document IDs.
779 if ($key == "documents") {
781 echo "<hr />";
782 echo "<div class='text documents'>";
783 foreach($val as $valkey => $valvalue) {
784 $document_id = $valvalue;
785 if (!is_numeric($document_id)) continue;
786 $d = new Document($document_id);
787 $fname = basename($d->get_url());
788 $couch_docid = $d->get_couch_docid();
789 $couch_revid = $d->get_couch_revid();
790 echo "<h1>" . xl('Document') . " '" . $fname ."'</h1>";
791 $n = new Note();
792 $notes = $n->notes_factory($d->get_id());
793 if (!empty($notes)) echo "<table>";
794 foreach ($notes as $note) {
795 echo '<tr>';
796 echo '<td>' . xl('Note') . ' #' . $note->get_id() . '</td>';
797 echo '</tr>';
798 echo '<tr>';
799 echo '<td>' . xl('Date') . ': ' . oeFormatShortDate($note->get_date()) . '</td>';
800 echo '</tr>';
801 echo '<tr>';
802 echo '<td>'.$note->get_note().'<br><br></td>';
803 echo '</tr>';
805 if (!empty($notes)) echo "</table>";
807 $url_file = $d->get_url_filepath();
808 if($couch_docid && $couch_revid){
809 $url_file = $d->get_couch_url($pid,$encounter);
811 // Collect filename and path
812 $from_all = explode("/",$url_file);
813 $from_filename = array_pop($from_all);
814 $from_pathname_array = array();
815 for ($i=0;$i<$d->get_path_depth();$i++) {
816 $from_pathname_array[] = array_pop($from_all);
818 $from_pathname_array = array_reverse($from_pathname_array);
819 $from_pathname = implode("/",$from_pathname_array);
821 if($couch_docid && $couch_revid) {
822 $from_file = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $from_filename;
823 $to_file = substr($from_file, 0, strrpos($from_file, '.')) . '_converted.jpg';
825 else {
826 $from_file = $GLOBALS["fileroot"] . "/sites/" . $_SESSION['site_id'] .
827 '/documents/' . $from_pathname . '/' . $from_filename;
828 $to_file = substr($from_file, 0, strrpos($from_file, '.')) . '_converted.jpg';
830 //Extract the extension by the mime/type and not the file name extension
831 $image_data = getimagesize($from_file);
832 $extension = image_type_to_extension($image_data[2]);
833 if ($extension == ".png" || $extension == ".jpg" || $extension == ".jpeg" || $extension == ".gif") {
834 if ($PDF_OUTPUT) {
835 // OK to link to the image file because it will be accessed by the
836 // HTML2PDF parser and not the browser.
837 $from_rel = $web_root . substr($from_file, strlen($webserver_root));
838 echo "<img src='$from_rel'";
839 // Flag images with excessive width for possible stylesheet action.
840 $asize = getimagesize($from_file);
841 if ($asize[0] > 750) echo " class='bigimage'";
842 echo " /><br><br>";
844 else {
845 echo "<img src='" . $GLOBALS['webroot'] .
846 "/controller.php?document&retrieve&patient_id=&document_id=" .
847 $document_id . "&as_file=false'><br><br>";
850 else {
852 // Most clinic documents are expected to be PDFs, and in that happy case
853 // we can avoid the lengthy image conversion process.
854 if ($PDF_OUTPUT && $extension == ".pdf") {
855 // HTML to PDF conversion will fail if there are open tags.
856 echo "</div></div>\n";
857 $content = getContent();
858 // $pdf->setDefaultFont('Arial');
859 $pdf->writeHTML($content, false);
860 $pagecount = $pdf->pdf->setSourceFile($from_file);
861 for($i = 0; $i < $pagecount; ++$i){
862 $pdf->pdf->AddPage();
863 $itpl = $pdf->pdf->importPage($i + 1, '/MediaBox');
864 $pdf->pdf->useTemplate($itpl);
866 // Make sure whatever follows is on a new page.
867 $pdf->pdf->AddPage();
868 // Resume output buffering and the above-closed tags.
869 ob_start();
870 echo "<div><div class='text documents'>\n";
872 else {
873 if (! is_file($to_file)) exec("convert -density 200 \"$from_file\" -append -resize 850 \"$to_file\"");
874 if (is_file($to_file)) {
875 if ($PDF_OUTPUT) {
876 // OK to link to the image file because it will be accessed by the
877 // HTML2PDF parser and not the browser.
878 echo "<img src='$to_file'><br><br>";
880 else {
881 echo "<img src='" . $GLOBALS['webroot'] .
882 "/controller.php?document&retrieve&patient_id=&document_id=" .
883 $document_id . "&as_file=false&original_file=false'><br><br>";
885 } else {
886 echo "<b>NOTE</b>: " . xl('Document') . "'" . $fname . "' " .
887 xl('cannot be converted to JPEG. Perhaps ImageMagick is not installed?') . "<br><br>";
888 if($couch_docid && $couch_revid) {
889 unlink($from_file);
893 } // end if-else
894 } // end Documents loop
895 echo "</div>";
898 // Procedures is an array of checkboxes whose values are procedure order IDs.
900 else if ($key == "procedures") {
901 if ($auth_med) {
902 echo "<hr />";
903 echo "<div class='text documents'>";
904 foreach($val as $valkey => $poid) {
905 echo "<h1>" . xlt('Procedure Order') . ":</h1>";
906 echo "<br />\n";
907 // Need to move the inline styles from this function to the stylesheet, but until
908 // then we do it just for PDFs to avoid breaking anything.
909 generate_order_report($poid, false, !$PDF_OUTPUT);
910 echo "<br />\n";
912 echo "</div>";
916 else if (strpos($key, "issue_") === 0) {
917 // display patient Issues
919 if ($first_issue) {
920 $prevIssueType = 'asdf1234!@#$'; // random junk so as to not match anything
921 $first_issue = 0;
922 echo "<hr />";
923 echo "<h1>".xl("Issues")."</h1>";
925 preg_match('/^(.*)_(\d+)$/', $key, $res);
926 $rowid = $res[2];
927 $irow = sqlQuery("SELECT type, title, comments, diagnosis " .
928 "FROM lists WHERE id = '$rowid'");
929 $diagnosis = $irow['diagnosis'];
930 if ($prevIssueType != $irow['type']) {
931 // output a header for each Issue Type we encounter
932 $disptype = $ISSUE_TYPES[$irow['type']][0];
933 echo "<div class='issue_type'>" . $disptype . ":</div>\n";
934 $prevIssueType = $irow['type'];
936 echo "<div class='text issue'>";
937 echo "<span class='issue_title'>" . $irow['title'] . ":</span>";
938 echo "<span class='issue_comments'> " . $irow['comments'] . "</span>\n";
939 // Show issue's chief diagnosis and its description:
940 if ($diagnosis) {
941 echo "<div class='text issue_diag'>";
942 echo "<span class='bold'>[".xl('Diagnosis')."]</span><br>";
943 $dcodes = explode(";", $diagnosis);
944 foreach ($dcodes as $dcode) {
945 echo "<span class='italic'>".$dcode."</span>: ";
946 echo lookup_code_descriptions($dcode)."<br>\n";
948 //echo $diagnosis." -- ".lookup_code_descriptions($diagnosis)."\n";
949 echo "</div>";
952 // Supplemental data for GCAC or Contraception issues.
953 if ($irow['type'] == 'ippf_gcac') {
954 echo " <table>\n";
955 display_layout_rows('GCA', sqlQuery("SELECT * FROM lists_ippf_gcac WHERE id = '$rowid'"));
956 echo " </table>\n";
958 else if ($irow['type'] == 'contraceptive') {
959 echo " <table>\n";
960 display_layout_rows('CON', sqlQuery("SELECT * FROM lists_ippf_con WHERE id = '$rowid'"));
961 echo " </table>\n";
964 echo "</div>\n"; //end the issue DIV
966 } else {
967 // we have an "encounter form" form field whose name is like
968 // dirname_formid, with a value which is the encounter ID.
970 // display encounter forms, encoded as a POST variable
971 // in the format: <formdirname_formid>=<encounterID>
973 if (($auth_notes_a || $auth_notes || $auth_coding_a || $auth_coding || $auth_med || $auth_relaxed)) {
974 $form_encounter = $val;
975 preg_match('/^(.*)_(\d+)$/', $key, $res);
976 $form_id = $res[2];
977 $formres = getFormNameByFormdirAndFormid($res[1],$form_id);
978 $dateres = getEncounterDateByEncounter($form_encounter);
979 $formId = getFormIdByFormdirAndFormid($res[1], $form_id);
981 if ($res[1] == 'newpatient') {
982 echo "<div class='text encounter'>\n";
983 echo "<h1>" . xl($formres["form_name"]) . "</h1>";
985 else {
986 echo "<div class='text encounter_form'>";
987 echo "<h1>" . xl_form_title($formres["form_name"]) . "</h1>";
990 // show the encounter's date
991 echo "(" . oeFormatSDFT(strtotime($dateres["date"])) . ") ";
992 if ($res[1] == 'newpatient') {
993 // display the provider info
994 echo ' '. xl('Provider') . ': ' . text(getProviderName(getProviderIdOfEncounter($form_encounter)));
996 echo "<br>\n";
998 // call the report function for the form
1000 <div name="search_div" id="search_div_<?php echo attr($form_id)?>_<?php echo attr($res[1])?>" class="report_search_div class_<?php echo attr($res[1]); ?>">
1001 <?php
1002 if (substr($res[1],0,3) == 'LBF')
1003 call_user_func("lbf_report", $pid, $form_encounter, $N, $form_id, $res[1]);
1004 else
1005 call_user_func($res[1] . "_report", $pid, $form_encounter, $N, $form_id);
1007 $esign = $esignApi->createFormESign( $formId, $res[1], $form_encounter );
1008 if ( $esign->isLogViewable("report") ) {
1009 $esign->renderLog();
1013 </div>
1014 <?php
1016 if ($res[1] == 'newpatient') {
1017 // display billing info
1018 $bres = sqlStatement("SELECT b.date, b.code, b.code_text " .
1019 "FROM billing AS b, code_types AS ct WHERE " .
1020 "b.pid = ? AND " .
1021 "b.encounter = ? AND " .
1022 "b.activity = 1 AND " .
1023 "b.code_type = ct.ct_key AND " .
1024 "ct.ct_diag = 0 " .
1025 "ORDER BY b.date",
1026 array($pid, $form_encounter));
1027 while ($brow=sqlFetchArray($bres)) {
1028 echo "<span class='bold'>&nbsp;".xl('Procedure').": </span><span class='text'>" .
1029 $brow['code'] . " " . $brow['code_text'] . "</span><br>\n";
1033 print "</div>";
1035 } // end auth-check for encounter forms
1037 } // end if('issue_')... else...
1039 } // end if('include_')... else...
1041 } // end $ar loop
1043 if ($printable)
1044 echo "<br /><br />" . xl('Signature') . ": _______________________________<br />";
1047 </div> <!-- end of report_custom DIV -->
1049 <?php
1050 if ($PDF_OUTPUT) {
1051 $content = getContent();
1052 // $pdf->setDefaultFont('Arial');
1053 $pdf->writeHTML($content, false);
1054 if ($PDF_OUTPUT == 1) {
1055 $pdf->Output('report.pdf', $GLOBALS['pdf_output']); // D = Download, I = Inline
1057 else {
1058 // This is the case of writing the PDF as a message to the CMS portal.
1059 $ptdata = getPatientData($pid, 'cmsportal_login');
1060 $contents = $pdf->Output('', true);
1061 echo "<html><head>\n";
1062 echo "<link rel='stylesheet' href='$css_header' type='text/css'>\n";
1063 echo "</head><body class='body_top'>\n";
1064 $result = cms_portal_call(array(
1065 'action' => 'putmessage',
1066 'user' => $ptdata['cmsportal_login'],
1067 'title' => xl('Your Clinical Report'),
1068 'message' => xl('Please see the attached PDF.'),
1069 'filename' => 'report.pdf',
1070 'mimetype' => 'application/pdf',
1071 'contents' => base64_encode($contents),
1073 if ($result['errmsg']) die(text($result['errmsg']));
1074 echo "<p>" . xlt('Report has been sent to the patient.') . "</p>\n";
1075 echo "</body></html>\n";
1078 else {
1080 </body>
1081 </html>
1082 <?php } ?>