dump db version
[openemr.git] / controllers / C_Document.class.php
blob21fc558e1b7d9df7fcc75352469d7e80189902a2
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");
8 require_once(dirname(__FILE__) . "/../library/crypto.php");
10 use OpenEMR\Services\FacilityService;
11 use OpenEMR\Services\PatientService;
13 class C_Document extends Controller
16 var $template_mod;
17 var $documents;
18 var $document_categories;
19 var $tree;
20 var $_config;
21 var $manual_set_owner=false; // allows manual setting of a document owner/service
22 var $facilityService;
23 var $patientService;
25 function __construct($template_mod = "general")
27 parent::__construct();
28 $this->facilityService = new FacilityService();
29 $this->patientService = new PatientService();
30 $this->documents = array();
31 $this->template_mod = $template_mod;
32 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . attr($_SERVER['QUERY_STRING']));
33 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
35 $this->assign("CSRF_TOKEN_FORM", collectCsrfToken());
37 //get global config options for this namespace
38 $this->_config = $GLOBALS['oer_config']['documents'];
40 $this->_args = array("patient_id" => $_GET['patient_id']);
42 $this->assign("STYLE", $GLOBALS['style']);
43 $t = new CategoryTree(1);
44 //print_r($t->tree);
45 $this->tree = $t;
46 $this->Document = new Document();
49 function upload_action($patient_id, $category_id)
51 $category_name = $this->tree->get_node_name($category_id);
52 $this->assign("category_id", $category_id);
53 $this->assign("category_name", $category_name);
54 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
55 $this->assign("patient_id", $patient_id);
57 // Added by Rod to support document template download from general_upload.html.
58 // Cloned from similar stuff in manage_document_templates.php.
59 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
60 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
61 if (file_exists($templatedir)) {
62 $dh = opendir($templatedir);
64 if ($dh) {
65 $templateslist = array();
66 while (false !== ($sfname = readdir($dh))) {
67 if (substr($sfname, 0, 1) == '.') {
68 continue;
70 $templateslist[$sfname] = $sfname;
72 closedir($dh);
73 ksort($templateslist);
74 foreach ($templateslist as $sfname) {
75 $templates_options .= "<option value='" . attr($sfname) .
76 "'>" . text($sfname) . "</option>";
79 $this->assign("TEMPLATES_LIST", $templates_options);
81 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
82 $this->assign("activity", $activity);
83 return $this->list_action($patient_id);
86 //Upload multiple files on single click
87 function upload_action_process()
90 // Collect a manually set owner if this has been set
91 // Used when want to manually assign the owning user/service such as the Direct mechanism
92 $non_HTTP_owner=false;
93 if ($this->manual_set_owner) {
94 $non_HTTP_owner=$this->manual_set_owner;
97 $couchDB = false;
98 $harddisk = false;
99 if ($GLOBALS['document_storage_method']==0) {
100 $harddisk = true;
102 if ($GLOBALS['document_storage_method']==1) {
103 $couchDB = true;
106 if ($_POST['process'] != "true") {
107 return;
110 $doDecryption = false;
111 $encrypted = $_POST['encrypted'];
112 $passphrase = $_POST['passphrase'];
113 if (!$GLOBALS['hide_document_encryption'] &&
114 $encrypted && $passphrase ) {
115 $doDecryption = true;
118 if (is_numeric($_POST['category_id'])) {
119 $category_id = $_POST['category_id'];
122 $patient_id = 0;
123 if (isset($_GET['patient_id']) && !$couchDB) {
124 $patient_id = $_GET['patient_id'];
125 } else if (is_numeric($_POST['patient_id'])) {
126 $patient_id = $_POST['patient_id'];
129 $sentUploadStatus = array();
130 if (count($_FILES['file']['name']) > 0) {
131 $upl_inc = 0;
133 foreach ($_FILES['file']['name'] as $key => $value) {
134 $fname = $value;
135 $error = "";
136 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
137 $fname = $value;
138 if (empty($fname)) {
139 $fname = htmlentities("<empty>");
141 $error = xl("Error number") . ": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
142 if ($_FILES['file']['size'][$key] == 0) {
143 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
145 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
146 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
147 } else {
148 // Test for a zip of DICOM images
149 if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {
150 $za = new ZipArchive();
151 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
152 if ($handler) {
153 $mimetype = "application/dicom+zip";
154 for ($i = 0; $i < $za->numFiles; $i++) {
155 $stat = $za->statIndex($i);
156 $fp = $za->getStream($stat['name']);
157 if ($fp) {
158 $head = fread($fp, 256);
159 fclose($fp);
160 if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.
161 $mimetype = "application/zip";
162 break;
164 unset($head);
165 // if here -then a DICOM
166 $parts = pathinfo($stat['name']);
167 if (strtolower($parts['extension']) != "dcm") { // require extension for viewer
168 $new_name = $stat['name'] . ".dcm";
169 $za->renameIndex($i, $new_name); // only use index rename!
171 } else { // Rarely here
172 $mimetype = "application/zip";
173 break;
176 $za->close();
177 if ($mimetype == "application/dicom+zip") {
178 $_FILES['file']['type'][$key] = $mimetype;
179 sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!
180 $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.
184 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
185 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
186 fclose($tmpfile);
187 if ($doDecryption) {
188 $filetext = decryptStandard($filetext, $passphrase);
189 if ($filetext === false) {
190 error_log("OpenEMR Error: Unable to decrypt a document since decryption failed.");
191 $filetext = "";
194 if ($_POST['destination'] != '') {
195 $fname = $_POST['destination'];
197 // set mime, test for single DICOM and assign extension if missing.
198 $mimetype = $_FILES['file']['type'][$key];
199 if (strpos($filetext, 'DICM') !== false) {
200 $mimetype = 'application/dicom';
201 $parts = pathinfo($fname);
202 if (!$parts['extension']) {
203 $fname .= '.dcm';
206 $d = new Document();
207 $rc = $d->createDocument(
208 $patient_id,
209 $category_id,
210 $fname,
211 $mimetype,
212 $filetext,
213 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
214 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
215 $non_HTTP_owner,
216 $_FILES['file']['tmp_name'][$key]
218 if ($rc) {
219 $error .= $rc . "\n";
220 } else {
221 $this->assign("upload_success", "true");
223 $sentUploadStatus[] = $d;
224 $this->assign("file", $sentUploadStatus);
227 // Option to run a custom plugin for each file upload.
228 // This was initially created to delete the original source file in a custom setting.
229 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
230 if (file_exists($upload_plugin)) {
231 include_once($upload_plugin);
233 $upload_plugin_pp = 'documentUploadPostProcess';
234 if (function_exists($upload_plugin_pp)) {
235 $tmp = call_user_func($upload_plugin_pp, $value, $d);
236 if ($tmp) {
237 $error = $tmp;
240 // Following is just an example of code in such a plugin file.
241 /*****************************************************
242 function documentUploadPostProcess($filename, &$d) {
243 $userid = $_SESSION['authUserID'];
244 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
245 $owner = strtolower($row['username']);
246 $dn = '1_' . ucfirst($owner);
247 $filepath = "/shared_network_directory/$dn/$filename";
248 if (@unlink($filepath)) return '';
249 return "Failed to delete '$filepath'.";
251 *****************************************************/
255 $this->assign("error", nl2br($error));
256 //$this->_state = false;
257 $_POST['process'] = "";
258 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
261 function note_action_process($patient_id)
263 // this function is a dual function that will set up a note associated with a document or send a document via email.
265 if ($_POST['process'] != "true") {
266 return;
269 $n = new Note();
270 $n->set_owner($_SESSION['authUserID']);
271 parent::populate_object($n);
272 if ($_POST['identifier'] == "no") {
273 // associate a note with a document
274 $n->persist();
275 } elseif ($_POST['identifier'] == "yes") {
276 // send the document via email
277 $d = new Document($_POST['foreign_id']);
278 $url = $d->get_url();
279 $storagemethod = $d->get_storagemethod();
280 $couch_docid = $d->get_couch_docid();
281 $couch_revid = $d->get_couch_revid();
282 if ($couch_docid && $couch_revid) {
283 $couch = new CouchDB();
284 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
285 $resp = $couch->retrieve_doc($data);
286 $content = $resp->data;
287 if ($content=='' && $GLOBALS['couchdb_log']==1) {
288 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
289 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
290 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
291 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
292 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
293 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
294 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
295 die(xlt("File retrieval from CouchDB failed"));
297 // place it in a temporary file and will remove the file below after emailed
298 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
299 $fh = fopen($temp_couchdb_url, "w");
300 fwrite($fh, base64_decode($content));
301 fclose($fh);
302 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
303 } else {
304 $url = preg_replace("|^(.*)://|", "", $url);
305 // Collect filename and path
306 $from_all = explode("/", $url);
307 $from_filename = array_pop($from_all);
308 $from_pathname_array = array();
309 for ($i=0; $i<$d->get_path_depth(); $i++) {
310 $from_pathname_array[] = array_pop($from_all);
312 $from_pathname_array = array_reverse($from_pathname_array);
313 $from_pathname = implode("/", $from_pathname_array);
314 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
316 if (!file_exists($temp_url)) {
317 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;
319 $url = $temp_url;
320 $pdetails = getPatientData($patient_id);
321 $pname = $pdetails['fname']." ".$pdetails['lname'];
322 $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);
323 if ($couch_docid && $couch_revid) {
324 // remove the temporary couchdb file
325 unlink($temp_couchdb_url);
328 $this->_state = false;
329 $_POST['process'] = "";
330 return $this->view_action($patient_id, $n->get_foreign_id());
333 function default_action()
335 return $this->list_action();
338 function view_action($patient_id = "", $doc_id)
340 // Added by Rod to support document delete:
341 global $gacl_object, $phpgacl_location;
342 global $ISSUE_TYPES;
344 require_once(dirname(__FILE__) . "/../library/acl.inc");
345 require_once(dirname(__FILE__) . "/../library/lists.inc");
347 $d = new Document($doc_id);
348 $notes = $d->get_notes();
350 $this->assign("csrf_token_form", collectCsrfToken());
352 $this->assign("file", $d);
353 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
354 $this->assign("NOTE_ACTION", $this->_link("note"));
355 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
356 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
357 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
358 $this->assign("webroot", $GLOBALS['webroot']);
360 // Added by Rod to support document delete:
361 $delete_string = '';
362 if (acl_check('patients', 'docs_rm')) {
363 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
364 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
366 $this->assign("delete_string", $delete_string);
367 $this->assign("REFRESH_ACTION", $this->_link("list"));
369 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
370 "document_id=" . $d->get_id() . "&process=true");
372 // Added by Rod to support document date update:
373 $this->assign("DOCDATE", $d->get_docdate());
374 $this->assign("UPDATE_ACTION", $this->_link("update") .
375 "document_id=" . $d->get_id() . "&process=true");
377 // Added by Rod to support document issue update:
378 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
379 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
380 "pid = ? " . // AND enddate IS NULL " .
381 "ORDER BY type, begdate", array($patient_id));
382 while ($irow = sqlFetchArray($ires)) {
383 $desc = $irow['type'];
384 if ($ISSUE_TYPES[$desc]) {
385 $desc = $ISSUE_TYPES[$desc][2];
387 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
388 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
389 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
391 $this->assign("ISSUES_LIST", $issues_options);
393 // For tagging to encounter
394 // Populate the dropdown with patient's encounter list
395 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
396 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
397 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
398 "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));
399 if (sqlNumRows($result_docs) > 0) {
400 while ($row_result_docs = sqlFetchArray($result_docs)) {
401 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
402 $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>";
405 $this->assign("ENC_LIST", $encOptions);
407 //clear encounter tag
408 if ($d->get_encounter_id() != 0) {
409 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
410 } else {
411 $this->assign('clear_encounter_tag', 'javascript:void(0)');
414 //Populate the dropdown with category list
415 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
416 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
417 while ($crow = sqlFetchArray($cres)) {
418 $catid = $crow['pc_catid'];
419 if ($catid < 9 && $catid != 5) {
420 continue; // Applying same logic as in new encounter page.
422 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
424 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
426 $this->assign("notes", $notes);
428 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
429 // Populate the dropdown with image procedure order list
430 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
431 $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));
432 $mapping = $this->get_mapped_procedure($d->get_id());
433 if (sqlNumRows($imgOrders) > 0) {
434 while ($row = sqlFetchArray($imgOrders)) {
435 $sel_proc = '';
436 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
437 $sel_proc = 'selected';
439 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
443 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
445 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
447 $this->_last_node = null;
449 $menu = new HTML_TreeMenu();
451 //pass an empty array because we don't want the documents for each category showing up in this list box
452 $rnode = $this->_array_recurse($this->tree->tree, array());
453 $menu->addItem($rnode);
454 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
456 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
458 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
459 $this->assign("activity", $activity);
461 return $this->list_action($patient_id);
465 * Retrieve file from hard disk / CouchDB.
466 * In case that file isn't download this function will return thumbnail image (if exist).
467 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
468 * @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.
469 * */
470 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
472 $encrypted = $_POST['encrypted'];
473 $passphrase = $_POST['passphrase'];
474 $doEncryption = false;
475 if (!$GLOBALS['hide_document_encryption'] &&
476 $encrypted == "true" &&
477 $passphrase ) {
478 $doEncryption = true;
481 //controller function ruins booleans, so need to manually re-convert to booleans
482 if ($as_file == "true") {
483 $as_file=true;
484 } else if ($as_file == "false") {
485 $as_file=false;
487 if ($original_file == "true") {
488 $original_file=true;
489 } else if ($original_file == "false") {
490 $original_file=false;
492 if ($disable_exit == "true") {
493 $disable_exit=true;
494 } else if ($disable_exit == "false") {
495 $disable_exit=false;
497 if ($show_original == "true") {
498 $show_original=true;
499 } else if ($show_original == "false") {
500 $show_original=false;
503 switch ($context) {
504 case "patient_picture":
505 $this->patientService->setPid($patient_id);
506 $document_id = $this->patientService->getPatientPictureDocumentId();
507 break;
510 $d = new Document($document_id);
511 $url = $d->get_url();
512 $th_url = $d->get_thumb_url();
514 $storagemethod = $d->get_storagemethod();
515 $couch_docid = $d->get_couch_docid();
516 $couch_revid = $d->get_couch_revid();
518 if ($couch_docid && $couch_revid && $original_file) {
519 $couch = new CouchDB();
520 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
521 $resp = $couch->retrieve_doc($data);
522 //Take thumbnail file when is not null and file is presented online
523 if (!$as_file && !is_null($th_url) && !$show_original) {
524 $content = $resp->th_data;
525 } else {
526 $content = $resp->data;
528 if ($content=='' && $GLOBALS['couchdb_log']==1) {
529 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
530 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
531 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
532 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
533 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
534 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
535 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
536 die(xl("File retrieval from CouchDB failed"));
538 if ($disable_exit == true) {
539 return base64_decode($content);
541 header('Content-Description: File Transfer');
542 header('Content-Transfer-Encoding: binary');
543 header('Expires: 0');
544 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
545 header('Pragma: public');
546 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
547 $fh = fopen($tmpcouchpath, "w");
548 fwrite($fh, base64_decode($content));
549 fclose($fh);
550 $f = fopen($tmpcouchpath, "r");
551 if ($doEncryption) {
552 $filetext = fread($f, filesize($tmpcouchpath));
553 $ciphertext = encryptStandard($filetext, $passphrase);
554 $tmpfilepath = $GLOBALS['temporary_files_dir'];
555 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
556 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
557 fwrite($tmpfile, $ciphertext);
558 fclose($tmpfile);
559 header('Content-Disposition: attachment; filename='.$tmpfilename);
560 header("Content-Type: application/octet-stream");
561 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
562 ob_clean();
563 flush();
564 readfile($tmpfilepath.$tmpfilename);
565 unlink($tmpfilepath.$tmpfilename);
566 } else {
567 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
568 header("Content-Type: " . $d->get_mimetype());
569 header("Content-Length: " . filesize($tmpcouchpath));
570 fpassthru($f);
572 fclose($f);
573 if ($content!='') {
574 unlink($tmpcouchpath);
576 exit;//exits only if file download from CouchDB is successfull.
579 //Take thumbnail file when is not null and file is presented online
580 if (!$as_file && !is_null($th_url) && !$show_original) {
581 $url = $th_url;
584 //strip url of protocol handler
585 $url = preg_replace("|^(.*)://|", "", $url);
587 //change full path to current webroot. this is for documents that may have
588 //been moved from a different filesystem and the full path in the database
589 //is not current. this is also for documents that may of been moved to
590 //different patients. Note that the path_depth is used to see how far down
591 //the path to go. For example, originally the path_depth was always 1, which
592 //only allowed things like documents/1/<file>, but now can have more structured
593 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
594 // etc.
595 // NOTE that $from_filename and basename($url) are the same thing
596 $from_all = explode("/", $url);
597 $from_filename = array_pop($from_all);
598 $from_pathname_array = array();
599 for ($i=0; $i<$d->get_path_depth(); $i++) {
600 $from_pathname_array[] = array_pop($from_all);
602 $from_pathname_array = array_reverse($from_pathname_array);
603 $from_pathname = implode("/", $from_pathname_array);
604 if ($couch_docid && $couch_revid) {
605 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
606 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
607 } else {
608 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
611 if (file_exists($temp_url)) {
612 $url = $temp_url;
616 if (!file_exists($url)) {
617 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;
618 } else {
619 if ($original_file) {
620 //normal case when serving the file referenced in database
621 if ($disable_exit == true) {
622 $f = fopen($url, "r");
623 $filetext = fread($f, filesize($url));
624 return $filetext;
626 header('Content-Description: File Transfer');
627 header('Content-Transfer-Encoding: binary');
628 header('Expires: 0');
629 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
630 header('Pragma: public');
631 if (is_file($url)) {
632 $f = fopen($url, "r");
634 if ($doEncryption) {
635 $filetext = fread($f, filesize($url));
636 $ciphertext = encryptStandard($filetext, $passphrase);
637 $tmpfilepath = $GLOBALS['temporary_files_dir'];
638 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
639 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
640 fwrite($tmpfile, $ciphertext);
641 fclose($tmpfile);
642 header('Content-Disposition: attachment; filename='.$tmpfilename);
643 header("Content-Type: application/octet-stream");
644 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
645 ob_clean();
646 flush();
647 readfile($tmpfilepath.$tmpfilename);
648 unlink($tmpfilepath.$tmpfilename);
649 } else {
650 if ($f) {
651 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
652 header("Content-Type: " . $d->get_mimetype());
653 header("Content-Length: " . filesize($url));
654 fpassthru($f);
657 exit;
658 } else {
659 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
660 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
661 if ($couch_docid && $couch_revid) {
662 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
663 } else {
664 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
666 if ($disable_exit == true) {
667 return ;
669 header("Pragma: public");
670 header("Expires: 0");
671 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
672 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
673 header("Content-Type: image/jpeg");
674 header("Content-Length: " . filesize($url));
675 $f = fopen($url, "r");
676 fpassthru($f);
677 if ($couch_docid && $couch_revid) {
678 fclose($f);
679 unlink($url);
680 $url=str_replace("_converted.jpg", '.pdf', $url);
681 unlink($url);
683 exit;
688 function queue_action($patient_id = "")
690 $messages = $this->_tpl_vars['messages'];
691 $queue_files = array();
693 //see if the repository exists and it is a directory else error
694 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
695 $dir = opendir($this->_config['repository']);
696 //read each entry in the directory
697 while (($file = readdir($dir)) !== false) {
698 //concat the filename and path
699 $file = $this->_config['repository'] .$file;
700 $file_info = array();
701 //if the filename is a file get its info and put into a tmp array
702 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
703 $file_info['filename'] = basename_international($file);
704 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
705 $d = $this->Document->document_factory_url("file://" . $file);
706 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
707 $file_info['patient_id'] = $patient_match[1];
708 $file_info['document_id'] = $d->get_id();
709 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
711 //merge the tmp array into the larger array
712 $queue_files[] = $file_info;
715 closedir($dir);
716 } else {
717 $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";
721 $this->assign("queue_files", $queue_files);
722 $this->_last_node = null;
724 $menu = new HTML_TreeMenu();
726 //pass an empty array because we don't want the documents for each category showing up in this list box
727 $rnode = $this->_array_recurse($this->tree->tree, array());
728 $menu->addItem($rnode);
729 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
731 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
733 $this->assign("messages", nl2br($messages));
734 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
737 function queue_action_process()
739 if ($_POST['process'] != "true") {
740 return;
743 $messages = $this->_tpl_vars['messages'];
745 //build a category tree so we can have a list of category ids that are valid
746 $ct = new CategoryTree(1);
747 $categories = $ct->_id_name;
749 //see if there were and posted files and assign them
750 $files = null;
751 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
753 //loop through posted files
754 foreach ($files as $doc_id => $file) {
755 //only operate on files checked as active
756 if (!$file['active']) {
757 continue;
760 //run basic validation checks
761 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
762 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
763 continue;
766 //validate that the pod exists
767 $d = new Document($doc_id);
768 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
769 $result = $d->_db->Execute($sql);
771 if (!$result || $result->EOF) {
772 //patient id does not exist
773 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
774 continue;
777 //validate that the category id exists
778 if (!isset($categories[$file['category_id']])) {
779 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
780 continue;
783 //now do the work of moving the file
784 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
786 //see if the patient dir exists in the repository and create if not
787 if (!file_exists($new_path)) {
788 if (!mkdir($new_path, 0700)) {
789 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
790 continue;
794 //fname is the name of the file after it is moved
795 $fname = $file['name'];
797 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
798 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
799 if ($patient_match[1] == $file['patient_id']) {
800 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
803 //filenames should not have funny chars
804 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
806 //see if there is an existing file with the same name and rename as necessary
807 if (file_exists($new_path.$file['name'])) {
808 $messages .= "File with same name already exists at location: " . $new_path . "\n";
809 $fname = basename_international($this->_rename_file($new_path.$file['name']));
810 $messages .= "Current file name was changed to " . $fname ."\n";
813 //now move the file
814 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
815 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
816 $d->url = "file://" .$new_path.$fname;
817 $d->set_foreign_id($file['patient_id']);
818 $d->set_mimetype($mimetype);
819 $d->persist();
820 $d->populate();
822 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
823 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
824 $d->_db->Execute($sql);
826 } else {
827 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
830 $this->assign("messages", $messages);
831 $_POST['process'] = "";
834 function move_action_process($patient_id = "", $document_id)
836 if ($_POST['process'] != "true") {
837 return;
840 $new_category_id = $_POST['new_category_id'];
841 $new_patient_id = $_POST['new_patient_id'];
843 //move to new category
844 if (is_numeric($new_category_id) && is_numeric($document_id)) {
845 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
846 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
847 //echo $sql;
848 $this->tree->_db->Execute($sql);
851 //move to new patient
852 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
853 $d = new Document($document_id);
854 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
855 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
856 $result = $d->_db->Execute($sql);
858 if (!$result || $result->EOF) {
859 //patient id does not exist
860 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
861 } else {
862 $couchsavefailed = !$d->change_patient($new_patient_id);
864 $this->_state = false;
865 if (!$couchsavefailed) {
866 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
867 } else {
868 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
870 $this->assign("messages", $messages);
871 return $this->list_action($patient_id);
873 } //in this case return the document to the queue instead of moving it
874 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
875 $d = new Document($document_id);
876 $new_path = $this->_config['repository'];
877 $fname = $d->get_url_file();
879 //see if there is an existing file with the same name and rename as necessary
880 if (file_exists($new_path.$d->get_url_file())) {
881 $messages .= "File with same name already exists in the queue.\n";
882 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
883 $messages .= "Current file name was changed to " . $fname ."\n";
886 //now move the file
887 if (rename($d->get_url_filepath(), $new_path.$fname)) {
888 $d->url = "file://" .$new_path.$fname;
889 $d->set_foreign_id("");
890 $d->persist();
891 $d->persist();
892 $d->populate();
894 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
895 $d->_db->Execute($sql);
896 $messages .= "Document returned to queue successfully.\n";
897 } else {
898 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
901 $this->_state = false;
902 $this->assign("messages", $messages);
903 return $this->list_action($patient_id);
906 $this->_state = false;
907 $this->assign("messages", $messages);
908 return $this->view_action($patient_id, $document_id);
911 function validate_action_process($patient_id = "", $document_id)
914 $d = new Document($document_id);
915 if ($d->couch_docid && $d->couch_revid) {
916 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
917 $url = $file_path.$d->get_url();
918 $couch = new CouchDB();
919 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
920 $resp = $couch->retrieve_doc($data);
921 $content = $resp->data;
922 //--------Temporarily writing the file for calculating the hash--------//
923 //-----------Will be removed after calculating the hash value----------//
924 $temp_file = fopen($url, "w");
925 fwrite($temp_file, base64_decode($content));
926 fclose($temp_file);
927 } else {
928 $url = $d->get_url();
930 //strip url of protocol handler
931 $url = preg_replace("|^(.*)://|", "", $url);
933 //change full path to current webroot. this is for documents that may have
934 //been moved from a different filesystem and the full path in the database
935 //is not current. this is also for documents that may of been moved to
936 //different patients. Note that the path_depth is used to see how far down
937 //the path to go. For example, originally the path_depth was always 1, which
938 //only allowed things like documents/1/<file>, but now can have more structured
939 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
940 // etc.
941 // NOTE that $from_filename and basename($url) are the same thing
942 $from_all = explode("/", $url);
943 $from_filename = array_pop($from_all);
944 $from_pathname_array = array();
945 for ($i=0; $i<$d->get_path_depth(); $i++) {
946 $from_pathname_array[] = array_pop($from_all);
948 $from_pathname_array = array_reverse($from_pathname_array);
949 $from_pathname = implode("/", $from_pathname_array);
950 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
951 if (file_exists($temp_url)) {
952 $url = $temp_url;
955 if ($_POST['process'] != "true") {
956 die("process is '" . $_POST['process'] . "', expected 'true'");
957 return;
960 $d = new Document($document_id);
961 $current_hash = sha1_file($url);
962 $messages = xl('Current Hash').": ".$current_hash."<br>";
963 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
964 if ($d->get_hash() == '') {
965 $d->hash = $current_hash;
966 $d->persist();
967 $d->populate();
968 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
969 } else if ($current_hash != $d->get_hash()) {
970 $messages .= xl('Hash does not match. Data integrity has been compromised.');
971 } else {
972 $messages .= xl('Document passed integrity check.');
974 $this->_state = false;
975 $this->assign("messages", $messages);
976 if ($d->couch_docid && $d->couch_revid) {
977 //Removing the temporary file which is used to create the hash
978 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
980 return $this->view_action($patient_id, $document_id);
983 // Added by Rod for metadata update.
985 function update_action_process($patient_id = "", $document_id)
988 if ($_POST['process'] != "true") {
989 die("process is '" . $_POST['process'] . "', expected 'true'");
990 return;
993 $docdate = $_POST['docdate'];
994 $docname = $_POST['docname'];
995 $issue_id = $_POST['issue_id'];
997 if (is_numeric($document_id)) {
998 $messages = '';
999 $d = new Document($document_id);
1000 $file_name = $d->get_url_file();
1001 if ($docname != '' &&
1002 $docname != $file_name ) {
1003 // Ready to rename - check for relocation
1004 $old_url = $this->_check_relocation($d->get_url());
1005 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
1006 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
1007 if (rename($old_url, $new_url)) {
1008 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
1009 if (file_exists($old_url)) {
1010 unlink($old_url);
1012 $d->url = $new_url;
1013 $d->persist();
1014 $d->populate();
1015 $messages .= xl('Document successfully renamed.')."<br>";
1016 } else {
1017 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
1021 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
1022 $docdate = "'$docdate'";
1023 } else {
1024 $docdate = "NULL";
1026 if (!is_numeric($issue_id)) {
1027 $issue_id = 0;
1029 $couch_docid = $d->get_couch_docid();
1030 $couch_revid = $d->get_couch_revid();
1031 if ($couch_docid && $couch_revid) {
1032 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
1033 "list_id = '$issue_id' " .
1034 "WHERE id = '$document_id'";
1035 $this->tree->_db->Execute($sql);
1036 } else {
1037 $sql = "UPDATE documents SET docdate = $docdate, " .
1038 "list_id = '$issue_id' " .
1039 "WHERE id = '$document_id'";
1040 $this->tree->_db->Execute($sql);
1042 $messages .= xl('Document date and issue updated successfully') . "<br>";
1045 $this->_state = false;
1046 $this->assign("messages", $messages);
1047 return $this->view_action($patient_id, $document_id);
1050 function list_action($patient_id = "")
1052 $this->_last_node = null;
1053 $categories_list = $this->tree->_get_categories_array($patient_id);
1054 //print_r($categories_list);
1056 $menu = new HTML_TreeMenu();
1057 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1058 $menu->addItem($rnode);
1059 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1060 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1061 $this->assign("tree_html", $treeMenu->toHTML());
1063 $is_new = isset($_GET['patient_name']) ? 1 : false;
1064 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1065 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1066 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1067 if ($cur_pid == '00') {
1068 $cur_pid = '0';
1069 $is_new = 1;
1071 $this->assign('is_new', $is_new);
1072 $this->assign('place_hld', $place_hld);
1073 $this->assign('cur_pid', $cur_pid);
1074 $this->assign('used_msg', $used_msg);
1075 $this->assign('demo_pid', $_SESSION['pid']);
1077 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1080 /* This is a recursive function to rename a file to something that doesn't already exist.
1081 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1082 * at end) to ensure documents opened correctly by external browser viewers. If the
1083 * counter is at the end of the file, then will use it (to continue to work with older
1084 * files), however all new counters will be placed within filenames.
1086 * Modified to only deal with base file name when renaming, to avoid issues with directory
1087 * names with dots.
1089 function _rename_file($fname, $self = false)
1091 // Allow same routine for new file name check
1092 if (!file_exists($fname)) {
1093 return($fname);
1096 $path = dirname($fname);
1097 $file = basename_international($fname);
1099 $fparts = explode(".", $file);
1100 switch (count($fparts)) {
1101 case 1:
1102 // Has a single node (base file name). Create counter node with value 0
1103 $fparts[1] = '1';
1104 break;
1105 case 2:
1106 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1107 if (is_numeric($fparts[1])) {
1108 $fparts[1] += 1;
1109 } else {
1110 array_push($fparts, $fparts[1]);
1111 $fparts[1] = '1';
1113 break;
1114 default:
1115 // Multiple nodes
1116 $ix_end = count($fparts) - 1;
1117 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1118 // Switch old style to new and check again
1119 $wrk = $fparts[$ix_end - 1];
1120 $fparts[$ix_end - 1] = $fparts[$ix_end];
1121 $fparts[$ix_end] = $wrk;
1122 } else if (is_numeric($fparts[$ix_end - 1])) {
1123 $fparts[$ix_end - 1] += 1;
1124 } else {
1125 array_push($fparts, $fparts[$ix_end]);
1126 $fparts[$ix_end] = '1';
1128 break;
1131 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1133 if (file_exists($fname)) {
1134 return $this->_rename_file($fname, true);
1135 } else {
1136 return($fname);
1140 function &_array_recurse($array, $categories = array())
1142 if (!is_array($array)) {
1143 $array = array();
1145 $node = &$this->_last_node;
1146 $current_node = &$node;
1147 $expandedIcon = 'folder-expanded.gif';
1148 foreach ($array as $id => $ar) {
1149 $icon = 'folder.gif';
1150 if (is_array($ar) || !empty($id)) {
1151 if ($node == null) {
1152 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1153 $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));
1154 $this->_last_node = &$rnode;
1155 $node = &$rnode;
1156 $current_node = &$rnode;
1157 } else {
1158 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1159 $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)));
1160 $current_node = &$this->_last_node;
1163 $this->_array_recurse($ar, $categories);
1164 } else {
1165 if ($id === 0 && !empty($ar)) {
1166 $info = $this->tree->get_node_info($id);
1167 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1168 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1169 } else {
1170 //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
1171 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1172 if ($id !== 0 && is_object($node)) {
1173 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1174 $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)));
1179 // If there are documents in this document category, then add their
1180 // attributes to the current node.
1181 $icon = "file3.png";
1182 if (is_array($categories[$id])) {
1183 foreach ($categories[$id] as $doc) {
1184 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1185 // If user has no access then there will be no link.
1186 if (!acl_check_aco_spec($doc['aco_spec'])) {
1187 $link = '';
1189 if ($this->tree->get_node_name($id) == "CCR") {
1190 $current_node->addItem(new HTML_TreeNode(array(
1191 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1192 'link' => $link,
1193 'icon' => $icon,
1194 'expandedIcon' => $expandedIcon,
1195 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','_blank');")
1196 )));
1197 } elseif ($this->tree->get_node_name($id) == "CCD") {
1198 $current_node->addItem(new HTML_TreeNode(array(
1199 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1200 'link' => $link,
1201 'icon' => $icon,
1202 'expandedIcon' => $expandedIcon,
1203 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','_blank');")
1204 )));
1205 } else {
1206 $current_node->addItem(new HTML_TreeNode(array(
1207 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1208 'link' => $link,
1209 'icon' => $icon,
1210 'expandedIcon' => $expandedIcon
1211 )));
1216 return $node;
1219 //function for logging the errors in writing file to CouchDB/Hard Disk
1220 function document_upload_download_log($patientid, $content)
1222 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1223 $log_file = 'log.txt';
1224 if (!is_dir($log_path)) {
1225 mkdir($log_path, 0777, true);
1227 $LOG = fopen($log_path.$log_file, 'a');
1228 fwrite($LOG, $content);
1229 fclose($LOG);
1232 function document_send($email, $body, $attfile, $pname)
1234 if (empty($email)) {
1235 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1236 return;
1239 $desc = "Please check the attached patient document.\n Content:".$body;
1240 $mail = new MyMailer();
1241 $from_name = $GLOBALS["practice_return_email_path"];
1242 $from = $GLOBALS["practice_return_email_path"];
1243 $mail->AddReplyTo($from, $from_name);
1244 $mail->SetFrom($from, $from);
1245 $to = $email ;
1246 $to_name =$email;
1247 $mail->AddAddress($to, $to_name);
1248 $subject = "Patient documents";
1249 $mail->Subject = $subject;
1250 $mail->Body = $desc;
1251 $mail->AddAttachment($attfile);
1252 if ($mail->Send()) {
1253 $retstatus = "email_sent";
1254 } else {
1255 $email_status = $mail->ErrorInfo;
1256 //echo "EMAIL ERROR: ".$email_status;
1257 $retstatus = "email_fail";
1261 //place to hold optional code
1262 //$first_node = array_keys($t->tree);
1263 //$first_node = $first_node[0];
1264 //$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')"));
1266 //$this->_last_node = &$node1;
1268 // Function to tag a document to an encounter.
1269 function tag_action_process($patient_id = "", $document_id)
1271 if ($_POST['process'] != "true") {
1272 die("process is '" . text($_POST['process']) . "', expected 'true'");
1273 return;
1276 // Create Encounter and Tag it.
1277 $event_date = date('Y-m-d H:i:s');
1278 $encounter_id = $_POST['encounter_id'];
1279 $encounter_check = $_POST['encounter_check'];
1280 $visit_category_id = $_POST['visit_category_id'];
1282 if (is_numeric($document_id)) {
1283 $messages = '';
1284 $d = new Document($document_id);
1285 $file_name = $d->get_url_file();
1286 if (!is_numeric($encounter_id)) {
1287 $encounter_id = 0;
1290 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1291 if ($encounter_check) {
1292 $provider_id = $_SESSION['authUserID'] ;
1294 // Get the logged in user's facility
1295 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1296 $username = $facilityRow['username'];
1297 $facility = $facilityRow['facility'];
1298 $facility_id = $facilityRow['facility_id'];
1299 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1300 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1301 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1303 $conn = $GLOBALS['adodb']['db'];
1304 $encounter = $conn->GenID("sequences");
1305 $query = "INSERT INTO form_encounter SET
1306 date = ?,
1307 reason = ?,
1308 facility = ?,
1309 sensitivity = 'normal',
1310 pc_catid = ?,
1311 facility_id = ?,
1312 billing_facility = ?,
1313 provider_id = ?,
1314 pid = ?,
1315 encounter = ?";
1316 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1317 $formID = sqlInsert($query, $bindArray);
1318 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1319 $d->set_encounter_id($encounter);
1320 $this->image_result_indication($d->id, $encounter);
1321 } else {
1322 $d->set_encounter_id($encounter_id);
1323 $this->image_result_indication($d->id, $encounter_id);
1325 $d->set_encounter_check($encounter_check);
1326 $d->persist();
1328 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1331 $this->_state = false;
1332 $this->assign("messages", $messages);
1334 return $this->view_action($patient_id, $document_id);
1337 function image_procedure_action($patient_id = "", $document_id)
1340 $img_procedure_id = $_POST['image_procedure_id'];
1341 $proc_code = $_POST['procedure_code'];
1343 if (is_numeric($document_id)) {
1344 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1345 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1346 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1347 if ($img_report_id == 0) {
1348 $report_date = date('Y-m-d H:i:s');
1349 $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));
1352 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1353 if (empty($img_result)) {
1354 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));
1357 $this->image_result_indication($document_id, 0, $img_procedure_id);
1359 return $this->view_action($patient_id, $document_id);
1362 function clear_procedure_tag_action($patient_id = "", $document_id)
1364 if (is_numeric($document_id)) {
1365 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1367 return $this->view_action($patient_id, $document_id);
1370 function get_mapped_procedure($document_id)
1372 $map = array();
1373 if (is_numeric($document_id)) {
1374 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1375 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1376 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1377 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1378 where pres.document_id = ?", array($document_id));
1380 return $map;
1383 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1385 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1386 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1388 if ($encounter != 0) {
1389 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1390 } else if ($image_procedure_id != 0) {
1391 $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));
1392 } else {
1393 $ep = array('assigned_to' => $_SESSION['authUser']);
1396 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1397 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1398 setGpRelation(1, $doc_id, 6, $noteid);
1401 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1402 * Also usable for documents that may of been moved to different patients.
1404 * @param string $url - Current url string from database.
1405 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1406 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1408 * @return string
1410 function _check_relocation($url, $new_pid = null, $new_name = null)
1412 //strip url of protocol handler
1413 $url = preg_replace("|^(.*)://|", "", $url);
1414 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1415 while (current($fsnodes) != "documents") {
1416 array_shift($fsnodes);
1418 if ($new_pid) {
1419 $fsnodes[1] = $new_pid;
1421 if ($new_name) {
1422 $fsnodes[count($fsnodes)-1] = $new_name;
1424 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1425 // Make sure the url is available after corrections
1426 if ($new_pid || $new_name) {
1427 $url = $this->_rename_file($url);
1429 //Add full path and remaining nodes
1430 return $url;
1433 //clear encounter tag function
1434 function clear_encounter_tag_action($patient_id = "", $document_id)
1436 if (is_numeric($document_id)) {
1437 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1439 return $this->view_action($patient_id, $document_id);