2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 require_once(dirname(__FILE__
) . "/../library/forms.inc");
9 use OpenEMR\Services\FacilityService
;
10 use OpenEMR\Services\PatientService
;
12 class C_Document
extends Controller
17 var $document_categories;
20 var $manual_set_owner=false; // allows manual setting of a document owner/service
24 function __construct($template_mod = "general")
26 parent
::__construct();
27 $this->facilityService
= new FacilityService();
28 $this->patientService
= new PatientService();
29 $this->documents
= array();
30 $this->template_mod
= $template_mod;
31 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . attr($_SERVER['QUERY_STRING']));
32 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
34 //get global config options for this namespace
35 $this->_config
= $GLOBALS['oer_config']['documents'];
37 $this->_args
= array("patient_id" => $_GET['patient_id']);
39 $this->assign("STYLE", $GLOBALS['style']);
40 $t = new CategoryTree(1);
43 $this->Document
= new Document();
46 function upload_action($patient_id, $category_id)
48 $category_name = $this->tree
->get_node_name($category_id);
49 $this->assign("category_id", $category_id);
50 $this->assign("category_name", $category_name);
51 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
52 $this->assign("patient_id", $patient_id);
54 // Added by Rod to support document template download from general_upload.html.
55 // Cloned from similar stuff in manage_document_templates.php.
56 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
57 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
58 if (file_exists($templatedir)) {
59 $dh = opendir($templatedir);
62 $templateslist = array();
63 while (false !== ($sfname = readdir($dh))) {
64 if (substr($sfname, 0, 1) == '.') {
67 $templateslist[$sfname] = $sfname;
70 ksort($templateslist);
71 foreach ($templateslist as $sfname) {
72 $templates_options .= "<option value='" . attr($sfname) .
73 "'>" . text($sfname) . "</option>";
76 $this->assign("TEMPLATES_LIST", $templates_options);
78 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_upload.html");
79 $this->assign("activity", $activity);
80 return $this->list_action($patient_id);
83 //Upload multiple files on single click
84 function upload_action_process()
87 // Collect a manually set owner if this has been set
88 // Used when want to manually assign the owning user/service such as the Direct mechanism
89 $non_HTTP_owner=false;
90 if ($this->manual_set_owner
) {
91 $non_HTTP_owner=$this->manual_set_owner
;
96 if ($GLOBALS['document_storage_method']==0) {
99 if ($GLOBALS['document_storage_method']==1) {
103 if ($_POST['process'] != "true") {
107 $doDecryption = false;
108 $encrypted = $_POST['encrypted'];
109 $passphrase = $_POST['passphrase'];
110 if (!$GLOBALS['hide_document_encryption'] &&
111 $encrypted && $passphrase ) {
112 $doDecryption = true;
115 if (is_numeric($_POST['category_id'])) {
116 $category_id = $_POST['category_id'];
120 if (isset($_GET['patient_id']) && !$couchDB) {
121 $patient_id = $_GET['patient_id'];
122 } else if (is_numeric($_POST['patient_id'])) {
123 $patient_id = $_POST['patient_id'];
126 $sentUploadStatus = array();
127 if (count($_FILES['file']['name']) > 0) {
130 foreach ($_FILES['file']['name'] as $key => $value) {
133 if ($_FILES['file']['error'][$key] > 0 ||
empty($fname) ||
$_FILES['file']['size'][$key] == 0) {
136 $fname = htmlentities("<empty>");
138 $error = xl("Error number") .": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
139 if ($_FILES['file']['size'][$key] == 0) {
140 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
142 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
143 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
145 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
146 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
149 $filetext = $this->decrypt($filetext, $passphrase);
151 if ($_POST['destination'] != '') {
152 $fname = $_POST['destination'];
155 $rc = $d->createDocument(
159 $_FILES['file']['type'][$key],
161 empty($_GET['higher_level_path']) ?
'' : $_GET['higher_level_path'],
162 empty($_POST['path_depth']) ?
1 : $_POST['path_depth'],
164 $_FILES['file']['tmp_name'][$key]
167 $error .= $rc . "\n";
169 $this->assign("upload_success", "true");
171 $sentUploadStatus[] = $d;
172 $this->assign("file", $sentUploadStatus);
175 // Option to run a custom plugin for each file upload.
176 // This was initially created to delete the original source file in a custom setting.
177 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
178 if (file_exists($upload_plugin)) {
179 include_once($upload_plugin);
181 $upload_plugin_pp = 'documentUploadPostProcess';
182 if (function_exists($upload_plugin_pp)) {
183 $tmp = call_user_func($upload_plugin_pp, $value, $d);
188 // Following is just an example of code in such a plugin file.
189 /*****************************************************
190 function documentUploadPostProcess($filename, &$d) {
191 $userid = $_SESSION['authUserID'];
192 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
193 $owner = strtolower($row['username']);
194 $dn = '1_' . ucfirst($owner);
195 $filepath = "/shared_network_directory/$dn/$filename";
196 if (@unlink($filepath)) return '';
197 return "Failed to delete '$filepath'.";
199 *****************************************************/
203 $this->assign("error", nl2br($error));
204 //$this->_state = false;
205 $_POST['process'] = "";
206 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
209 function note_action_process($patient_id)
211 // this function is a dual function that will set up a note associated with a document or send a document via email.
213 if ($_POST['process'] != "true") {
218 $n->set_owner($_SESSION['authUserID']);
219 parent
::populate_object($n);
220 if ($_POST['identifier'] == "no") {
221 // associate a note with a document
223 } elseif ($_POST['identifier'] == "yes") {
224 // send the document via email
225 $d = new Document($_POST['foreign_id']);
226 $url = $d->get_url();
227 $storagemethod = $d->get_storagemethod();
228 $couch_docid = $d->get_couch_docid();
229 $couch_revid = $d->get_couch_revid();
230 if ($couch_docid && $couch_revid) {
231 $couch = new CouchDB();
232 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
233 $resp = $couch->retrieve_doc($data);
234 $content = $resp->data
;
235 if ($content=='' && $GLOBALS['couchdb_log']==1) {
236 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
237 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
238 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
239 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
240 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
241 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
242 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
243 die(xlt("File retrieval from CouchDB failed"));
245 // place it in a temporary file and will remove the file below after emailed
246 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
247 $fh = fopen($temp_couchdb_url, "w");
248 fwrite($fh, base64_decode($content));
250 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
252 $url = preg_replace("|^(.*)://|", "", $url);
253 // Collect filename and path
254 $from_all = explode("/", $url);
255 $from_filename = array_pop($from_all);
256 $from_pathname_array = array();
257 for ($i=0; $i<$d->get_path_depth(); $i++
) {
258 $from_pathname_array[] = array_pop($from_all);
260 $from_pathname_array = array_reverse($from_pathname_array);
261 $from_pathname = implode("/", $from_pathname_array);
262 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
264 if (!file_exists($temp_url)) {
265 echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $temp_url;
268 $body_notes = attr($_POST['note']);
269 $pdetails = getPatientData($patient_id);
270 $pname = $pdetails['fname']." ".$pdetails['lname'];
271 $this->document_send($_POST['provide_email'], $body_notes, $url, $pname);
272 if ($couch_docid && $couch_revid) {
273 // remove the temporary couchdb file
274 unlink($temp_couchdb_url);
277 $this->_state
= false;
278 $_POST['process'] = "";
279 return $this->view_action($patient_id, $n->get_foreign_id());
282 function default_action()
284 return $this->list_action();
287 function view_action($patient_id = "", $doc_id)
289 // Added by Rod to support document delete:
290 global $gacl_object, $phpgacl_location;
293 require_once(dirname(__FILE__
) . "/../library/acl.inc");
294 require_once(dirname(__FILE__
) . "/../library/lists.inc");
296 $d = new Document($doc_id);
297 $notes = $d->get_notes();
299 $this->assign("file", $d);
300 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
301 $this->assign("NOTE_ACTION", $this->_link("note"));
302 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
303 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
304 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
305 $this->assign("webroot", $GLOBALS['webroot']);
307 // Added by Rod to support document delete:
309 if (acl_check('admin', 'super')) {
310 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
311 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
313 $this->assign("delete_string", $delete_string);
314 $this->assign("REFRESH_ACTION", $this->_link("list"));
316 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
317 "document_id=" . $d->get_id() . "&process=true");
319 // Added by Rod to support document date update:
320 $this->assign("DOCDATE", $d->get_docdate());
321 $this->assign("UPDATE_ACTION", $this->_link("update") .
322 "document_id=" . $d->get_id() . "&process=true");
324 // Added by Rod to support document issue update:
325 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
326 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
327 "pid = ? " . // AND enddate IS NULL " .
328 "ORDER BY type, begdate", array($patient_id));
329 while ($irow = sqlFetchArray($ires)) {
330 $desc = $irow['type'];
331 if ($ISSUE_TYPES[$desc]) {
332 $desc = $ISSUE_TYPES[$desc][2];
334 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
335 $sel = ($irow['id'] == $d->get_list_id()) ?
' selected' : '';
336 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
338 $this->assign("ISSUES_LIST", $issues_options);
340 // For tagging to encounter
341 // Populate the dropdown with patient's encounter list
342 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
343 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
344 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
345 "LEFT JOIN openemr_postcalendar_categories ON fe.pc_catid=openemr_postcalendar_categories.pc_catid WHERE fe.pid = ? ORDER BY fe.date desc", array($patient_id));
346 if (sqlNumRows($result_docs) > 0) {
347 while ($row_result_docs = sqlFetchArray($result_docs)) {
348 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ?
' selected' : '';
349 $encOptions .= "<option value='" . attr($row_result_docs['encounter']) . "' $sel_enc>". text(oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date'])))) . "-" . text(xl_appt_category($row_result_docs['pc_catname'])) . "</option>";
352 $this->assign("ENC_LIST", $encOptions);
354 //clear encounter tag
355 if ($d->get_encounter_id() != 0) {
356 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
358 $this->assign('clear_encounter_tag', 'javascript:void(0)');
361 //Populate the dropdown with category list
362 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
363 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
364 while ($crow = sqlFetchArray($cres)) {
365 $catid = $crow['pc_catid'];
366 if ($catid < 9 && $catid != 5) {
367 continue; // Applying same logic as in new encounter page.
369 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
371 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
373 $this->assign("notes", $notes);
375 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
376 // Populate the dropdown with image procedure order list
377 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
378 $imgOrders = sqlStatement("select procedure_name,po.procedure_order_id,procedure_code from procedure_order po inner join procedure_order_code poc on poc.procedure_order_id = po.procedure_order_id where po.patient_id = ? and poc.procedure_order_title = 'imaging'", array($patient_id));
379 $mapping = $this->get_mapped_procedure($d->get_id());
380 if (sqlNumRows($imgOrders) > 0) {
381 while ($row = sqlFetchArray($imgOrders)) {
383 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
384 $sel_proc = 'selected';
386 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
390 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
392 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
394 $this->_last_node
= null;
396 $menu = new HTML_TreeMenu();
398 //pass an empty array because we don't want the documents for each category showing up in this list box
399 $rnode = $this->_array_recurse($this->tree
->tree
, array());
400 $menu->addItem($rnode);
401 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
403 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
405 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_view.html");
406 $this->assign("activity", $activity);
408 return $this->list_action($patient_id);
411 function encrypt($plaintext, $key, $cypher = 'tripledes', $mode = 'cfb')
413 $td = mcrypt_module_open($cypher, '', $mode, '');
414 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND
);
415 mcrypt_generic_init($td, $key, $iv);
416 $crypttext = mcrypt_generic($td, $plaintext);
417 mcrypt_generic_deinit($td);
418 return $iv.$crypttext;
421 function decrypt($crypttext, $key, $cypher = 'tripledes', $mode = 'cfb')
424 $td = mcrypt_module_open($cypher, '', $mode, '');
425 $ivsize = mcrypt_enc_get_iv_size($td) ;
426 $iv = substr($crypttext, 0, $ivsize);
427 $crypttext = substr($crypttext, $ivsize);
429 mcrypt_generic_init($td, $key, $iv);
430 $plaintext = mdecrypt_generic($td, $crypttext);
436 * Retrieve file from hard disk / CouchDB.
437 * In case that file isn't download this function will return thumbnail image (if exist).
438 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
439 * @param (string) $context - given a special document scenario (e.g.: patient avatar, custom image viewer document, etc), the context can be set so that a switch statement can execute a custom strategy.
441 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
443 $encrypted = $_POST['encrypted'];
444 $passphrase = $_POST['passphrase'];
445 $doEncryption = false;
446 if (!$GLOBALS['hide_document_encryption'] &&
447 $encrypted == "true" &&
449 $doEncryption = true;
452 //controller function ruins booleans, so need to manually re-convert to booleans
453 if ($as_file == "true") {
455 } else if ($as_file == "false") {
458 if ($original_file == "true") {
460 } else if ($original_file == "false") {
461 $original_file=false;
463 if ($disable_exit == "true") {
465 } else if ($disable_exit == "false") {
468 if ($show_original == "true") {
470 } else if ($show_original == "false") {
471 $show_original=false;
475 case "patient_picture":
476 $this->patientService
->setPid($patient_id);
477 $document_id = $this->patientService
->getPatientPictureDocumentId();
481 $d = new Document($document_id);
482 $url = $d->get_url();
483 $th_url = $d->get_thumb_url();
485 $storagemethod = $d->get_storagemethod();
486 $couch_docid = $d->get_couch_docid();
487 $couch_revid = $d->get_couch_revid();
489 if ($couch_docid && $couch_revid && $original_file) {
490 $couch = new CouchDB();
491 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
492 $resp = $couch->retrieve_doc($data);
493 //Take thumbnail file when is not null and file is presented online
494 if (!$as_file && !is_null($th_url) && !$show_original) {
495 $content = $resp->th_data
;
497 $content = $resp->data
;
499 if ($content=='' && $GLOBALS['couchdb_log']==1) {
500 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
501 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
502 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
503 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
504 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
505 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
506 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
507 die(xl("File retrieval from CouchDB failed"));
509 if ($disable_exit == true) {
510 return base64_decode($content);
512 header('Content-Description: File Transfer');
513 header('Content-Transfer-Encoding: binary');
514 header('Expires: 0');
515 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
516 header('Pragma: public');
517 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
518 $fh = fopen($tmpcouchpath, "w");
519 fwrite($fh, base64_decode($content));
521 $f = fopen($tmpcouchpath, "r");
523 $filetext = fread($f, filesize($tmpcouchpath));
524 $ciphertext = $this->encrypt($filetext, $passphrase);
525 $tmpfilepath = $GLOBALS['temporary_files_dir'];
526 $tmpfilename = "/encrypted_".$d->get_url_file();
527 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
528 fwrite($tmpfile, $ciphertext);
530 header('Content-Disposition: attachment; filename='.$tmpfilename);
531 header("Content-Type: application/octet-stream");
532 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
535 readfile($tmpfilepath.$tmpfilename);
536 unlink($tmpfilepath.$tmpfilename);
538 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
539 header("Content-Type: " . $d->get_mimetype());
540 header("Content-Length: " . filesize($tmpcouchpath));
545 unlink($tmpcouchpath);
547 exit;//exits only if file download from CouchDB is successfull.
550 //Take thumbnail file when is not null and file is presented online
551 if (!$as_file && !is_null($th_url) && !$show_original) {
555 //strip url of protocol handler
556 $url = preg_replace("|^(.*)://|", "", $url);
558 //change full path to current webroot. this is for documents that may have
559 //been moved from a different filesystem and the full path in the database
560 //is not current. this is also for documents that may of been moved to
561 //different patients. Note that the path_depth is used to see how far down
562 //the path to go. For example, originally the path_depth was always 1, which
563 //only allowed things like documents/1/<file>, but now can have more structured
564 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
566 // NOTE that $from_filename and basename($url) are the same thing
567 $from_all = explode("/", $url);
568 $from_filename = array_pop($from_all);
569 $from_pathname_array = array();
570 for ($i=0; $i<$d->get_path_depth(); $i++
) {
571 $from_pathname_array[] = array_pop($from_all);
573 $from_pathname_array = array_reverse($from_pathname_array);
574 $from_pathname = implode("/", $from_pathname_array);
575 if ($couch_docid && $couch_revid) {
576 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
577 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
579 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
582 if (file_exists($temp_url)) {
587 if (!file_exists($url)) {
588 echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $url;
590 if ($original_file) {
591 //normal case when serving the file referenced in database
592 if ($disable_exit == true) {
593 $f = fopen($url, "r");
594 $filetext = fread($f, filesize($url));
597 header('Content-Description: File Transfer');
598 header('Content-Transfer-Encoding: binary');
599 header('Expires: 0');
600 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
601 header('Pragma: public');
602 $f = fopen($url, "r");
604 $filetext = fread($f, filesize($url));
605 $ciphertext = $this->encrypt($filetext, $passphrase);
606 $tmpfilepath = $GLOBALS['temporary_files_dir'];
607 $tmpfilename = "/encrypted_".$d->get_url_file();
608 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
609 fwrite($tmpfile, $ciphertext);
611 header('Content-Disposition: attachment; filename='.$tmpfilename);
612 header("Content-Type: application/octet-stream");
613 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
616 readfile($tmpfilepath.$tmpfilename);
617 unlink($tmpfilepath.$tmpfilename);
619 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
620 header("Content-Type: " . $d->get_mimetype());
621 header("Content-Length: " . filesize($url));
626 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
627 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
628 if ($couch_docid && $couch_revid) {
629 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
631 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
633 if ($disable_exit == true) {
636 header("Pragma: public");
637 header("Expires: 0");
638 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
639 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
640 header("Content-Type: image/jpeg");
641 header("Content-Length: " . filesize($url));
642 $f = fopen($url, "r");
644 if ($couch_docid && $couch_revid) {
647 $url=str_replace("_converted.jpg", '.pdf', $url);
655 function queue_action($patient_id = "")
657 $messages = $this->_tpl_vars
['messages'];
658 $queue_files = array();
660 //see if the repository exists and it is a directory else error
661 if (file_exists($this->_config
['repository']) && is_dir($this->_config
['repository'])) {
662 $dir = opendir($this->_config
['repository']);
663 //read each entry in the directory
664 while (($file = readdir($dir)) !== false) {
665 //concat the filename and path
666 $file = $this->_config
['repository'] .$file;
667 $file_info = array();
668 //if the filename is a file get its info and put into a tmp array
669 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
670 $file_info['filename'] = basename_international($file);
671 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
672 $d = $this->Document
->document_factory_url("file://" . $file);
673 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
674 $file_info['patient_id'] = $patient_match[1];
675 $file_info['document_id'] = $d->get_id();
676 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
678 //merge the tmp array into the larger array
679 $queue_files[] = $file_info;
684 $messages .= "The repository directory does not exist, it is not a directory or there are not sufficient permissions to access it. '" . $this->config
['repository'] . "'\n";
688 $this->assign("queue_files", $queue_files);
689 $this->_last_node
= null;
691 $menu = new HTML_TreeMenu();
693 //pass an empty array because we don't want the documents for each category showing up in this list box
694 $rnode = $this->_array_recurse($this->tree
->tree
, array());
695 $menu->addItem($rnode);
696 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
698 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
700 $this->assign("messages", nl2br($messages));
701 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_queue.html");
704 function queue_action_process()
706 if ($_POST['process'] != "true") {
710 $messages = $this->_tpl_vars
['messages'];
712 //build a category tree so we can have a list of category ids that are valid
713 $ct = new CategoryTree(1);
714 $categories = $ct->_id_name
;
716 //see if there were and posted files and assign them
718 is_array($_POST['files']) ?
$files = $_POST['files']: $files = array();
720 //loop through posted files
721 foreach ($files as $doc_id => $file) {
722 //only operate on files checked as active
723 if (!$file['active']) {
727 //run basic validation checks
728 if (!is_numeric($file['patient_id']) ||
!is_numeric($file['category_id']) ||
!is_numeric($doc_id)) {
729 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
733 //validate that the pod exists
734 $d = new Document($doc_id);
735 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
736 $result = $d->_db
->Execute($sql);
738 if (!$result ||
$result->EOF
) {
739 //patient id does not exist
740 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
744 //validate that the category id exists
745 if (!isset($categories[$file['category_id']])) {
746 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
750 //now do the work of moving the file
751 $new_path = $this->_config
['repository'] . $file['patient_id'] ."/";
753 //see if the patient dir exists in the repository and create if not
754 if (!file_exists($new_path)) {
755 if (!mkdir($new_path, 0700)) {
756 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
761 //fname is the name of the file after it is moved
762 $fname = $file['name'];
764 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
765 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
766 if ($patient_match[1] == $file['patient_id']) {
767 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
770 //filenames should not have funny chars
771 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
773 //see if there is an existing file with the same name and rename as necessary
774 if (file_exists($new_path.$file['name'])) {
775 $messages .= "File with same name already exists at location: " . $new_path . "\n";
776 $fname = basename_international($this->_rename_file($new_path.$file['name']));
777 $messages .= "Current file name was changed to " . $fname ."\n";
781 if (rename($this->_config
['repository'].$file['name'], $new_path.$fname)) {
782 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
783 $d->url
= "file://" .$new_path.$fname;
784 $d->set_foreign_id($file['patient_id']);
785 $d->set_mimetype($mimetype);
789 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
790 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
791 $d->_db
->Execute($sql);
794 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
797 $this->assign("messages", $messages);
798 $_POST['process'] = "";
801 function move_action_process($patient_id = "", $document_id)
803 if ($_POST['process'] != "true") {
807 $new_category_id = $_POST['new_category_id'];
808 $new_patient_id = $_POST['new_patient_id'];
810 //move to new category
811 if (is_numeric($new_category_id) && is_numeric($document_id)) {
812 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
813 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree
->_id_name
[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
815 $this->tree
->_db
->Execute($sql);
818 //move to new patient
819 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
820 $d = new Document($document_id);
821 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
822 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
823 $result = $d->_db
->Execute($sql);
825 if (!$result ||
$result->EOF
) {
826 //patient id does not exist
827 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
829 $couchsavefailed = !$d->change_patient($new_patient_id);
831 $this->_state
= false;
832 if (!$couchsavefailed) {
833 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
835 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
837 $this->assign("messages", $messages);
838 return $this->list_action($patient_id);
840 } //in this case return the document to the queue instead of moving it
841 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
842 $d = new Document($document_id);
843 $new_path = $this->_config
['repository'];
844 $fname = $d->get_url_file();
846 //see if there is an existing file with the same name and rename as necessary
847 if (file_exists($new_path.$d->get_url_file())) {
848 $messages .= "File with same name already exists in the queue.\n";
849 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
850 $messages .= "Current file name was changed to " . $fname ."\n";
854 if (rename($d->get_url_filepath(), $new_path.$fname)) {
855 $d->url
= "file://" .$new_path.$fname;
856 $d->set_foreign_id("");
861 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db
->qstr($document_id);
862 $d->_db
->Execute($sql);
863 $messages .= "Document returned to queue successfully.\n";
865 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
868 $this->_state
= false;
869 $this->assign("messages", $messages);
870 return $this->list_action($patient_id);
873 $this->_state
= false;
874 $this->assign("messages", $messages);
875 return $this->view_action($patient_id, $document_id);
878 function validate_action_process($patient_id = "", $document_id)
881 $d = new Document($document_id);
882 if ($d->couch_docid
&& $d->couch_revid
) {
883 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
884 $url = $file_path.$d->get_url();
885 $couch = new CouchDB();
886 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid
);
887 $resp = $couch->retrieve_doc($data);
888 $content = $resp->data
;
889 //--------Temporarily writing the file for calculating the hash--------//
890 //-----------Will be removed after calculating the hash value----------//
891 $temp_file = fopen($url, "w");
892 fwrite($temp_file, base64_decode($content));
895 $url = $d->get_url();
897 //strip url of protocol handler
898 $url = preg_replace("|^(.*)://|", "", $url);
900 //change full path to current webroot. this is for documents that may have
901 //been moved from a different filesystem and the full path in the database
902 //is not current. this is also for documents that may of been moved to
903 //different patients. Note that the path_depth is used to see how far down
904 //the path to go. For example, originally the path_depth was always 1, which
905 //only allowed things like documents/1/<file>, but now can have more structured
906 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
908 // NOTE that $from_filename and basename($url) are the same thing
909 $from_all = explode("/", $url);
910 $from_filename = array_pop($from_all);
911 $from_pathname_array = array();
912 for ($i=0; $i<$d->get_path_depth(); $i++
) {
913 $from_pathname_array[] = array_pop($from_all);
915 $from_pathname_array = array_reverse($from_pathname_array);
916 $from_pathname = implode("/", $from_pathname_array);
917 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
918 if (file_exists($temp_url)) {
922 if ($_POST['process'] != "true") {
923 die("process is '" . $_POST['process'] . "', expected 'true'");
927 $d = new Document($document_id);
928 $current_hash = sha1_file($url);
929 $messages = xl('Current Hash').": ".$current_hash."<br>";
930 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
931 if ($d->get_hash() == '') {
932 $d->hash
= $current_hash;
935 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
936 } else if ($current_hash != $d->get_hash()) {
937 $messages .= xl('Hash does not match. Data integrity has been compromised.');
939 $messages .= xl('Document passed integrity check.');
941 $this->_state
= false;
942 $this->assign("messages", $messages);
943 if ($d->couch_docid
&& $d->couch_revid
) {
944 //Removing the temporary file which is used to create the hash
945 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
947 return $this->view_action($patient_id, $document_id);
950 // Added by Rod for metadata update.
952 function update_action_process($patient_id = "", $document_id)
955 if ($_POST['process'] != "true") {
956 die("process is '" . $_POST['process'] . "', expected 'true'");
960 $docdate = $_POST['docdate'];
961 $docname = $_POST['docname'];
962 $issue_id = $_POST['issue_id'];
964 if (is_numeric($document_id)) {
966 $d = new Document($document_id);
967 $file_name = $d->get_url_file();
968 if ($docname != '' &&
969 $docname != $file_name ) {
970 // Ready to rename - check for relocation
971 $old_url = $this->_check_relocation($d->get_url());
972 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
973 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
974 if (rename($old_url, $new_url)) {
975 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
976 if (file_exists($old_url)) {
982 $messages .= xl('Document successfully renamed.')."<br>";
984 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
988 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
989 $docdate = "'$docdate'";
993 if (!is_numeric($issue_id)) {
996 $couch_docid = $d->get_couch_docid();
997 $couch_revid = $d->get_couch_revid();
998 if ($couch_docid && $couch_revid) {
999 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
1000 "list_id = '$issue_id' " .
1001 "WHERE id = '$document_id'";
1002 $this->tree
->_db
->Execute($sql);
1004 $sql = "UPDATE documents SET docdate = $docdate, " .
1005 "list_id = '$issue_id' " .
1006 "WHERE id = '$document_id'";
1007 $this->tree
->_db
->Execute($sql);
1009 $messages .= xl('Document date and issue updated successfully') . "<br>";
1012 $this->_state
= false;
1013 $this->assign("messages", $messages);
1014 return $this->view_action($patient_id, $document_id);
1017 function list_action($patient_id = "")
1019 $this->_last_node
= null;
1020 $categories_list = $this->tree
->_get_categories_array($patient_id);
1021 //print_r($categories_list);
1023 $menu = new HTML_TreeMenu();
1024 $rnode = $this->_array_recurse($this->tree
->tree
, $categories_list);
1025 $menu->addItem($rnode);
1026 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1027 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1028 $this->assign("tree_html", $treeMenu->toHTML());
1030 $is_new = isset($_GET['patient_name']) ?
1 : false;
1031 $place_hld = isset($_GET['patient_name']) ?
filter_input(INPUT_GET
, 'patient_name') : xl("Patient search or select.");
1032 $cur_pid = isset($_GET['patient_id']) ?
filter_input(INPUT_GET
, 'patient_id') : '';
1033 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1034 if ($cur_pid == '00') {
1038 $this->assign('is_new', $is_new);
1039 $this->assign('place_hld', $place_hld);
1040 $this->assign('cur_pid', $cur_pid);
1041 $this->assign('used_msg', $used_msg);
1042 $this->assign('demo_pid', $_SESSION['pid']);
1044 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_list.html");
1047 /* This is a recursive function to rename a file to something that doesn't already exist.
1048 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1049 * at end) to ensure documents opened correctly by external browser viewers. If the
1050 * counter is at the end of the file, then will use it (to continue to work with older
1051 * files), however all new counters will be placed within filenames.
1053 * Modified to only deal with base file name when renaming, to avoid issues with directory
1056 function _rename_file($fname, $self = false)
1058 // Allow same routine for new file name check
1059 if (!file_exists($fname)) {
1063 $path = dirname($fname);
1064 $file = basename_international($fname);
1066 $fparts = explode(".", $file);
1067 switch (count($fparts)) {
1069 // Has a single node (base file name). Create counter node with value 0
1073 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1074 if (is_numeric($fparts[1])) {
1077 array_push($fparts, $fparts[1]);
1083 $ix_end = count($fparts) - 1;
1084 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1085 // Switch old style to new and check again
1086 $wrk = $fparts[$ix_end - 1];
1087 $fparts[$ix_end - 1] = $fparts[$ix_end];
1088 $fparts[$ix_end] = $wrk;
1089 } else if (is_numeric($fparts[$ix_end - 1])) {
1090 $fparts[$ix_end - 1] +
= 1;
1092 array_push($fparts, $fparts[$ix_end]);
1093 $fparts[$ix_end] = '1';
1098 $fname = $path.DIRECTORY_SEPARATOR
.join(".", $fparts);
1100 if (file_exists($fname)) {
1101 return $this->_rename_file($fname, true);
1107 function &_array_recurse($array, $categories = array())
1109 if (!is_array($array)) {
1112 $node = &$this->_last_node
;
1113 $current_node = &$node;
1114 $expandedIcon = 'folder-expanded.gif';
1115 foreach ($array as $id => $ar) {
1116 $icon = 'folder.gif';
1117 if (is_array($ar) ||
!empty($id)) {
1118 if ($node == null) {
1119 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1120 $rnode = new HTML_TreeNode(array("id" => $id, 'text' => $this->tree
->get_node_name($id), 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => false));
1121 $this->_last_node
= &$rnode;
1123 $current_node = &$rnode;
1125 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1126 $this->_last_node
= &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $this->tree
->get_node_name($id), 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1127 $current_node = &$this->_last_node
;
1130 $this->_array_recurse($ar, $categories);
1132 if ($id === 0 && !empty($ar)) {
1133 $info = $this->tree
->get_node_info($id);
1134 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1135 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1137 //there is a third case that is implicit here when title === 0 and $ar is empty, in that case we do not want to do anything
1138 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1139 if ($id !== 0 && is_object($node)) {
1140 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1141 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $this->tree
->get_node_name($id), 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1146 // If there are documents in this document category, then add their
1147 // attributes to the current node.
1148 $icon = "file3.png";
1149 if (is_array($categories[$id])) {
1150 foreach ($categories[$id] as $doc) {
1151 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1152 // If user has no access then there will be no link.
1153 if (!acl_check_aco_spec($doc['aco_spec'])) {
1156 if ($this->tree
->get_node_name($id) == "CCR") {
1157 $current_node->addItem(new HTML_TreeNode(array(
1158 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1161 'expandedIcon' => $expandedIcon,
1162 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','_blank');")
1164 } elseif ($this->tree
->get_node_name($id) == "CCD") {
1165 $current_node->addItem(new HTML_TreeNode(array(
1166 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1169 'expandedIcon' => $expandedIcon,
1170 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','_blank');")
1173 $current_node->addItem(new HTML_TreeNode(array(
1174 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1177 'expandedIcon' => $expandedIcon
1186 //function for logging the errors in writing file to CouchDB/Hard Disk
1187 function document_upload_download_log($patientid, $content)
1189 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1190 $log_file = 'log.txt';
1191 if (!is_dir($log_path)) {
1192 mkdir($log_path, 0777, true);
1194 $LOG = fopen($log_path.$log_file, 'a');
1195 fwrite($LOG, $content);
1199 function document_send($email, $body, $attfile, $pname)
1201 if (empty($email)) {
1202 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1206 $desc = "Please check the attached patient document.\n Content:".attr($body);
1207 $mail = new MyMailer();
1208 $from_name = $GLOBALS["practice_return_email_path"];
1209 $from = $GLOBALS["practice_return_email_path"];
1210 $mail->AddReplyTo($from, $from_name);
1211 $mail->SetFrom($from, $from);
1214 $mail->AddAddress($to, $to_name);
1215 $subject = "Patient documents";
1216 $mail->Subject
= $subject;
1217 $mail->Body
= $desc;
1218 $mail->AddAttachment($attfile);
1219 if ($mail->Send()) {
1220 $retstatus = "email_sent";
1222 $email_status = $mail->ErrorInfo
;
1223 //echo "EMAIL ERROR: ".$email_status;
1224 $retstatus = "email_fail";
1228 //place to hold optional code
1229 //$first_node = array_keys($t->tree);
1230 //$first_node = $first_node[0];
1231 //$node1 = new HTML_TreeNode(array('text' => $t->get_node_name($first_node), 'link' => "test.php", 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true), array('onclick' => "alert('foo'); return false", 'onexpand' => "alert('Expanded')"));
1233 //$this->_last_node = &$node1;
1235 // Function to tag a document to an encounter.
1236 function tag_action_process($patient_id = "", $document_id)
1238 if ($_POST['process'] != "true") {
1239 die("process is '" . text($_POST['process']) . "', expected 'true'");
1243 // Create Encounter and Tag it.
1244 $event_date = date('Y-m-d H:i:s');
1245 $encounter_id = $_POST['encounter_id'];
1246 $encounter_check = $_POST['encounter_check'];
1247 $visit_category_id = $_POST['visit_category_id'];
1249 if (is_numeric($document_id)) {
1251 $d = new Document($document_id);
1252 $file_name = $d->get_url_file();
1253 if (!is_numeric($encounter_id)) {
1257 $encounter_check = ( $encounter_check == 'on') ?
1 : 0;
1258 if ($encounter_check) {
1259 $provider_id = $_SESSION['authUserID'] ;
1261 // Get the logged in user's facility
1262 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1263 $username = $facilityRow['username'];
1264 $facility = $facilityRow['facility'];
1265 $facility_id = $facilityRow['facility_id'];
1266 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1267 $billingFacility = $this->facilityService
->getPrimaryBusinessEntity();
1268 $billingFacilityID = ( $billingFacility['id'] ) ?
$billingFacility['id'] : $facility_id;
1270 $conn = $GLOBALS['adodb']['db'];
1271 $encounter = $conn->GenID("sequences");
1272 $query = "INSERT INTO form_encounter SET
1276 sensitivity = 'normal',
1279 billing_facility = ?,
1283 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1284 $formID = sqlInsert($query, $bindArray);
1285 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1286 $d->set_encounter_id($encounter);
1287 $this->image_result_indication($d->id
, $encounter);
1289 $d->set_encounter_id($encounter_id);
1290 $this->image_result_indication($d->id
, $encounter_id);
1292 $d->set_encounter_check($encounter_check);
1295 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1298 $this->_state
= false;
1299 $this->assign("messages", $messages);
1301 return $this->view_action($patient_id, $document_id);
1304 function image_procedure_action($patient_id = "", $document_id)
1307 $img_procedure_id = $_POST['image_procedure_id'];
1308 $proc_code = $_POST['procedure_code'];
1310 if (is_numeric($document_id)) {
1311 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1312 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1313 $img_report_id = !empty($img_report['procedure_report_id']) ?
$img_report['procedure_report_id'] : 0;
1314 if ($img_report_id == 0) {
1315 $report_date = date('Y-m-d H:i:s');
1316 $img_report_id = sqlInsert("INSERT INTO procedure_report(procedure_order_id,procedure_order_seq,date_collected,date_report,report_status) values(?,?,?,?,'final')", array($img_procedure_id,$img_order['procedure_order_seq'],$img_order['date_collected'],$report_date));
1319 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1320 if (empty($img_result)) {
1321 sqlInsert("INSERT INTO procedure_result(procedure_report_id,date,document_id,result_status) values(?,?,?,'final')", array($img_report_id,date('Y-m-d H:i:s'),$document_id));
1324 $this->image_result_indication($document_id, 0, $img_procedure_id);
1326 return $this->view_action($patient_id, $document_id);
1329 function clear_procedure_tag_action($patient_id = "", $document_id)
1331 if (is_numeric($document_id)) {
1332 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1334 return $this->view_action($patient_id, $document_id);
1337 function get_mapped_procedure($document_id)
1340 if (is_numeric($document_id)) {
1341 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1342 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1343 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1344 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1345 where pres.document_id = ?", array($document_id));
1350 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1352 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1353 $narration = isset($doc_notes['note']) ?
'With Narration': 'Without Narration';
1355 if ($encounter != 0) {
1356 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1357 } else if ($image_procedure_id != 0) {
1358 $ep = sqlQuery("select u.username as assigned_to from procedure_order inner join users u on u.id = provider_id where procedure_order_id = ?", array($image_procedure_id));
1360 $ep = array('assigned_to' => $_SESSION['authUser']);
1363 $encounter_provider = isset($ep['assigned_to']) ?
$ep['assigned_to'] : $_SESSION['authUser'];
1364 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1365 setGpRelation(1, $doc_id, 6, $noteid);
1368 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1369 * Also usable for documents that may of been moved to different patients.
1371 * @param string $url - Current url string from database.
1372 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1373 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1377 function _check_relocation($url, $new_pid = null, $new_name = null)
1379 //strip url of protocol handler
1380 $url = preg_replace("|^(.*)://|", "", $url);
1381 $fsnodes = explode(DIRECTORY_SEPARATOR
, $url);
1382 while (current($fsnodes) != "documents") {
1383 array_shift($fsnodes);
1386 $fsnodes[1] = $new_pid;
1389 $fsnodes[count($fsnodes)-1] = $new_name;
1391 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR
.implode(DIRECTORY_SEPARATOR
, $fsnodes);
1392 // Make sure the url is available after corrections
1393 if ($new_pid ||
$new_name) {
1394 $url = $this->_rename_file($url);
1396 //Add full path and remaining nodes
1400 //clear encounter tag function
1401 function clear_encounter_tag_action($patient_id = "", $document_id)
1403 if (is_numeric($document_id)) {
1404 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1406 return $this->view_action($patient_id, $document_id);