Merge pull request #1459 from bradymiller/more-openssl-stuff_1
[openemr.git] / controllers / C_Document.class.php
blob124758bf4d74fdd1f0122405c859b050f57bb50a
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 //get global config options for this namespace
36 $this->_config = $GLOBALS['oer_config']['documents'];
38 $this->_args = array("patient_id" => $_GET['patient_id']);
40 $this->assign("STYLE", $GLOBALS['style']);
41 $t = new CategoryTree(1);
42 //print_r($t->tree);
43 $this->tree = $t;
44 $this->Document = new Document();
47 function upload_action($patient_id, $category_id)
49 $category_name = $this->tree->get_node_name($category_id);
50 $this->assign("category_id", $category_id);
51 $this->assign("category_name", $category_name);
52 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
53 $this->assign("patient_id", $patient_id);
55 // Added by Rod to support document template download from general_upload.html.
56 // Cloned from similar stuff in manage_document_templates.php.
57 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
58 $templates_options = "<option value=''>-- " . xlt('Select Template') . " --</option>";
59 if (file_exists($templatedir)) {
60 $dh = opendir($templatedir);
62 if ($dh) {
63 $templateslist = array();
64 while (false !== ($sfname = readdir($dh))) {
65 if (substr($sfname, 0, 1) == '.') {
66 continue;
68 $templateslist[$sfname] = $sfname;
70 closedir($dh);
71 ksort($templateslist);
72 foreach ($templateslist as $sfname) {
73 $templates_options .= "<option value='" . attr($sfname) .
74 "'>" . text($sfname) . "</option>";
77 $this->assign("TEMPLATES_LIST", $templates_options);
79 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
80 $this->assign("activity", $activity);
81 return $this->list_action($patient_id);
84 //Upload multiple files on single click
85 function upload_action_process()
88 // Collect a manually set owner if this has been set
89 // Used when want to manually assign the owning user/service such as the Direct mechanism
90 $non_HTTP_owner=false;
91 if ($this->manual_set_owner) {
92 $non_HTTP_owner=$this->manual_set_owner;
95 $couchDB = false;
96 $harddisk = false;
97 if ($GLOBALS['document_storage_method']==0) {
98 $harddisk = true;
100 if ($GLOBALS['document_storage_method']==1) {
101 $couchDB = true;
104 if ($_POST['process'] != "true") {
105 return;
108 $doDecryption = false;
109 $encrypted = $_POST['encrypted'];
110 $passphrase = $_POST['passphrase'];
111 if (!$GLOBALS['hide_document_encryption'] &&
112 $encrypted && $passphrase ) {
113 $doDecryption = true;
116 if (is_numeric($_POST['category_id'])) {
117 $category_id = $_POST['category_id'];
120 $patient_id = 0;
121 if (isset($_GET['patient_id']) && !$couchDB) {
122 $patient_id = $_GET['patient_id'];
123 } else if (is_numeric($_POST['patient_id'])) {
124 $patient_id = $_POST['patient_id'];
127 $sentUploadStatus = array();
128 if (count($_FILES['file']['name']) > 0) {
129 $upl_inc = 0;
131 foreach ($_FILES['file']['name'] as $key => $value) {
132 $fname = $value;
133 $err = "";
134 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
135 $fname = $value;
136 if (empty($fname)) {
137 $fname = htmlentities("<empty>");
139 $error = xl("Error number") .": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
140 if ($_FILES['file']['size'][$key] == 0) {
141 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
143 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
144 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
145 } else {
146 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
147 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
148 fclose($tmpfile);
149 if ($doDecryption) {
150 $filetext = $this->decrypt($filetext, $passphrase);
152 if ($_POST['destination'] != '') {
153 $fname = $_POST['destination'];
155 $mimetype = $_FILES['file']['type'][$key];
156 if ($mimetype == 'application/octet-stream') { // windows most likely...
157 $parts = pathinfo($fname);
158 if (strtolower($parts['extension']) == 'dcm') { // cheat for dicom on windows because MS must be different!!!
159 $mimetype = 'application/dicom';
161 } elseif (stripos($mimetype, 'zip') !== false) {
162 $za = new ZipArchive();
163 $handler = $za->open($_FILES['file']['tmp_name'][$key]);
164 if ($handler) {
165 $mimetype = "application/dicom+zip";
166 for ($i = 0; $i < $za->numFiles; $i++) {
167 $stat = $za->statIndex($i);
168 $parts = pathinfo($stat['name']);
169 if (strtolower($parts['extension']) != "dcm") {
170 $mimetype = "application/zip";
171 break;
176 $d = new Document();
177 $rc = $d->createDocument(
178 $patient_id,
179 $category_id,
180 $fname,
181 $mimetype,
182 $filetext,
183 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
184 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
185 $non_HTTP_owner,
186 $_FILES['file']['tmp_name'][$key]
188 if ($rc) {
189 $error .= $rc . "\n";
190 } else {
191 $this->assign("upload_success", "true");
193 $sentUploadStatus[] = $d;
194 $this->assign("file", $sentUploadStatus);
197 // Option to run a custom plugin for each file upload.
198 // This was initially created to delete the original source file in a custom setting.
199 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
200 if (file_exists($upload_plugin)) {
201 include_once($upload_plugin);
203 $upload_plugin_pp = 'documentUploadPostProcess';
204 if (function_exists($upload_plugin_pp)) {
205 $tmp = call_user_func($upload_plugin_pp, $value, $d);
206 if ($tmp) {
207 $error = $tmp;
210 // Following is just an example of code in such a plugin file.
211 /*****************************************************
212 function documentUploadPostProcess($filename, &$d) {
213 $userid = $_SESSION['authUserID'];
214 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
215 $owner = strtolower($row['username']);
216 $dn = '1_' . ucfirst($owner);
217 $filepath = "/shared_network_directory/$dn/$filename";
218 if (@unlink($filepath)) return '';
219 return "Failed to delete '$filepath'.";
221 *****************************************************/
225 $this->assign("error", nl2br($error));
226 //$this->_state = false;
227 $_POST['process'] = "";
228 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
231 function note_action_process($patient_id)
233 // this function is a dual function that will set up a note associated with a document or send a document via email.
235 if ($_POST['process'] != "true") {
236 return;
239 $n = new Note();
240 $n->set_owner($_SESSION['authUserID']);
241 parent::populate_object($n);
242 if ($_POST['identifier'] == "no") {
243 // associate a note with a document
244 $n->persist();
245 } elseif ($_POST['identifier'] == "yes") {
246 // send the document via email
247 $d = new Document($_POST['foreign_id']);
248 $url = $d->get_url();
249 $storagemethod = $d->get_storagemethod();
250 $couch_docid = $d->get_couch_docid();
251 $couch_revid = $d->get_couch_revid();
252 if ($couch_docid && $couch_revid) {
253 $couch = new CouchDB();
254 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
255 $resp = $couch->retrieve_doc($data);
256 $content = $resp->data;
257 if ($content=='' && $GLOBALS['couchdb_log']==1) {
258 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
259 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
260 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
261 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
262 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
263 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
264 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
265 die(xlt("File retrieval from CouchDB failed"));
267 // place it in a temporary file and will remove the file below after emailed
268 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
269 $fh = fopen($temp_couchdb_url, "w");
270 fwrite($fh, base64_decode($content));
271 fclose($fh);
272 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
273 } else {
274 $url = preg_replace("|^(.*)://|", "", $url);
275 // Collect filename and path
276 $from_all = explode("/", $url);
277 $from_filename = array_pop($from_all);
278 $from_pathname_array = array();
279 for ($i=0; $i<$d->get_path_depth(); $i++) {
280 $from_pathname_array[] = array_pop($from_all);
282 $from_pathname_array = array_reverse($from_pathname_array);
283 $from_pathname = implode("/", $from_pathname_array);
284 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
286 if (!file_exists($temp_url)) {
287 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;
289 $url = $temp_url;
290 $body_notes = attr($_POST['note']);
291 $pdetails = getPatientData($patient_id);
292 $pname = $pdetails['fname']." ".$pdetails['lname'];
293 $this->document_send($_POST['provide_email'], $body_notes, $url, $pname);
294 if ($couch_docid && $couch_revid) {
295 // remove the temporary couchdb file
296 unlink($temp_couchdb_url);
299 $this->_state = false;
300 $_POST['process'] = "";
301 return $this->view_action($patient_id, $n->get_foreign_id());
304 function default_action()
306 return $this->list_action();
309 function view_action($patient_id = "", $doc_id)
311 // Added by Rod to support document delete:
312 global $gacl_object, $phpgacl_location;
313 global $ISSUE_TYPES;
315 require_once(dirname(__FILE__) . "/../library/acl.inc");
316 require_once(dirname(__FILE__) . "/../library/lists.inc");
318 $d = new Document($doc_id);
319 $notes = $d->get_notes();
321 $this->assign("file", $d);
322 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
323 $this->assign("NOTE_ACTION", $this->_link("note"));
324 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
325 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
326 $this->assign("assets_static_relative", $GLOBALS['assets_static_relative']);
327 $this->assign("webroot", $GLOBALS['webroot']);
329 // Added by Rod to support document delete:
330 $delete_string = '';
331 if (acl_check('admin', 'super')) {
332 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
333 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
335 $this->assign("delete_string", $delete_string);
336 $this->assign("REFRESH_ACTION", $this->_link("list"));
338 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
339 "document_id=" . $d->get_id() . "&process=true");
341 // Added by Rod to support document date update:
342 $this->assign("DOCDATE", $d->get_docdate());
343 $this->assign("UPDATE_ACTION", $this->_link("update") .
344 "document_id=" . $d->get_id() . "&process=true");
346 // Added by Rod to support document issue update:
347 $issues_options = "<option value='0'>-- " . xlt('Select Issue') . " --</option>";
348 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
349 "pid = ? " . // AND enddate IS NULL " .
350 "ORDER BY type, begdate", array($patient_id));
351 while ($irow = sqlFetchArray($ires)) {
352 $desc = $irow['type'];
353 if ($ISSUE_TYPES[$desc]) {
354 $desc = $ISSUE_TYPES[$desc][2];
356 $desc .= ": " . text($irow['begdate']) . " " . text(substr($irow['title'], 0, 40));
357 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
358 $issues_options .= "<option value='" . attr($irow['id']) . "'$sel>$desc</option>";
360 $this->assign("ISSUES_LIST", $issues_options);
362 // For tagging to encounter
363 // Populate the dropdown with patient's encounter list
364 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
365 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
366 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
367 "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));
368 if (sqlNumRows($result_docs) > 0) {
369 while ($row_result_docs = sqlFetchArray($result_docs)) {
370 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
371 $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>";
374 $this->assign("ENC_LIST", $encOptions);
376 //clear encounter tag
377 if ($d->get_encounter_id() != 0) {
378 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
379 } else {
380 $this->assign('clear_encounter_tag', 'javascript:void(0)');
383 //Populate the dropdown with category list
384 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
385 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
386 while ($crow = sqlFetchArray($cres)) {
387 $catid = $crow['pc_catid'];
388 if ($catid < 9 && $catid != 5) {
389 continue; // Applying same logic as in new encounter page.
391 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
393 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
395 $this->assign("notes", $notes);
397 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
398 // Populate the dropdown with image procedure order list
399 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
400 $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));
401 $mapping = $this->get_mapped_procedure($d->get_id());
402 if (sqlNumRows($imgOrders) > 0) {
403 while ($row = sqlFetchArray($imgOrders)) {
404 $sel_proc = '';
405 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
406 $sel_proc = 'selected';
408 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
412 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
414 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
416 $this->_last_node = null;
418 $menu = new HTML_TreeMenu();
420 //pass an empty array because we don't want the documents for each category showing up in this list box
421 $rnode = $this->_array_recurse($this->tree->tree, array());
422 $menu->addItem($rnode);
423 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
425 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
427 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
428 $this->assign("activity", $activity);
430 return $this->list_action($patient_id);
433 function encrypt($plaintext, $key)
435 return aes256Encrypt($plaintext, $key, false);
438 function decrypt($crypttext, $key)
440 return aes256Decrypt($crypttext, $key, false);
444 * Retrieve file from hard disk / CouchDB.
445 * In case that file isn't download this function will return thumbnail image (if exist).
446 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
447 * @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.
448 * */
449 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
451 $encrypted = $_POST['encrypted'];
452 $passphrase = $_POST['passphrase'];
453 $doEncryption = false;
454 if (!$GLOBALS['hide_document_encryption'] &&
455 $encrypted == "true" &&
456 $passphrase ) {
457 $doEncryption = true;
460 //controller function ruins booleans, so need to manually re-convert to booleans
461 if ($as_file == "true") {
462 $as_file=true;
463 } else if ($as_file == "false") {
464 $as_file=false;
466 if ($original_file == "true") {
467 $original_file=true;
468 } else if ($original_file == "false") {
469 $original_file=false;
471 if ($disable_exit == "true") {
472 $disable_exit=true;
473 } else if ($disable_exit == "false") {
474 $disable_exit=false;
476 if ($show_original == "true") {
477 $show_original=true;
478 } else if ($show_original == "false") {
479 $show_original=false;
482 switch ($context) {
483 case "patient_picture":
484 $this->patientService->setPid($patient_id);
485 $document_id = $this->patientService->getPatientPictureDocumentId();
486 break;
489 $d = new Document($document_id);
490 $url = $d->get_url();
491 $th_url = $d->get_thumb_url();
493 $storagemethod = $d->get_storagemethod();
494 $couch_docid = $d->get_couch_docid();
495 $couch_revid = $d->get_couch_revid();
497 if ($couch_docid && $couch_revid && $original_file) {
498 $couch = new CouchDB();
499 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
500 $resp = $couch->retrieve_doc($data);
501 //Take thumbnail file when is not null and file is presented online
502 if (!$as_file && !is_null($th_url) && !$show_original) {
503 $content = $resp->th_data;
504 } else {
505 $content = $resp->data;
507 if ($content=='' && $GLOBALS['couchdb_log']==1) {
508 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
509 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
510 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
511 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
512 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
513 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
514 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
515 die(xl("File retrieval from CouchDB failed"));
517 if ($disable_exit == true) {
518 return base64_decode($content);
520 header('Content-Description: File Transfer');
521 header('Content-Transfer-Encoding: binary');
522 header('Expires: 0');
523 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
524 header('Pragma: public');
525 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
526 $fh = fopen($tmpcouchpath, "w");
527 fwrite($fh, base64_decode($content));
528 fclose($fh);
529 $f = fopen($tmpcouchpath, "r");
530 if ($doEncryption) {
531 $filetext = fread($f, filesize($tmpcouchpath));
532 $ciphertext = $this->encrypt($filetext, $passphrase);
533 $tmpfilepath = $GLOBALS['temporary_files_dir'];
534 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
535 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
536 fwrite($tmpfile, $ciphertext);
537 fclose($tmpfile);
538 header('Content-Disposition: attachment; filename='.$tmpfilename);
539 header("Content-Type: application/octet-stream");
540 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
541 ob_clean();
542 flush();
543 readfile($tmpfilepath.$tmpfilename);
544 unlink($tmpfilepath.$tmpfilename);
545 } else {
546 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
547 header("Content-Type: " . $d->get_mimetype());
548 header("Content-Length: " . filesize($tmpcouchpath));
549 fpassthru($f);
551 fclose($f);
552 if ($content!='') {
553 unlink($tmpcouchpath);
555 exit;//exits only if file download from CouchDB is successfull.
558 //Take thumbnail file when is not null and file is presented online
559 if (!$as_file && !is_null($th_url) && !$show_original) {
560 $url = $th_url;
563 //strip url of protocol handler
564 $url = preg_replace("|^(.*)://|", "", $url);
566 //change full path to current webroot. this is for documents that may have
567 //been moved from a different filesystem and the full path in the database
568 //is not current. this is also for documents that may of been moved to
569 //different patients. Note that the path_depth is used to see how far down
570 //the path to go. For example, originally the path_depth was always 1, which
571 //only allowed things like documents/1/<file>, but now can have more structured
572 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
573 // etc.
574 // NOTE that $from_filename and basename($url) are the same thing
575 $from_all = explode("/", $url);
576 $from_filename = array_pop($from_all);
577 $from_pathname_array = array();
578 for ($i=0; $i<$d->get_path_depth(); $i++) {
579 $from_pathname_array[] = array_pop($from_all);
581 $from_pathname_array = array_reverse($from_pathname_array);
582 $from_pathname = implode("/", $from_pathname_array);
583 if ($couch_docid && $couch_revid) {
584 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
585 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
586 } else {
587 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
590 if (file_exists($temp_url)) {
591 $url = $temp_url;
595 if (!file_exists($url)) {
596 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;
597 } else {
598 if ($original_file) {
599 //normal case when serving the file referenced in database
600 if ($disable_exit == true) {
601 $f = fopen($url, "r");
602 $filetext = fread($f, filesize($url));
603 return $filetext;
605 header('Content-Description: File Transfer');
606 header('Content-Transfer-Encoding: binary');
607 header('Expires: 0');
608 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
609 header('Pragma: public');
610 $f = fopen($url, "r");
611 if ($doEncryption) {
612 $filetext = fread($f, filesize($url));
613 $ciphertext = $this->encrypt($filetext, $passphrase);
614 $tmpfilepath = $GLOBALS['temporary_files_dir'];
615 $tmpfilename = "/encrypted_aes_".$d->get_url_file();
616 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
617 fwrite($tmpfile, $ciphertext);
618 fclose($tmpfile);
619 header('Content-Disposition: attachment; filename='.$tmpfilename);
620 header("Content-Type: application/octet-stream");
621 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
622 ob_clean();
623 flush();
624 readfile($tmpfilepath.$tmpfilename);
625 unlink($tmpfilepath.$tmpfilename);
626 } else {
627 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
628 header("Content-Type: " . $d->get_mimetype());
629 header("Content-Length: " . filesize($url));
630 fpassthru($f);
632 exit;
633 } else {
634 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
635 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
636 if ($couch_docid && $couch_revid) {
637 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
638 } else {
639 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
641 if ($disable_exit == true) {
642 return ;
644 header("Pragma: public");
645 header("Expires: 0");
646 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
647 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
648 header("Content-Type: image/jpeg");
649 header("Content-Length: " . filesize($url));
650 $f = fopen($url, "r");
651 fpassthru($f);
652 if ($couch_docid && $couch_revid) {
653 fclose($f);
654 unlink($url);
655 $url=str_replace("_converted.jpg", '.pdf', $url);
656 unlink($url);
658 exit;
663 function queue_action($patient_id = "")
665 $messages = $this->_tpl_vars['messages'];
666 $queue_files = array();
668 //see if the repository exists and it is a directory else error
669 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
670 $dir = opendir($this->_config['repository']);
671 //read each entry in the directory
672 while (($file = readdir($dir)) !== false) {
673 //concat the filename and path
674 $file = $this->_config['repository'] .$file;
675 $file_info = array();
676 //if the filename is a file get its info and put into a tmp array
677 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
678 $file_info['filename'] = basename_international($file);
679 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
680 $d = $this->Document->document_factory_url("file://" . $file);
681 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
682 $file_info['patient_id'] = $patient_match[1];
683 $file_info['document_id'] = $d->get_id();
684 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
686 //merge the tmp array into the larger array
687 $queue_files[] = $file_info;
690 closedir($dir);
691 } else {
692 $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";
696 $this->assign("queue_files", $queue_files);
697 $this->_last_node = null;
699 $menu = new HTML_TreeMenu();
701 //pass an empty array because we don't want the documents for each category showing up in this list box
702 $rnode = $this->_array_recurse($this->tree->tree, array());
703 $menu->addItem($rnode);
704 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
706 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
708 $this->assign("messages", nl2br($messages));
709 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
712 function queue_action_process()
714 if ($_POST['process'] != "true") {
715 return;
718 $messages = $this->_tpl_vars['messages'];
720 //build a category tree so we can have a list of category ids that are valid
721 $ct = new CategoryTree(1);
722 $categories = $ct->_id_name;
724 //see if there were and posted files and assign them
725 $files = null;
726 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
728 //loop through posted files
729 foreach ($files as $doc_id => $file) {
730 //only operate on files checked as active
731 if (!$file['active']) {
732 continue;
735 //run basic validation checks
736 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
737 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
738 continue;
741 //validate that the pod exists
742 $d = new Document($doc_id);
743 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
744 $result = $d->_db->Execute($sql);
746 if (!$result || $result->EOF) {
747 //patient id does not exist
748 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
749 continue;
752 //validate that the category id exists
753 if (!isset($categories[$file['category_id']])) {
754 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
755 continue;
758 //now do the work of moving the file
759 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
761 //see if the patient dir exists in the repository and create if not
762 if (!file_exists($new_path)) {
763 if (!mkdir($new_path, 0700)) {
764 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
765 continue;
769 //fname is the name of the file after it is moved
770 $fname = $file['name'];
772 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
773 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
774 if ($patient_match[1] == $file['patient_id']) {
775 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
778 //filenames should not have funny chars
779 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
781 //see if there is an existing file with the same name and rename as necessary
782 if (file_exists($new_path.$file['name'])) {
783 $messages .= "File with same name already exists at location: " . $new_path . "\n";
784 $fname = basename_international($this->_rename_file($new_path.$file['name']));
785 $messages .= "Current file name was changed to " . $fname ."\n";
788 //now move the file
789 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
790 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
791 $d->url = "file://" .$new_path.$fname;
792 $d->set_foreign_id($file['patient_id']);
793 $d->set_mimetype($mimetype);
794 $d->persist();
795 $d->populate();
797 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
798 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
799 $d->_db->Execute($sql);
801 } else {
802 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
805 $this->assign("messages", $messages);
806 $_POST['process'] = "";
809 function move_action_process($patient_id = "", $document_id)
811 if ($_POST['process'] != "true") {
812 return;
815 $new_category_id = $_POST['new_category_id'];
816 $new_patient_id = $_POST['new_patient_id'];
818 //move to new category
819 if (is_numeric($new_category_id) && is_numeric($document_id)) {
820 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
821 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
822 //echo $sql;
823 $this->tree->_db->Execute($sql);
826 //move to new patient
827 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
828 $d = new Document($document_id);
829 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
830 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
831 $result = $d->_db->Execute($sql);
833 if (!$result || $result->EOF) {
834 //patient id does not exist
835 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
836 } else {
837 $couchsavefailed = !$d->change_patient($new_patient_id);
839 $this->_state = false;
840 if (!$couchsavefailed) {
841 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
842 } else {
843 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
845 $this->assign("messages", $messages);
846 return $this->list_action($patient_id);
848 } //in this case return the document to the queue instead of moving it
849 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
850 $d = new Document($document_id);
851 $new_path = $this->_config['repository'];
852 $fname = $d->get_url_file();
854 //see if there is an existing file with the same name and rename as necessary
855 if (file_exists($new_path.$d->get_url_file())) {
856 $messages .= "File with same name already exists in the queue.\n";
857 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
858 $messages .= "Current file name was changed to " . $fname ."\n";
861 //now move the file
862 if (rename($d->get_url_filepath(), $new_path.$fname)) {
863 $d->url = "file://" .$new_path.$fname;
864 $d->set_foreign_id("");
865 $d->persist();
866 $d->persist();
867 $d->populate();
869 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
870 $d->_db->Execute($sql);
871 $messages .= "Document returned to queue successfully.\n";
872 } else {
873 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
876 $this->_state = false;
877 $this->assign("messages", $messages);
878 return $this->list_action($patient_id);
881 $this->_state = false;
882 $this->assign("messages", $messages);
883 return $this->view_action($patient_id, $document_id);
886 function validate_action_process($patient_id = "", $document_id)
889 $d = new Document($document_id);
890 if ($d->couch_docid && $d->couch_revid) {
891 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
892 $url = $file_path.$d->get_url();
893 $couch = new CouchDB();
894 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
895 $resp = $couch->retrieve_doc($data);
896 $content = $resp->data;
897 //--------Temporarily writing the file for calculating the hash--------//
898 //-----------Will be removed after calculating the hash value----------//
899 $temp_file = fopen($url, "w");
900 fwrite($temp_file, base64_decode($content));
901 fclose($temp_file);
902 } else {
903 $url = $d->get_url();
905 //strip url of protocol handler
906 $url = preg_replace("|^(.*)://|", "", $url);
908 //change full path to current webroot. this is for documents that may have
909 //been moved from a different filesystem and the full path in the database
910 //is not current. this is also for documents that may of been moved to
911 //different patients. Note that the path_depth is used to see how far down
912 //the path to go. For example, originally the path_depth was always 1, which
913 //only allowed things like documents/1/<file>, but now can have more structured
914 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
915 // etc.
916 // NOTE that $from_filename and basename($url) are the same thing
917 $from_all = explode("/", $url);
918 $from_filename = array_pop($from_all);
919 $from_pathname_array = array();
920 for ($i=0; $i<$d->get_path_depth(); $i++) {
921 $from_pathname_array[] = array_pop($from_all);
923 $from_pathname_array = array_reverse($from_pathname_array);
924 $from_pathname = implode("/", $from_pathname_array);
925 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
926 if (file_exists($temp_url)) {
927 $url = $temp_url;
930 if ($_POST['process'] != "true") {
931 die("process is '" . $_POST['process'] . "', expected 'true'");
932 return;
935 $d = new Document($document_id);
936 $current_hash = sha1_file($url);
937 $messages = xl('Current Hash').": ".$current_hash."<br>";
938 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
939 if ($d->get_hash() == '') {
940 $d->hash = $current_hash;
941 $d->persist();
942 $d->populate();
943 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
944 } else if ($current_hash != $d->get_hash()) {
945 $messages .= xl('Hash does not match. Data integrity has been compromised.');
946 } else {
947 $messages .= xl('Document passed integrity check.');
949 $this->_state = false;
950 $this->assign("messages", $messages);
951 if ($d->couch_docid && $d->couch_revid) {
952 //Removing the temporary file which is used to create the hash
953 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
955 return $this->view_action($patient_id, $document_id);
958 // Added by Rod for metadata update.
960 function update_action_process($patient_id = "", $document_id)
963 if ($_POST['process'] != "true") {
964 die("process is '" . $_POST['process'] . "', expected 'true'");
965 return;
968 $docdate = $_POST['docdate'];
969 $docname = $_POST['docname'];
970 $issue_id = $_POST['issue_id'];
972 if (is_numeric($document_id)) {
973 $messages = '';
974 $d = new Document($document_id);
975 $file_name = $d->get_url_file();
976 if ($docname != '' &&
977 $docname != $file_name ) {
978 // Ready to rename - check for relocation
979 $old_url = $this->_check_relocation($d->get_url());
980 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
981 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
982 if (rename($old_url, $new_url)) {
983 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
984 if (file_exists($old_url)) {
985 unlink($old_url);
987 $d->url = $new_url;
988 $d->persist();
989 $d->populate();
990 $messages .= xl('Document successfully renamed.')."<br>";
991 } else {
992 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
996 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
997 $docdate = "'$docdate'";
998 } else {
999 $docdate = "NULL";
1001 if (!is_numeric($issue_id)) {
1002 $issue_id = 0;
1004 $couch_docid = $d->get_couch_docid();
1005 $couch_revid = $d->get_couch_revid();
1006 if ($couch_docid && $couch_revid) {
1007 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
1008 "list_id = '$issue_id' " .
1009 "WHERE id = '$document_id'";
1010 $this->tree->_db->Execute($sql);
1011 } else {
1012 $sql = "UPDATE documents SET docdate = $docdate, " .
1013 "list_id = '$issue_id' " .
1014 "WHERE id = '$document_id'";
1015 $this->tree->_db->Execute($sql);
1017 $messages .= xl('Document date and issue updated successfully') . "<br>";
1020 $this->_state = false;
1021 $this->assign("messages", $messages);
1022 return $this->view_action($patient_id, $document_id);
1025 function list_action($patient_id = "")
1027 $this->_last_node = null;
1028 $categories_list = $this->tree->_get_categories_array($patient_id);
1029 //print_r($categories_list);
1031 $menu = new HTML_TreeMenu();
1032 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1033 $menu->addItem($rnode);
1034 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1035 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1036 $this->assign("tree_html", $treeMenu->toHTML());
1038 $is_new = isset($_GET['patient_name']) ? 1 : false;
1039 $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl("Patient search or select.");
1040 $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';
1041 $used_msg = xl('Current patient unavailable here. Use Patient Documents');
1042 if ($cur_pid == '00') {
1043 $cur_pid = '0';
1044 $is_new = 1;
1046 $this->assign('is_new', $is_new);
1047 $this->assign('place_hld', $place_hld);
1048 $this->assign('cur_pid', $cur_pid);
1049 $this->assign('used_msg', $used_msg);
1050 $this->assign('demo_pid', $_SESSION['pid']);
1052 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1055 /* This is a recursive function to rename a file to something that doesn't already exist.
1056 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1057 * at end) to ensure documents opened correctly by external browser viewers. If the
1058 * counter is at the end of the file, then will use it (to continue to work with older
1059 * files), however all new counters will be placed within filenames.
1061 * Modified to only deal with base file name when renaming, to avoid issues with directory
1062 * names with dots.
1064 function _rename_file($fname, $self = false)
1066 // Allow same routine for new file name check
1067 if (!file_exists($fname)) {
1068 return($fname);
1071 $path = dirname($fname);
1072 $file = basename_international($fname);
1074 $fparts = explode(".", $file);
1075 switch (count($fparts)) {
1076 case 1:
1077 // Has a single node (base file name). Create counter node with value 0
1078 $fparts[1] = '1';
1079 break;
1080 case 2:
1081 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1082 if (is_numeric($fparts[1])) {
1083 $fparts[1] += 1;
1084 } else {
1085 array_push($fparts, $fparts[1]);
1086 $fparts[1] = '1';
1088 break;
1089 default:
1090 // Multiple nodes
1091 $ix_end = count($fparts) - 1;
1092 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1093 // Switch old style to new and check again
1094 $wrk = $fparts[$ix_end - 1];
1095 $fparts[$ix_end - 1] = $fparts[$ix_end];
1096 $fparts[$ix_end] = $wrk;
1097 } else if (is_numeric($fparts[$ix_end - 1])) {
1098 $fparts[$ix_end - 1] += 1;
1099 } else {
1100 array_push($fparts, $fparts[$ix_end]);
1101 $fparts[$ix_end] = '1';
1103 break;
1106 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1108 if (file_exists($fname)) {
1109 return $this->_rename_file($fname, true);
1110 } else {
1111 return($fname);
1115 function &_array_recurse($array, $categories = array())
1117 if (!is_array($array)) {
1118 $array = array();
1120 $node = &$this->_last_node;
1121 $current_node = &$node;
1122 $expandedIcon = 'folder-expanded.gif';
1123 foreach ($array as $id => $ar) {
1124 $icon = 'folder.gif';
1125 if (is_array($ar) || !empty($id)) {
1126 if ($node == null) {
1127 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1128 $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));
1129 $this->_last_node = &$rnode;
1130 $node = &$rnode;
1131 $current_node = &$rnode;
1132 } else {
1133 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1134 $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)));
1135 $current_node = &$this->_last_node;
1138 $this->_array_recurse($ar, $categories);
1139 } else {
1140 if ($id === 0 && !empty($ar)) {
1141 $info = $this->tree->get_node_info($id);
1142 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1143 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1144 } else {
1145 //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
1146 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1147 if ($id !== 0 && is_object($node)) {
1148 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1149 $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)));
1154 // If there are documents in this document category, then add their
1155 // attributes to the current node.
1156 $icon = "file3.png";
1157 if (is_array($categories[$id])) {
1158 foreach ($categories[$id] as $doc) {
1159 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1160 // If user has no access then there will be no link.
1161 if (!acl_check_aco_spec($doc['aco_spec'])) {
1162 $link = '';
1164 if ($this->tree->get_node_name($id) == "CCR") {
1165 $current_node->addItem(new HTML_TreeNode(array(
1166 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1167 'link' => $link,
1168 'icon' => $icon,
1169 'expandedIcon' => $expandedIcon,
1170 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','_blank');")
1171 )));
1172 } elseif ($this->tree->get_node_name($id) == "CCD") {
1173 $current_node->addItem(new HTML_TreeNode(array(
1174 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1175 'link' => $link,
1176 'icon' => $icon,
1177 'expandedIcon' => $expandedIcon,
1178 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','_blank');")
1179 )));
1180 } else {
1181 $current_node->addItem(new HTML_TreeNode(array(
1182 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1183 'link' => $link,
1184 'icon' => $icon,
1185 'expandedIcon' => $expandedIcon
1186 )));
1191 return $node;
1194 //function for logging the errors in writing file to CouchDB/Hard Disk
1195 function document_upload_download_log($patientid, $content)
1197 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1198 $log_file = 'log.txt';
1199 if (!is_dir($log_path)) {
1200 mkdir($log_path, 0777, true);
1202 $LOG = fopen($log_path.$log_file, 'a');
1203 fwrite($LOG, $content);
1204 fclose($LOG);
1207 function document_send($email, $body, $attfile, $pname)
1209 if (empty($email)) {
1210 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1211 return;
1214 $desc = "Please check the attached patient document.\n Content:".attr($body);
1215 $mail = new MyMailer();
1216 $from_name = $GLOBALS["practice_return_email_path"];
1217 $from = $GLOBALS["practice_return_email_path"];
1218 $mail->AddReplyTo($from, $from_name);
1219 $mail->SetFrom($from, $from);
1220 $to = $email ;
1221 $to_name =$email;
1222 $mail->AddAddress($to, $to_name);
1223 $subject = "Patient documents";
1224 $mail->Subject = $subject;
1225 $mail->Body = $desc;
1226 $mail->AddAttachment($attfile);
1227 if ($mail->Send()) {
1228 $retstatus = "email_sent";
1229 } else {
1230 $email_status = $mail->ErrorInfo;
1231 //echo "EMAIL ERROR: ".$email_status;
1232 $retstatus = "email_fail";
1236 //place to hold optional code
1237 //$first_node = array_keys($t->tree);
1238 //$first_node = $first_node[0];
1239 //$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')"));
1241 //$this->_last_node = &$node1;
1243 // Function to tag a document to an encounter.
1244 function tag_action_process($patient_id = "", $document_id)
1246 if ($_POST['process'] != "true") {
1247 die("process is '" . text($_POST['process']) . "', expected 'true'");
1248 return;
1251 // Create Encounter and Tag it.
1252 $event_date = date('Y-m-d H:i:s');
1253 $encounter_id = $_POST['encounter_id'];
1254 $encounter_check = $_POST['encounter_check'];
1255 $visit_category_id = $_POST['visit_category_id'];
1257 if (is_numeric($document_id)) {
1258 $messages = '';
1259 $d = new Document($document_id);
1260 $file_name = $d->get_url_file();
1261 if (!is_numeric($encounter_id)) {
1262 $encounter_id = 0;
1265 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1266 if ($encounter_check) {
1267 $provider_id = $_SESSION['authUserID'] ;
1269 // Get the logged in user's facility
1270 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1271 $username = $facilityRow['username'];
1272 $facility = $facilityRow['facility'];
1273 $facility_id = $facilityRow['facility_id'];
1274 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1275 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1276 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1278 $conn = $GLOBALS['adodb']['db'];
1279 $encounter = $conn->GenID("sequences");
1280 $query = "INSERT INTO form_encounter SET
1281 date = ?,
1282 reason = ?,
1283 facility = ?,
1284 sensitivity = 'normal',
1285 pc_catid = ?,
1286 facility_id = ?,
1287 billing_facility = ?,
1288 provider_id = ?,
1289 pid = ?,
1290 encounter = ?";
1291 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1292 $formID = sqlInsert($query, $bindArray);
1293 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1294 $d->set_encounter_id($encounter);
1295 $this->image_result_indication($d->id, $encounter);
1296 } else {
1297 $d->set_encounter_id($encounter_id);
1298 $this->image_result_indication($d->id, $encounter_id);
1300 $d->set_encounter_check($encounter_check);
1301 $d->persist();
1303 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1306 $this->_state = false;
1307 $this->assign("messages", $messages);
1309 return $this->view_action($patient_id, $document_id);
1312 function image_procedure_action($patient_id = "", $document_id)
1315 $img_procedure_id = $_POST['image_procedure_id'];
1316 $proc_code = $_POST['procedure_code'];
1318 if (is_numeric($document_id)) {
1319 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1320 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1321 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1322 if ($img_report_id == 0) {
1323 $report_date = date('Y-m-d H:i:s');
1324 $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));
1327 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1328 if (empty($img_result)) {
1329 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));
1332 $this->image_result_indication($document_id, 0, $img_procedure_id);
1334 return $this->view_action($patient_id, $document_id);
1337 function clear_procedure_tag_action($patient_id = "", $document_id)
1339 if (is_numeric($document_id)) {
1340 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1342 return $this->view_action($patient_id, $document_id);
1345 function get_mapped_procedure($document_id)
1347 $map = array();
1348 if (is_numeric($document_id)) {
1349 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1350 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1351 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1352 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1353 where pres.document_id = ?", array($document_id));
1355 return $map;
1358 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1360 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1361 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1363 if ($encounter != 0) {
1364 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1365 } else if ($image_procedure_id != 0) {
1366 $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));
1367 } else {
1368 $ep = array('assigned_to' => $_SESSION['authUser']);
1371 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1372 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1373 setGpRelation(1, $doc_id, 6, $noteid);
1376 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1377 * Also usable for documents that may of been moved to different patients.
1379 * @param string $url - Current url string from database.
1380 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1381 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1383 * @return string
1385 function _check_relocation($url, $new_pid = null, $new_name = null)
1387 //strip url of protocol handler
1388 $url = preg_replace("|^(.*)://|", "", $url);
1389 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1390 while (current($fsnodes) != "documents") {
1391 array_shift($fsnodes);
1393 if ($new_pid) {
1394 $fsnodes[1] = $new_pid;
1396 if ($new_name) {
1397 $fsnodes[count($fsnodes)-1] = $new_name;
1399 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1400 // Make sure the url is available after corrections
1401 if ($new_pid || $new_name) {
1402 $url = $this->_rename_file($url);
1404 //Add full path and remaining nodes
1405 return $url;
1408 //clear encounter tag function
1409 function clear_encounter_tag_action($patient_id = "", $document_id)
1411 if (is_numeric($document_id)) {
1412 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1414 return $this->view_action($patient_id, $document_id);