fix css in patient details
[openemr.git] / controllers / C_Document.class.php
blobc152493e3395b124a59796bf265a1c2d70134ba1
1 <?php
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
15 var $template_mod;
16 var $documents;
17 var $document_categories;
18 var $tree;
19 var $_config;
20 var $manual_set_owner=false; // allows manual setting of a document owner/service
21 var $facilityService;
22 var $patientService;
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);
41 //print_r($t->tree);
42 $this->tree = $t;
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);
61 if ($dh) {
62 $templateslist = array();
63 while (false !== ($sfname = readdir($dh))) {
64 if (substr($sfname, 0, 1) == '.') {
65 continue;
67 $templateslist[$sfname] = $sfname;
69 closedir($dh);
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;
94 $couchDB = false;
95 $harddisk = false;
96 if ($GLOBALS['document_storage_method']==0) {
97 $harddisk = true;
99 if ($GLOBALS['document_storage_method']==1) {
100 $couchDB = true;
103 if ($_POST['process'] != "true") {
104 return;
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'];
119 $patient_id = 0;
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) {
128 $upl_inc = 0;
130 foreach ($_FILES['file']['name'] as $key => $value) {
131 $fname = $value;
132 $err = "";
133 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
134 $fname = $value;
135 if (empty($fname)) {
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";
144 } else {
145 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
146 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
147 fclose($tmpfile);
148 if ($doDecryption) {
149 $filetext = $this->decrypt($filetext, $passphrase);
151 if ($_POST['destination'] != '') {
152 $fname = $_POST['destination'];
154 $mimetype = $_FILES['file']['type'][$key];
155 if ($mimetype == 'application/octet-stream') { // windows most likely...
156 $parts = pathinfo($fname);
157 if (strtolower($parts['extension']) == 'dcm') { // cheat for dicom on windows because MS must be different!!!
158 $mimetype = 'application/dicom';
160 } elseif (stripos($mimetype, 'zip') !== false) {
161 $za = new ZipArchive();
162 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
163 if ($handler) {
164 $mimetype = "application/dicom+zip";
165 for ($i = 0; $i < $za->numFiles; $i++) {
166 $stat = $za->statIndex($i);
167 $parts = pathinfo($stat['name']);
168 if (strtolower($parts['extension']) != "dcm") {
169 $mimetype = "application/zip";
170 break;
175 $d = new Document();
176 $rc = $d->createDocument(
177 $patient_id,
178 $category_id,
179 $fname,
180 $mimetype,
181 $filetext,
182 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
183 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
184 $non_HTTP_owner,
185 $_FILES['file']['tmp_name'][$key]
187 if ($rc) {
188 $error .= $rc . "\n";
189 } else {
190 $this->assign("upload_success", "true");
192 $sentUploadStatus[] = $d;
193 $this->assign("file", $sentUploadStatus);
196 // Option to run a custom plugin for each file upload.
197 // This was initially created to delete the original source file in a custom setting.
198 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
199 if (file_exists($upload_plugin)) {
200 include_once($upload_plugin);
202 $upload_plugin_pp = 'documentUploadPostProcess';
203 if (function_exists($upload_plugin_pp)) {
204 $tmp = call_user_func($upload_plugin_pp, $value, $d);
205 if ($tmp) {
206 $error = $tmp;
209 // Following is just an example of code in such a plugin file.
210 /*****************************************************
211 function documentUploadPostProcess($filename, &$d) {
212 $userid = $_SESSION['authUserID'];
213 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
214 $owner = strtolower($row['username']);
215 $dn = '1_' . ucfirst($owner);
216 $filepath = "/shared_network_directory/$dn/$filename";
217 if (@unlink($filepath)) return '';
218 return "Failed to delete '$filepath'.";
220 *****************************************************/
224 $this->assign("error", nl2br($error));
225 //$this->_state = false;
226 $_POST['process'] = "";
227 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
230 function note_action_process($patient_id)
232 // this function is a dual function that will set up a note associated with a document or send a document via email.
234 if ($_POST['process'] != "true") {
235 return;
238 $n = new Note();
239 $n->set_owner($_SESSION['authUserID']);
240 parent::populate_object($n);
241 if ($_POST['identifier'] == "no") {
242 // associate a note with a document
243 $n->persist();
244 } elseif ($_POST['identifier'] == "yes") {
245 // send the document via email
246 $d = new Document($_POST['foreign_id']);
247 $url = $d->get_url();
248 $storagemethod = $d->get_storagemethod();
249 $couch_docid = $d->get_couch_docid();
250 $couch_revid = $d->get_couch_revid();
251 if ($couch_docid && $couch_revid) {
252 $couch = new CouchDB();
253 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
254 $resp = $couch->retrieve_doc($data);
255 $content = $resp->data;
256 if ($content=='' && $GLOBALS['couchdb_log']==1) {
257 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
258 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
259 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
260 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
261 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
262 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
263 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
264 die(xlt("File retrieval from CouchDB failed"));
266 // place it in a temporary file and will remove the file below after emailed
267 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
268 $fh = fopen($temp_couchdb_url, "w");
269 fwrite($fh, base64_decode($content));
270 fclose($fh);
271 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
272 } else {
273 $url = preg_replace("|^(.*)://|", "", $url);
274 // Collect filename and path
275 $from_all = explode("/", $url);
276 $from_filename = array_pop($from_all);
277 $from_pathname_array = array();
278 for ($i=0; $i<$d->get_path_depth(); $i++) {
279 $from_pathname_array[] = array_pop($from_all);
281 $from_pathname_array = array_reverse($from_pathname_array);
282 $from_pathname = implode("/", $from_pathname_array);
283 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
285 if (!file_exists($temp_url)) {
286 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;
288 $url = $temp_url;
289 $body_notes = attr($_POST['note']);
290 $pdetails = getPatientData($patient_id);
291 $pname = $pdetails['fname']." ".$pdetails['lname'];
292 $this->document_send($_POST['provide_email'], $body_notes, $url, $pname);
293 if ($couch_docid && $couch_revid) {
294 // remove the temporary couchdb file
295 unlink($temp_couchdb_url);
298 $this->_state = false;
299 $_POST['process'] = "";
300 return $this->view_action($patient_id, $n->get_foreign_id());
303 function default_action()
305 return $this->list_action();
308 function view_action($patient_id = "", $doc_id)
310 // Added by Rod to support document delete:
311 global $gacl_object, $phpgacl_location;
312 global $ISSUE_TYPES;
314 require_once(dirname(__FILE__) . "/../library/acl.inc");
315 require_once(dirname(__FILE__) . "/../library/lists.inc");
317 $d = new Document($doc_id);
318 $notes = $d->get_notes();
320 $this->assign("file", $d);
321 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
322 $this->assign("NOTE_ACTION", $this->_link("note"));
323 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
324 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
325 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
326 $this->assign("webroot", $GLOBALS['webroot']);
328 // Added by Rod to support document delete:
329 $delete_string = '';
330 if (acl_check('admin', 'super')) {
331 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
332 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
334 $this->assign("delete_string", $delete_string);
335 $this->assign("REFRESH_ACTION", $this->_link("list"));
337 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
338 "document_id=" . $d->get_id() . "&process=true");
340 // Added by Rod to support document date update:
341 $this->assign("DOCDATE", $d->get_docdate());
342 $this->assign("UPDATE_ACTION", $this->_link("update") .
343 "document_id=" . $d->get_id() . "&process=true");
345 // Added by Rod to support document issue update:
346 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
347 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
348 "pid = ? " . // AND enddate IS NULL " .
349 "ORDER BY type, begdate", array($patient_id));
350 while ($irow = sqlFetchArray($ires)) {
351 $desc = $irow['type'];
352 if ($ISSUE_TYPES[$desc]) {
353 $desc = $ISSUE_TYPES[$desc][2];
355 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
356 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
357 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
359 $this->assign("ISSUES_LIST", $issues_options);
361 // For tagging to encounter
362 // Populate the dropdown with patient's encounter list
363 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
364 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
365 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
366 "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));
367 if (sqlNumRows($result_docs) > 0) {
368 while ($row_result_docs = sqlFetchArray($result_docs)) {
369 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
370 $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>";
373 $this->assign("ENC_LIST", $encOptions);
375 //clear encounter tag
376 if ($d->get_encounter_id() != 0) {
377 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
378 } else {
379 $this->assign('clear_encounter_tag', 'javascript:void(0)');
382 //Populate the dropdown with category list
383 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
384 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
385 while ($crow = sqlFetchArray($cres)) {
386 $catid = $crow['pc_catid'];
387 if ($catid < 9 && $catid != 5) {
388 continue; // Applying same logic as in new encounter page.
390 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
392 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
394 $this->assign("notes", $notes);
396 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
397 // Populate the dropdown with image procedure order list
398 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
399 $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));
400 $mapping = $this->get_mapped_procedure($d->get_id());
401 if (sqlNumRows($imgOrders) > 0) {
402 while ($row = sqlFetchArray($imgOrders)) {
403 $sel_proc = '';
404 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
405 $sel_proc = 'selected';
407 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
411 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
413 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
415 $this->_last_node = null;
417 $menu = new HTML_TreeMenu();
419 //pass an empty array because we don't want the documents for each category showing up in this list box
420 $rnode = $this->_array_recurse($this->tree->tree, array());
421 $menu->addItem($rnode);
422 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
424 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
426 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
427 $this->assign("activity", $activity);
429 return $this->list_action($patient_id);
432 function encrypt($plaintext, $key, $cypher = 'tripledes', $mode = 'cfb')
434 $td = mcrypt_module_open($cypher, '', $mode, '');
435 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
436 mcrypt_generic_init($td, $key, $iv);
437 $crypttext = mcrypt_generic($td, $plaintext);
438 mcrypt_generic_deinit($td);
439 return $iv.$crypttext;
442 function decrypt($crypttext, $key, $cypher = 'tripledes', $mode = 'cfb')
444 $plaintext = '';
445 $td = mcrypt_module_open($cypher, '', $mode, '');
446 $ivsize = mcrypt_enc_get_iv_size($td) ;
447 $iv = substr($crypttext, 0, $ivsize);
448 $crypttext = substr($crypttext, $ivsize);
449 if ($iv) {
450 mcrypt_generic_init($td, $key, $iv);
451 $plaintext = mdecrypt_generic($td, $crypttext);
453 return $plaintext;
457 * Retrieve file from hard disk / CouchDB.
458 * In case that file isn't download this function will return thumbnail image (if exist).
459 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
460 * @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.
461 * */
462 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
464 $encrypted = $_POST['encrypted'];
465 $passphrase = $_POST['passphrase'];
466 $doEncryption = false;
467 if (!$GLOBALS['hide_document_encryption'] &&
468 $encrypted == "true" &&
469 $passphrase ) {
470 $doEncryption = true;
473 //controller function ruins booleans, so need to manually re-convert to booleans
474 if ($as_file == "true") {
475 $as_file=true;
476 } else if ($as_file == "false") {
477 $as_file=false;
479 if ($original_file == "true") {
480 $original_file=true;
481 } else if ($original_file == "false") {
482 $original_file=false;
484 if ($disable_exit == "true") {
485 $disable_exit=true;
486 } else if ($disable_exit == "false") {
487 $disable_exit=false;
489 if ($show_original == "true") {
490 $show_original=true;
491 } else if ($show_original == "false") {
492 $show_original=false;
495 switch ($context) {
496 case "patient_picture":
497 $this->patientService->setPid($patient_id);
498 $document_id = $this->patientService->getPatientPictureDocumentId();
499 break;
502 $d = new Document($document_id);
503 $url = $d->get_url();
504 $th_url = $d->get_thumb_url();
506 $storagemethod = $d->get_storagemethod();
507 $couch_docid = $d->get_couch_docid();
508 $couch_revid = $d->get_couch_revid();
510 if ($couch_docid && $couch_revid && $original_file) {
511 $couch = new CouchDB();
512 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
513 $resp = $couch->retrieve_doc($data);
514 //Take thumbnail file when is not null and file is presented online
515 if (!$as_file && !is_null($th_url) && !$show_original) {
516 $content = $resp->th_data;
517 } else {
518 $content = $resp->data;
520 if ($content=='' && $GLOBALS['couchdb_log']==1) {
521 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
522 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
523 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
524 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
525 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
526 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
527 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
528 die(xl("File retrieval from CouchDB failed"));
530 if ($disable_exit == true) {
531 return base64_decode($content);
533 header('Content-Description: File Transfer');
534 header('Content-Transfer-Encoding: binary');
535 header('Expires: 0');
536 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
537 header('Pragma: public');
538 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
539 $fh = fopen($tmpcouchpath, "w");
540 fwrite($fh, base64_decode($content));
541 fclose($fh);
542 $f = fopen($tmpcouchpath, "r");
543 if ($doEncryption) {
544 $filetext = fread($f, filesize($tmpcouchpath));
545 $ciphertext = $this->encrypt($filetext, $passphrase);
546 $tmpfilepath = $GLOBALS['temporary_files_dir'];
547 $tmpfilename = "/encrypted_".$d->get_url_file();
548 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
549 fwrite($tmpfile, $ciphertext);
550 fclose($tmpfile);
551 header('Content-Disposition: attachment; filename='.$tmpfilename);
552 header("Content-Type: application/octet-stream");
553 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
554 ob_clean();
555 flush();
556 readfile($tmpfilepath.$tmpfilename);
557 unlink($tmpfilepath.$tmpfilename);
558 } else {
559 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
560 header("Content-Type: " . $d->get_mimetype());
561 header("Content-Length: " . filesize($tmpcouchpath));
562 fpassthru($f);
564 fclose($f);
565 if ($content!='') {
566 unlink($tmpcouchpath);
568 exit;//exits only if file download from CouchDB is successfull.
571 //Take thumbnail file when is not null and file is presented online
572 if (!$as_file && !is_null($th_url) && !$show_original) {
573 $url = $th_url;
576 //strip url of protocol handler
577 $url = preg_replace("|^(.*)://|", "", $url);
579 //change full path to current webroot. this is for documents that may have
580 //been moved from a different filesystem and the full path in the database
581 //is not current. this is also for documents that may of been moved to
582 //different patients. Note that the path_depth is used to see how far down
583 //the path to go. For example, originally the path_depth was always 1, which
584 //only allowed things like documents/1/<file>, but now can have more structured
585 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
586 // etc.
587 // NOTE that $from_filename and basename($url) are the same thing
588 $from_all = explode("/", $url);
589 $from_filename = array_pop($from_all);
590 $from_pathname_array = array();
591 for ($i=0; $i<$d->get_path_depth(); $i++) {
592 $from_pathname_array[] = array_pop($from_all);
594 $from_pathname_array = array_reverse($from_pathname_array);
595 $from_pathname = implode("/", $from_pathname_array);
596 if ($couch_docid && $couch_revid) {
597 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
598 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
599 } else {
600 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
603 if (file_exists($temp_url)) {
604 $url = $temp_url;
608 if (!file_exists($url)) {
609 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;
610 } else {
611 if ($original_file) {
612 //normal case when serving the file referenced in database
613 if ($disable_exit == true) {
614 $f = fopen($url, "r");
615 $filetext = fread($f, filesize($url));
616 return $filetext;
618 header('Content-Description: File Transfer');
619 header('Content-Transfer-Encoding: binary');
620 header('Expires: 0');
621 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
622 header('Pragma: public');
623 $f = fopen($url, "r");
624 if ($doEncryption) {
625 $filetext = fread($f, filesize($url));
626 $ciphertext = $this->encrypt($filetext, $passphrase);
627 $tmpfilepath = $GLOBALS['temporary_files_dir'];
628 $tmpfilename = "/encrypted_".$d->get_url_file();
629 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
630 fwrite($tmpfile, $ciphertext);
631 fclose($tmpfile);
632 header('Content-Disposition: attachment; filename='.$tmpfilename);
633 header("Content-Type: application/octet-stream");
634 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
635 ob_clean();
636 flush();
637 readfile($tmpfilepath.$tmpfilename);
638 unlink($tmpfilepath.$tmpfilename);
639 } else {
640 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
641 header("Content-Type: " . $d->get_mimetype());
642 header("Content-Length: " . filesize($url));
643 fpassthru($f);
645 exit;
646 } else {
647 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
648 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
649 if ($couch_docid && $couch_revid) {
650 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
651 } else {
652 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
654 if ($disable_exit == true) {
655 return ;
657 header("Pragma: public");
658 header("Expires: 0");
659 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
660 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
661 header("Content-Type: image/jpeg");
662 header("Content-Length: " . filesize($url));
663 $f = fopen($url, "r");
664 fpassthru($f);
665 if ($couch_docid && $couch_revid) {
666 fclose($f);
667 unlink($url);
668 $url=str_replace("_converted.jpg", '.pdf', $url);
669 unlink($url);
671 exit;
676 function queue_action($patient_id = "")
678 $messages = $this->_tpl_vars['messages'];
679 $queue_files = array();
681 //see if the repository exists and it is a directory else error
682 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
683 $dir = opendir($this->_config['repository']);
684 //read each entry in the directory
685 while (($file = readdir($dir)) !== false) {
686 //concat the filename and path
687 $file = $this->_config['repository'] .$file;
688 $file_info = array();
689 //if the filename is a file get its info and put into a tmp array
690 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
691 $file_info['filename'] = basename_international($file);
692 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
693 $d = $this->Document->document_factory_url("file://" . $file);
694 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
695 $file_info['patient_id'] = $patient_match[1];
696 $file_info['document_id'] = $d->get_id();
697 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
699 //merge the tmp array into the larger array
700 $queue_files[] = $file_info;
703 closedir($dir);
704 } else {
705 $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";
709 $this->assign("queue_files", $queue_files);
710 $this->_last_node = null;
712 $menu = new HTML_TreeMenu();
714 //pass an empty array because we don't want the documents for each category showing up in this list box
715 $rnode = $this->_array_recurse($this->tree->tree, array());
716 $menu->addItem($rnode);
717 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
719 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
721 $this->assign("messages", nl2br($messages));
722 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
725 function queue_action_process()
727 if ($_POST['process'] != "true") {
728 return;
731 $messages = $this->_tpl_vars['messages'];
733 //build a category tree so we can have a list of category ids that are valid
734 $ct = new CategoryTree(1);
735 $categories = $ct->_id_name;
737 //see if there were and posted files and assign them
738 $files = null;
739 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
741 //loop through posted files
742 foreach ($files as $doc_id => $file) {
743 //only operate on files checked as active
744 if (!$file['active']) {
745 continue;
748 //run basic validation checks
749 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
750 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
751 continue;
754 //validate that the pod exists
755 $d = new Document($doc_id);
756 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
757 $result = $d->_db->Execute($sql);
759 if (!$result || $result->EOF) {
760 //patient id does not exist
761 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
762 continue;
765 //validate that the category id exists
766 if (!isset($categories[$file['category_id']])) {
767 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
768 continue;
771 //now do the work of moving the file
772 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
774 //see if the patient dir exists in the repository and create if not
775 if (!file_exists($new_path)) {
776 if (!mkdir($new_path, 0700)) {
777 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
778 continue;
782 //fname is the name of the file after it is moved
783 $fname = $file['name'];
785 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
786 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
787 if ($patient_match[1] == $file['patient_id']) {
788 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
791 //filenames should not have funny chars
792 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
794 //see if there is an existing file with the same name and rename as necessary
795 if (file_exists($new_path.$file['name'])) {
796 $messages .= "File with same name already exists at location: " . $new_path . "\n";
797 $fname = basename_international($this->_rename_file($new_path.$file['name']));
798 $messages .= "Current file name was changed to " . $fname ."\n";
801 //now move the file
802 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
803 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
804 $d->url = "file://" .$new_path.$fname;
805 $d->set_foreign_id($file['patient_id']);
806 $d->set_mimetype($mimetype);
807 $d->persist();
808 $d->populate();
810 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
811 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
812 $d->_db->Execute($sql);
814 } else {
815 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
818 $this->assign("messages", $messages);
819 $_POST['process'] = "";
822 function move_action_process($patient_id = "", $document_id)
824 if ($_POST['process'] != "true") {
825 return;
828 $new_category_id = $_POST['new_category_id'];
829 $new_patient_id = $_POST['new_patient_id'];
831 //move to new category
832 if (is_numeric($new_category_id) && is_numeric($document_id)) {
833 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
834 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
835 //echo $sql;
836 $this->tree->_db->Execute($sql);
839 //move to new patient
840 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
841 $d = new Document($document_id);
842 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
843 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
844 $result = $d->_db->Execute($sql);
846 if (!$result || $result->EOF) {
847 //patient id does not exist
848 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
849 } else {
850 $couchsavefailed = !$d->change_patient($new_patient_id);
852 $this->_state = false;
853 if (!$couchsavefailed) {
854 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
855 } else {
856 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
858 $this->assign("messages", $messages);
859 return $this->list_action($patient_id);
861 } //in this case return the document to the queue instead of moving it
862 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
863 $d = new Document($document_id);
864 $new_path = $this->_config['repository'];
865 $fname = $d->get_url_file();
867 //see if there is an existing file with the same name and rename as necessary
868 if (file_exists($new_path.$d->get_url_file())) {
869 $messages .= "File with same name already exists in the queue.\n";
870 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
871 $messages .= "Current file name was changed to " . $fname ."\n";
874 //now move the file
875 if (rename($d->get_url_filepath(), $new_path.$fname)) {
876 $d->url = "file://" .$new_path.$fname;
877 $d->set_foreign_id("");
878 $d->persist();
879 $d->persist();
880 $d->populate();
882 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
883 $d->_db->Execute($sql);
884 $messages .= "Document returned to queue successfully.\n";
885 } else {
886 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
889 $this->_state = false;
890 $this->assign("messages", $messages);
891 return $this->list_action($patient_id);
894 $this->_state = false;
895 $this->assign("messages", $messages);
896 return $this->view_action($patient_id, $document_id);
899 function validate_action_process($patient_id = "", $document_id)
902 $d = new Document($document_id);
903 if ($d->couch_docid && $d->couch_revid) {
904 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
905 $url = $file_path.$d->get_url();
906 $couch = new CouchDB();
907 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
908 $resp = $couch->retrieve_doc($data);
909 $content = $resp->data;
910 //--------Temporarily writing the file for calculating the hash--------//
911 //-----------Will be removed after calculating the hash value----------//
912 $temp_file = fopen($url, "w");
913 fwrite($temp_file, base64_decode($content));
914 fclose($temp_file);
915 } else {
916 $url = $d->get_url();
918 //strip url of protocol handler
919 $url = preg_replace("|^(.*)://|", "", $url);
921 //change full path to current webroot. this is for documents that may have
922 //been moved from a different filesystem and the full path in the database
923 //is not current. this is also for documents that may of been moved to
924 //different patients. Note that the path_depth is used to see how far down
925 //the path to go. For example, originally the path_depth was always 1, which
926 //only allowed things like documents/1/<file>, but now can have more structured
927 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
928 // etc.
929 // NOTE that $from_filename and basename($url) are the same thing
930 $from_all = explode("/", $url);
931 $from_filename = array_pop($from_all);
932 $from_pathname_array = array();
933 for ($i=0; $i<$d->get_path_depth(); $i++) {
934 $from_pathname_array[] = array_pop($from_all);
936 $from_pathname_array = array_reverse($from_pathname_array);
937 $from_pathname = implode("/", $from_pathname_array);
938 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
939 if (file_exists($temp_url)) {
940 $url = $temp_url;
943 if ($_POST['process'] != "true") {
944 die("process is '" . $_POST['process'] . "', expected 'true'");
945 return;
948 $d = new Document($document_id);
949 $current_hash = sha1_file($url);
950 $messages = xl('Current Hash').": ".$current_hash."<br>";
951 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
952 if ($d->get_hash() == '') {
953 $d->hash = $current_hash;
954 $d->persist();
955 $d->populate();
956 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
957 } else if ($current_hash != $d->get_hash()) {
958 $messages .= xl('Hash does not match. Data integrity has been compromised.');
959 } else {
960 $messages .= xl('Document passed integrity check.');
962 $this->_state = false;
963 $this->assign("messages", $messages);
964 if ($d->couch_docid && $d->couch_revid) {
965 //Removing the temporary file which is used to create the hash
966 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
968 return $this->view_action($patient_id, $document_id);
971 // Added by Rod for metadata update.
973 function update_action_process($patient_id = "", $document_id)
976 if ($_POST['process'] != "true") {
977 die("process is '" . $_POST['process'] . "', expected 'true'");
978 return;
981 $docdate = $_POST['docdate'];
982 $docname = $_POST['docname'];
983 $issue_id = $_POST['issue_id'];
985 if (is_numeric($document_id)) {
986 $messages = '';
987 $d = new Document($document_id);
988 $file_name = $d->get_url_file();
989 if ($docname != '' &&
990 $docname != $file_name ) {
991 // Ready to rename - check for relocation
992 $old_url = $this->_check_relocation($d->get_url());
993 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
994 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
995 if (rename($old_url, $new_url)) {
996 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
997 if (file_exists($old_url)) {
998 unlink($old_url);
1000 $d->url = $new_url;
1001 $d->persist();
1002 $d->populate();
1003 $messages .= xl('Document successfully renamed.')."<br>";
1004 } else {
1005 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
1009 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1010 $docdate = "'$docdate'";
1011 } else {
1012 $docdate = "NULL";
1014 if (!is_numeric($issue_id)) {
1015 $issue_id = 0;
1017 $couch_docid = $d->get_couch_docid();
1018 $couch_revid = $d->get_couch_revid();
1019 if ($couch_docid && $couch_revid) {
1020 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
1021 "list_id = '$issue_id' " .
1022 "WHERE id = '$document_id'";
1023 $this->tree->_db->Execute($sql);
1024 } else {
1025 $sql = "UPDATE documents SET docdate = $docdate, " .
1026 "list_id = '$issue_id' " .
1027 "WHERE id = '$document_id'";
1028 $this->tree->_db->Execute($sql);
1030 $messages .= xl('Document date and issue updated successfully') . "<br>";
1033 $this->_state = false;
1034 $this->assign("messages", $messages);
1035 return $this->view_action($patient_id, $document_id);
1038 function list_action($patient_id = "")
1040 $this->_last_node = null;
1041 $categories_list = $this->tree->_get_categories_array($patient_id);
1042 //print_r($categories_list);
1044 $menu = new HTML_TreeMenu();
1045 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1046 $menu->addItem($rnode);
1047 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1048 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1049 $this->assign("tree_html", $treeMenu->toHTML());
1051 $is_new = isset($_GET['patient_name']) ? 1 : false;
1052 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1053 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1054 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1055 if ($cur_pid == '00') {
1056 $cur_pid = '0';
1057 $is_new = 1;
1059 $this->assign('is_new', $is_new);
1060 $this->assign('place_hld', $place_hld);
1061 $this->assign('cur_pid', $cur_pid);
1062 $this->assign('used_msg', $used_msg);
1063 $this->assign('demo_pid', $_SESSION['pid']);
1065 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1068 /* This is a recursive function to rename a file to something that doesn't already exist.
1069 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1070 * at end) to ensure documents opened correctly by external browser viewers. If the
1071 * counter is at the end of the file, then will use it (to continue to work with older
1072 * files), however all new counters will be placed within filenames.
1074 * Modified to only deal with base file name when renaming, to avoid issues with directory
1075 * names with dots.
1077 function _rename_file($fname, $self = false)
1079 // Allow same routine for new file name check
1080 if (!file_exists($fname)) {
1081 return($fname);
1084 $path = dirname($fname);
1085 $file = basename_international($fname);
1087 $fparts = explode(".", $file);
1088 switch (count($fparts)) {
1089 case 1:
1090 // Has a single node (base file name). Create counter node with value 0
1091 $fparts[1] = '1';
1092 break;
1093 case 2:
1094 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1095 if (is_numeric($fparts[1])) {
1096 $fparts[1] += 1;
1097 } else {
1098 array_push($fparts, $fparts[1]);
1099 $fparts[1] = '1';
1101 break;
1102 default:
1103 // Multiple nodes
1104 $ix_end = count($fparts) - 1;
1105 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1106 // Switch old style to new and check again
1107 $wrk = $fparts[$ix_end - 1];
1108 $fparts[$ix_end - 1] = $fparts[$ix_end];
1109 $fparts[$ix_end] = $wrk;
1110 } else if (is_numeric($fparts[$ix_end - 1])) {
1111 $fparts[$ix_end - 1] += 1;
1112 } else {
1113 array_push($fparts, $fparts[$ix_end]);
1114 $fparts[$ix_end] = '1';
1116 break;
1119 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1121 if (file_exists($fname)) {
1122 return $this->_rename_file($fname, true);
1123 } else {
1124 return($fname);
1128 function &_array_recurse($array, $categories = array())
1130 if (!is_array($array)) {
1131 $array = array();
1133 $node = &$this->_last_node;
1134 $current_node = &$node;
1135 $expandedIcon = 'folder-expanded.gif';
1136 foreach ($array as $id => $ar) {
1137 $icon = 'folder.gif';
1138 if (is_array($ar) || !empty($id)) {
1139 if ($node == null) {
1140 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1141 $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));
1142 $this->_last_node = &$rnode;
1143 $node = &$rnode;
1144 $current_node = &$rnode;
1145 } else {
1146 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1147 $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)));
1148 $current_node = &$this->_last_node;
1151 $this->_array_recurse($ar, $categories);
1152 } else {
1153 if ($id === 0 && !empty($ar)) {
1154 $info = $this->tree->get_node_info($id);
1155 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1156 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1157 } else {
1158 //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
1159 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1160 if ($id !== 0 && is_object($node)) {
1161 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1162 $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)));
1167 // If there are documents in this document category, then add their
1168 // attributes to the current node.
1169 $icon = "file3.png";
1170 if (is_array($categories[$id])) {
1171 foreach ($categories[$id] as $doc) {
1172 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1173 // If user has no access then there will be no link.
1174 if (!acl_check_aco_spec($doc['aco_spec'])) {
1175 $link = '';
1177 if ($this->tree->get_node_name($id) == "CCR") {
1178 $current_node->addItem(new HTML_TreeNode(array(
1179 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1180 'link' => $link,
1181 'icon' => $icon,
1182 'expandedIcon' => $expandedIcon,
1183 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','_blank');")
1184 )));
1185 } elseif ($this->tree->get_node_name($id) == "CCD") {
1186 $current_node->addItem(new HTML_TreeNode(array(
1187 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1188 'link' => $link,
1189 'icon' => $icon,
1190 'expandedIcon' => $expandedIcon,
1191 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','_blank');")
1192 )));
1193 } else {
1194 $current_node->addItem(new HTML_TreeNode(array(
1195 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1196 'link' => $link,
1197 'icon' => $icon,
1198 'expandedIcon' => $expandedIcon
1199 )));
1204 return $node;
1207 //function for logging the errors in writing file to CouchDB/Hard Disk
1208 function document_upload_download_log($patientid, $content)
1210 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1211 $log_file = 'log.txt';
1212 if (!is_dir($log_path)) {
1213 mkdir($log_path, 0777, true);
1215 $LOG = fopen($log_path.$log_file, 'a');
1216 fwrite($LOG, $content);
1217 fclose($LOG);
1220 function document_send($email, $body, $attfile, $pname)
1222 if (empty($email)) {
1223 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1224 return;
1227 $desc = "Please check the attached patient document.\n Content:".attr($body);
1228 $mail = new MyMailer();
1229 $from_name = $GLOBALS["practice_return_email_path"];
1230 $from = $GLOBALS["practice_return_email_path"];
1231 $mail->AddReplyTo($from, $from_name);
1232 $mail->SetFrom($from, $from);
1233 $to = $email ;
1234 $to_name =$email;
1235 $mail->AddAddress($to, $to_name);
1236 $subject = "Patient documents";
1237 $mail->Subject = $subject;
1238 $mail->Body = $desc;
1239 $mail->AddAttachment($attfile);
1240 if ($mail->Send()) {
1241 $retstatus = "email_sent";
1242 } else {
1243 $email_status = $mail->ErrorInfo;
1244 //echo "EMAIL ERROR: ".$email_status;
1245 $retstatus = "email_fail";
1249 //place to hold optional code
1250 //$first_node = array_keys($t->tree);
1251 //$first_node = $first_node[0];
1252 //$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')"));
1254 //$this->_last_node = &$node1;
1256 // Function to tag a document to an encounter.
1257 function tag_action_process($patient_id = "", $document_id)
1259 if ($_POST['process'] != "true") {
1260 die("process is '" . text($_POST['process']) . "', expected 'true'");
1261 return;
1264 // Create Encounter and Tag it.
1265 $event_date = date('Y-m-d H:i:s');
1266 $encounter_id = $_POST['encounter_id'];
1267 $encounter_check = $_POST['encounter_check'];
1268 $visit_category_id = $_POST['visit_category_id'];
1270 if (is_numeric($document_id)) {
1271 $messages = '';
1272 $d = new Document($document_id);
1273 $file_name = $d->get_url_file();
1274 if (!is_numeric($encounter_id)) {
1275 $encounter_id = 0;
1278 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1279 if ($encounter_check) {
1280 $provider_id = $_SESSION['authUserID'] ;
1282 // Get the logged in user's facility
1283 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1284 $username = $facilityRow['username'];
1285 $facility = $facilityRow['facility'];
1286 $facility_id = $facilityRow['facility_id'];
1287 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1288 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1289 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1291 $conn = $GLOBALS['adodb']['db'];
1292 $encounter = $conn->GenID("sequences");
1293 $query = "INSERT INTO form_encounter SET
1294 date = ?,
1295 reason = ?,
1296 facility = ?,
1297 sensitivity = 'normal',
1298 pc_catid = ?,
1299 facility_id = ?,
1300 billing_facility = ?,
1301 provider_id = ?,
1302 pid = ?,
1303 encounter = ?";
1304 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1305 $formID = sqlInsert($query, $bindArray);
1306 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1307 $d->set_encounter_id($encounter);
1308 $this->image_result_indication($d->id, $encounter);
1309 } else {
1310 $d->set_encounter_id($encounter_id);
1311 $this->image_result_indication($d->id, $encounter_id);
1313 $d->set_encounter_check($encounter_check);
1314 $d->persist();
1316 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1319 $this->_state = false;
1320 $this->assign("messages", $messages);
1322 return $this->view_action($patient_id, $document_id);
1325 function image_procedure_action($patient_id = "", $document_id)
1328 $img_procedure_id = $_POST['image_procedure_id'];
1329 $proc_code = $_POST['procedure_code'];
1331 if (is_numeric($document_id)) {
1332 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1333 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1334 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1335 if ($img_report_id == 0) {
1336 $report_date = date('Y-m-d H:i:s');
1337 $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));
1340 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1341 if (empty($img_result)) {
1342 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));
1345 $this->image_result_indication($document_id, 0, $img_procedure_id);
1347 return $this->view_action($patient_id, $document_id);
1350 function clear_procedure_tag_action($patient_id = "", $document_id)
1352 if (is_numeric($document_id)) {
1353 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1355 return $this->view_action($patient_id, $document_id);
1358 function get_mapped_procedure($document_id)
1360 $map = array();
1361 if (is_numeric($document_id)) {
1362 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1363 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1364 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1365 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1366 where pres.document_id = ?", array($document_id));
1368 return $map;
1371 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1373 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1374 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1376 if ($encounter != 0) {
1377 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1378 } else if ($image_procedure_id != 0) {
1379 $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));
1380 } else {
1381 $ep = array('assigned_to' => $_SESSION['authUser']);
1384 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1385 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1386 setGpRelation(1, $doc_id, 6, $noteid);
1389 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1390 * Also usable for documents that may of been moved to different patients.
1392 * @param string $url - Current url string from database.
1393 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1394 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1396 * @return string
1398 function _check_relocation($url, $new_pid = null, $new_name = null)
1400 //strip url of protocol handler
1401 $url = preg_replace("|^(.*)://|", "", $url);
1402 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1403 while (current($fsnodes) != "documents") {
1404 array_shift($fsnodes);
1406 if ($new_pid) {
1407 $fsnodes[1] = $new_pid;
1409 if ($new_name) {
1410 $fsnodes[count($fsnodes)-1] = $new_name;
1412 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1413 // Make sure the url is available after corrections
1414 if ($new_pid || $new_name) {
1415 $url = $this->_rename_file($url);
1417 //Add full path and remaining nodes
1418 return $url;
1421 //clear encounter tag function
1422 function clear_encounter_tag_action($patient_id = "", $document_id)
1424 if (is_numeric($document_id)) {
1425 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1427 return $this->view_action($patient_id, $document_id);