Highway to PSR2
[openemr.git] / controllers / C_Document.class.php
bloba7caf7a15ea92368d74a7d027285ce788bf0ba81
1 <?php
2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 require_once(dirname(__FILE__) . "/../library/forms.inc");
9 class C_Document extends Controller
12 var $template_mod;
13 var $documents;
14 var $document_categories;
15 var $tree;
16 var $_config;
17 var $manual_set_owner=false; // allows manual setting of a document owner/service
18 var $facilityService;
19 var $patientService;
21 function __construct($template_mod = "general")
23 parent::__construct();
24 $this->facilityService = new \services\FacilityService();
25 $this->patientService = new \services\PatientService();
26 $this->documents = array();
27 $this->template_mod = $template_mod;
28 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
29 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
31 //get global config options for this namespace
32 $this->_config = $GLOBALS['oer_config']['documents'];
34 $this->_args = array("patient_id" => $_GET['patient_id']);
36 $this->assign("STYLE", $GLOBALS['style']);
37 $t = new CategoryTree(1);
38 //print_r($t->tree);
39 $this->tree = $t;
40 $this->Document = new Document();
43 function upload_action($patient_id, $category_id)
45 $category_name = $this->tree->get_node_name($category_id);
46 $this->assign("category_id", $category_id);
47 $this->assign("category_name", $category_name);
48 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
49 $this->assign("patient_id", $patient_id);
51 // Added by Rod to support document template download from general_upload.html.
52 // Cloned from similar stuff in manage_document_templates.php.
53 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
54 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
55 if (file_exists($templatedir)) {
56 $dh = opendir($templatedir);
58 if ($dh) {
59 $templateslist = array();
60 while (false !== ($sfname = readdir($dh))) {
61 if (substr($sfname, 0, 1) == '.') {
62 continue;
64 $templateslist[$sfname] = $sfname;
66 closedir($dh);
67 ksort($templateslist);
68 foreach ($templateslist as $sfname) {
69 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
70 "'>" . htmlspecialchars($sfname) . "</option>";
73 $this->assign("TEMPLATES_LIST", $templates_options);
75 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
76 $this->assign("activity", $activity);
77 return $this->list_action($patient_id);
80 //Upload multiple files on single click
81 function upload_action_process()
84 // Collect a manually set owner if this has been set
85 // Used when want to manually assign the owning user/service such as the Direct mechanism
86 $non_HTTP_owner=false;
87 if ($this->manual_set_owner) {
88 $non_HTTP_owner=$this->manual_set_owner;
91 $couchDB = false;
92 $harddisk = false;
93 if ($GLOBALS['document_storage_method']==0) {
94 $harddisk = true;
96 if ($GLOBALS['document_storage_method']==1) {
97 $couchDB = true;
100 if ($_POST['process'] != "true") {
101 return;
104 $doDecryption = false;
105 $encrypted = $_POST['encrypted'];
106 $passphrase = $_POST['passphrase'];
107 if (!$GLOBALS['hide_document_encryption'] &&
108 $encrypted && $passphrase ) {
109 $doDecryption = true;
112 if (is_numeric($_POST['category_id'])) {
113 $category_id = $_POST['category_id'];
116 $patient_id = 0;
117 if (isset($_GET['patient_id']) && !$couchDB) {
118 $patient_id = $_GET['patient_id'];
119 } else if (is_numeric($_POST['patient_id'])) {
120 $patient_id = $_POST['patient_id'];
123 $sentUploadStatus = array();
124 if (count($_FILES['file']['name']) > 0) {
125 $upl_inc = 0;
127 foreach ($_FILES['file']['name'] as $key => $value) {
128 $fname = $value;
129 $err = "";
130 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
131 $fname = $value;
132 if (empty($fname)) {
133 $fname = htmlentities("<empty>");
135 $error = xl("Error number") .": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
136 if ($_FILES['file']['size'][$key] == 0) {
137 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
139 } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {
140 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
141 } else {
142 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
143 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
144 fclose($tmpfile);
145 if ($doDecryption) {
146 $filetext = $this->decrypt($filetext, $passphrase);
148 if ($_POST['destination'] != '') {
149 $fname = $_POST['destination'];
151 $d = new Document();
152 $rc = $d->createDocument(
153 $patient_id,
154 $category_id,
155 $fname,
156 $_FILES['file']['type'][$key],
157 $filetext,
158 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
159 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
160 $non_HTTP_owner,
161 $_FILES['file']['tmp_name'][$key]
163 if ($rc) {
164 $error .= $rc . "\n";
165 } else {
166 $this->assign("upload_success", "true");
168 $sentUploadStatus[] = $d;
169 $this->assign("file", $sentUploadStatus);
172 // Option to run a custom plugin for each file upload.
173 // This was initially created to delete the original source file in a custom setting.
174 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
175 if (file_exists($upload_plugin)) {
176 include_once($upload_plugin);
178 $upload_plugin_pp = 'documentUploadPostProcess';
179 if (function_exists($upload_plugin_pp)) {
180 $tmp = call_user_func($upload_plugin_pp, $value, $d);
181 if ($tmp) {
182 $error = $tmp;
185 // Following is just an example of code in such a plugin file.
186 /*****************************************************
187 function documentUploadPostProcess($filename, &$d) {
188 $userid = $_SESSION['authUserID'];
189 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
190 $owner = strtolower($row['username']);
191 $dn = '1_' . ucfirst($owner);
192 $filepath = "/shared_network_directory/$dn/$filename";
193 if (@unlink($filepath)) return '';
194 return "Failed to delete '$filepath'.";
196 *****************************************************/
200 $this->assign("error", nl2br($error));
201 //$this->_state = false;
202 $_POST['process'] = "";
203 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
206 function note_action_process($patient_id)
208 // this function is a dual function that will set up a note associated with a document or send a document via email.
210 if ($_POST['process'] != "true") {
211 return;
214 $n = new Note();
215 $n->set_owner($_SESSION['authUserID']);
216 parent::populate_object($n);
217 if ($_POST['identifier'] == "no") {
218 // associate a note with a document
219 $n->persist();
220 } elseif ($_POST['identifier'] == "yes") {
221 // send the document via email
222 $d = new Document($_POST['foreign_id']);
223 $url = $d->get_url();
224 $storagemethod = $d->get_storagemethod();
225 $couch_docid = $d->get_couch_docid();
226 $couch_revid = $d->get_couch_revid();
227 if ($couch_docid && $couch_revid) {
228 $couch = new CouchDB();
229 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
230 $resp = $couch->retrieve_doc($data);
231 $content = $resp->data;
232 if ($content=='' && $GLOBALS['couchdb_log']==1) {
233 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
234 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
235 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
236 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
237 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
238 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
239 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
240 die(xlt("File retrieval from CouchDB failed"));
242 // place it in a temporary file and will remove the file below after emailed
243 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
244 $fh = fopen($temp_couchdb_url, "w");
245 fwrite($fh, base64_decode($content));
246 fclose($fh);
247 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
248 } else {
249 $url = preg_replace("|^(.*)://|", "", $url);
250 // Collect filename and path
251 $from_all = explode("/", $url);
252 $from_filename = array_pop($from_all);
253 $from_pathname_array = array();
254 for ($i=0; $i<$d->get_path_depth(); $i++) {
255 $from_pathname_array[] = array_pop($from_all);
257 $from_pathname_array = array_reverse($from_pathname_array);
258 $from_pathname = implode("/", $from_pathname_array);
259 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
261 if (!file_exists($temp_url)) {
262 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;
264 $url = $temp_url;
265 $body_notes = attr($_POST['note']);
266 $pdetails = getPatientData($patient_id);
267 $pname = $pdetails['fname']." ".$pdetails['lname'];
268 $this->document_send($_POST['provide_email'], $body_notes, $url, $pname);
269 if ($couch_docid && $couch_revid) {
270 // remove the temporary couchdb file
271 unlink($temp_couchdb_url);
274 $this->_state = false;
275 $_POST['process'] = "";
276 return $this->view_action($patient_id, $n->get_foreign_id());
279 function default_action()
281 return $this->list_action();
284 function view_action($patient_id = "", $doc_id)
286 // Added by Rod to support document delete:
287 global $gacl_object, $phpgacl_location;
288 global $ISSUE_TYPES;
290 require_once(dirname(__FILE__) . "/../library/acl.inc");
291 require_once(dirname(__FILE__) . "/../library/lists.inc");
293 $d = new Document($doc_id);
294 $n = new Note();
296 $notes = $n->notes_factory($doc_id);
298 $this->assign("file", $d);
299 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
300 $this->assign("NOTE_ACTION", $this->_link("note"));
301 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
302 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
304 // Added by Rod to support document delete:
305 $delete_string = '';
306 if (acl_check('admin', 'super')) {
307 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
308 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
310 $this->assign("delete_string", $delete_string);
311 $this->assign("REFRESH_ACTION", $this->_link("list"));
313 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
314 "document_id=" . $d->get_id() . "&process=true");
316 // Added by Rod to support document date update:
317 $this->assign("DOCDATE", $d->get_docdate());
318 $this->assign("UPDATE_ACTION", $this->_link("update") .
319 "document_id=" . $d->get_id() . "&process=true");
321 // Added by Rod to support document issue update:
322 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
323 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
324 "pid = ? " . // AND enddate IS NULL " .
325 "ORDER BY type, begdate", array($patient_id));
326 while ($irow = sqlFetchArray($ires)) {
327 $desc = $irow['type'];
328 if ($ISSUE_TYPES[$desc]) {
329 $desc = $ISSUE_TYPES[$desc][2];
331 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
332 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
333 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
335 $this->assign("ISSUES_LIST", $issues_options);
337 // For tagging to encounter
338 // Populate the dropdown with patient's encounter list
339 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
340 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
341 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
342 "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));
343 if (sqlNumRows($result_docs) > 0) {
344 while ($row_result_docs = sqlFetchArray($result_docs)) {
345 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
346 $encOptions .= "<option value='" . attr($row_result_docs['encounter']) . "' $sel_enc>". oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date']))) . "-" . text(xl_appt_category($row_result_docs['pc_catname'])) . "</option>";
349 $this->assign("ENC_LIST", $encOptions);
351 //clear encounter tag
352 if ($d->get_encounter_id() != 0) {
353 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
354 } else {
355 $this->assign('clear_encounter_tag', 'javascript:void(0)');
358 //Populate the dropdown with category list
359 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
360 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
361 while ($crow = sqlFetchArray($cres)) {
362 $catid = $crow['pc_catid'];
363 if ($catid < 9 && $catid != 5) {
364 continue; // Applying same logic as in new encounter page.
366 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
368 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
370 $this->assign("notes", $notes);
372 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
373 // Populate the dropdown with image procedure order list
374 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
375 $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));
376 $mapping = $this->get_mapped_procedure($d->get_id());
377 if (sqlNumRows($imgOrders) > 0) {
378 while ($row = sqlFetchArray($imgOrders)) {
379 $sel_proc = '';
380 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
381 $sel_proc = 'selected';
383 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
387 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
389 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
391 $this->_last_node = null;
393 $menu = new HTML_TreeMenu();
395 //pass an empty array because we don't want the documents for each category showing up in this list box
396 $rnode = $this->_array_recurse($this->tree->tree, array());
397 $menu->addItem($rnode);
398 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
400 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
402 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
403 $this->assign("activity", $activity);
405 return $this->list_action($patient_id);
408 function encrypt($plaintext, $key, $cypher = 'tripledes', $mode = 'cfb')
410 $td = mcrypt_module_open($cypher, '', $mode, '');
411 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
412 mcrypt_generic_init($td, $key, $iv);
413 $crypttext = mcrypt_generic($td, $plaintext);
414 mcrypt_generic_deinit($td);
415 return $iv.$crypttext;
418 function decrypt($crypttext, $key, $cypher = 'tripledes', $mode = 'cfb')
420 $plaintext = '';
421 $td = mcrypt_module_open($cypher, '', $mode, '');
422 $ivsize = mcrypt_enc_get_iv_size($td) ;
423 $iv = substr($crypttext, 0, $ivsize);
424 $crypttext = substr($crypttext, $ivsize);
425 if ($iv) {
426 mcrypt_generic_init($td, $key, $iv);
427 $plaintext = mdecrypt_generic($td, $crypttext);
429 return $plaintext;
433 * Retrieve file from hard disk / CouchDB.
434 * In case that file isn't download this function will return thumbnail image (if exist).
435 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
436 * @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.
437 * */
438 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
440 $encrypted = $_POST['encrypted'];
441 $passphrase = $_POST['passphrase'];
442 $doEncryption = false;
443 if (!$GLOBALS['hide_document_encryption'] &&
444 $encrypted == "true" &&
445 $passphrase ) {
446 $doEncryption = true;
449 //controller function ruins booleans, so need to manually re-convert to booleans
450 if ($as_file == "true") {
451 $as_file=true;
452 } else if ($as_file == "false") {
453 $as_file=false;
455 if ($original_file == "true") {
456 $original_file=true;
457 } else if ($original_file == "false") {
458 $original_file=false;
460 if ($disable_exit == "true") {
461 $disable_exit=true;
462 } else if ($disable_exit == "false") {
463 $disable_exit=false;
465 if ($show_original == "true") {
466 $show_original=true;
467 } else if ($show_original == "false") {
468 $show_original=false;
471 switch ($context) {
472 case "patient_picture":
473 $this->patientService->setPid($patient_id);
474 $document_id = $this->patientService->getPatientPictureDocumentId();
475 break;
478 $d = new Document($document_id);
479 $url = $d->get_url();
480 $th_url = $d->get_thumb_url();
482 $storagemethod = $d->get_storagemethod();
483 $couch_docid = $d->get_couch_docid();
484 $couch_revid = $d->get_couch_revid();
486 if ($couch_docid && $couch_revid && $original_file) {
487 $couch = new CouchDB();
488 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
489 $resp = $couch->retrieve_doc($data);
490 //Take thumbnail file when is not null and file is presented online
491 if (!$as_file && !is_null($th_url) && !$show_original) {
492 $content = $resp->th_data;
493 } else {
494 $content = $resp->data;
496 if ($content=='' && $GLOBALS['couchdb_log']==1) {
497 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
498 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
499 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
500 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
501 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
502 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
503 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
504 die(xl("File retrieval from CouchDB failed"));
506 if ($disable_exit == true) {
507 return base64_decode($content);
509 header('Content-Description: File Transfer');
510 header('Content-Transfer-Encoding: binary');
511 header('Expires: 0');
512 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
513 header('Pragma: public');
514 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
515 $fh = fopen($tmpcouchpath, "w");
516 fwrite($fh, base64_decode($content));
517 fclose($fh);
518 $f = fopen($tmpcouchpath, "r");
519 if ($doEncryption) {
520 $filetext = fread($f, filesize($tmpcouchpath));
521 $ciphertext = $this->encrypt($filetext, $passphrase);
522 $tmpfilepath = $GLOBALS['temporary_files_dir'];
523 $tmpfilename = "/encrypted_".$d->get_url_file();
524 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
525 fwrite($tmpfile, $ciphertext);
526 fclose($tmpfile);
527 header('Content-Disposition: attachment; filename='.$tmpfilename);
528 header("Content-Type: application/octet-stream");
529 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
530 ob_clean();
531 flush();
532 readfile($tmpfilepath.$tmpfilename);
533 unlink($tmpfilepath.$tmpfilename);
534 } else {
535 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
536 header("Content-Type: " . $d->get_mimetype());
537 header("Content-Length: " . filesize($tmpcouchpath));
538 fpassthru($f);
540 fclose($f);
541 if ($content!='') {
542 unlink($tmpcouchpath);
544 exit;//exits only if file download from CouchDB is successfull.
547 //Take thumbnail file when is not null and file is presented online
548 if (!$as_file && !is_null($th_url) && !$show_original) {
549 $url = $th_url;
552 //strip url of protocol handler
553 $url = preg_replace("|^(.*)://|", "", $url);
555 //change full path to current webroot. this is for documents that may have
556 //been moved from a different filesystem and the full path in the database
557 //is not current. this is also for documents that may of been moved to
558 //different patients. Note that the path_depth is used to see how far down
559 //the path to go. For example, originally the path_depth was always 1, which
560 //only allowed things like documents/1/<file>, but now can have more structured
561 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
562 // etc.
563 // NOTE that $from_filename and basename($url) are the same thing
564 $from_all = explode("/", $url);
565 $from_filename = array_pop($from_all);
566 $from_pathname_array = array();
567 for ($i=0; $i<$d->get_path_depth(); $i++) {
568 $from_pathname_array[] = array_pop($from_all);
570 $from_pathname_array = array_reverse($from_pathname_array);
571 $from_pathname = implode("/", $from_pathname_array);
572 if ($couch_docid && $couch_revid) {
573 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
574 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
575 } else {
576 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
579 if (file_exists($temp_url)) {
580 $url = $temp_url;
584 if (!file_exists($url)) {
585 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;
586 } else {
587 if ($original_file) {
588 //normal case when serving the file referenced in database
589 if ($disable_exit == true) {
590 $f = fopen($url, "r");
591 $filetext = fread($f, filesize($url));
592 return $filetext;
594 header('Content-Description: File Transfer');
595 header('Content-Transfer-Encoding: binary');
596 header('Expires: 0');
597 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
598 header('Pragma: public');
599 $f = fopen($url, "r");
600 if ($doEncryption) {
601 $filetext = fread($f, filesize($url));
602 $ciphertext = $this->encrypt($filetext, $passphrase);
603 $tmpfilepath = $GLOBALS['temporary_files_dir'];
604 $tmpfilename = "/encrypted_".$d->get_url_file();
605 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
606 fwrite($tmpfile, $ciphertext);
607 fclose($tmpfile);
608 header('Content-Disposition: attachment; filename='.$tmpfilename);
609 header("Content-Type: application/octet-stream");
610 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
611 ob_clean();
612 flush();
613 readfile($tmpfilepath.$tmpfilename);
614 unlink($tmpfilepath.$tmpfilename);
615 } else {
616 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
617 header("Content-Type: " . $d->get_mimetype());
618 header("Content-Length: " . filesize($url));
619 fpassthru($f);
621 exit;
622 } else {
623 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
624 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
625 if ($couch_docid && $couch_revid) {
626 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
627 } else {
628 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
630 if ($disable_exit == true) {
631 return ;
633 header("Pragma: public");
634 header("Expires: 0");
635 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
636 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
637 header("Content-Type: image/jpeg");
638 header("Content-Length: " . filesize($url));
639 $f = fopen($url, "r");
640 fpassthru($f);
641 if ($couch_docid && $couch_revid) {
642 fclose($f);
643 unlink($url);
644 $url=str_replace("_converted.jpg", '.pdf', $url);
645 unlink($url);
647 exit;
652 function queue_action($patient_id = "")
654 $messages = $this->_tpl_vars['messages'];
655 $queue_files = array();
657 //see if the repository exists and it is a directory else error
658 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
659 $dir = opendir($this->_config['repository']);
660 //read each entry in the directory
661 while (($file = readdir($dir)) !== false) {
662 //concat the filename and path
663 $file = $this->_config['repository'] .$file;
664 $file_info = array();
665 //if the filename is a file get its info and put into a tmp array
666 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
667 $file_info['filename'] = basename_international($file);
668 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
669 $d = $this->Document->document_factory_url("file://" . $file);
670 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
671 $file_info['patient_id'] = $patient_match[1];
672 $file_info['document_id'] = $d->get_id();
673 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
675 //merge the tmp array into the larger array
676 $queue_files[] = $file_info;
679 closedir($dir);
680 } else {
681 $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";
685 $this->assign("queue_files", $queue_files);
686 $this->_last_node = null;
688 $menu = new HTML_TreeMenu();
690 //pass an empty array because we don't want the documents for each category showing up in this list box
691 $rnode = $this->_array_recurse($this->tree->tree, array());
692 $menu->addItem($rnode);
693 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
695 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
697 $this->assign("messages", nl2br($messages));
698 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
701 function queue_action_process()
703 if ($_POST['process'] != "true") {
704 return;
707 $messages = $this->_tpl_vars['messages'];
709 //build a category tree so we can have a list of category ids that are valid
710 $ct = new CategoryTree(1);
711 $categories = $ct->_id_name;
713 //see if there were and posted files and assign them
714 $files = null;
715 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
717 //loop through posted files
718 foreach ($files as $doc_id => $file) {
719 //only operate on files checked as active
720 if (!$file['active']) {
721 continue;
724 //run basic validation checks
725 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
726 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
727 continue;
730 //validate that the pod exists
731 $d = new Document($doc_id);
732 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
733 $result = $d->_db->Execute($sql);
735 if (!$result || $result->EOF) {
736 //patient id does not exist
737 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
738 continue;
741 //validate that the category id exists
742 if (!isset($categories[$file['category_id']])) {
743 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
744 continue;
747 //now do the work of moving the file
748 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
750 //see if the patient dir exists in the repository and create if not
751 if (!file_exists($new_path)) {
752 if (!mkdir($new_path, 0700)) {
753 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
754 continue;
758 //fname is the name of the file after it is moved
759 $fname = $file['name'];
761 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
762 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
763 if ($patient_match[1] == $file['patient_id']) {
764 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
767 //filenames should not have funny chars
768 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
770 //see if there is an existing file with the same name and rename as necessary
771 if (file_exists($new_path.$file['name'])) {
772 $messages .= "File with same name already exists at location: " . $new_path . "\n";
773 $fname = basename_international($this->_rename_file($new_path.$file['name']));
774 $messages .= "Current file name was changed to " . $fname ."\n";
777 //now move the file
778 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
779 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
780 $d->url = "file://" .$new_path.$fname;
781 $d->set_foreign_id($file['patient_id']);
782 $d->set_mimetype($mimetype);
783 $d->persist();
784 $d->populate();
786 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
787 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
788 $d->_db->Execute($sql);
790 } else {
791 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
794 $this->assign("messages", $messages);
795 $_POST['process'] = "";
798 function move_action_process($patient_id = "", $document_id)
800 if ($_POST['process'] != "true") {
801 return;
804 $new_category_id = $_POST['new_category_id'];
805 $new_patient_id = $_POST['new_patient_id'];
807 //move to new category
808 if (is_numeric($new_category_id) && is_numeric($document_id)) {
809 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
810 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
811 //echo $sql;
812 $this->tree->_db->Execute($sql);
815 //move to new patient
816 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
817 $d = new Document($document_id);
818 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
819 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
820 $result = $d->_db->Execute($sql);
822 if (!$result || $result->EOF) {
823 //patient id does not exist
824 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
825 } else {
826 $couchsavefailed = !$d->change_patient($new_patient_id);
828 $this->_state = false;
829 if (!$couchsavefailed) {
830 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
831 } else {
832 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
834 $this->assign("messages", $messages);
835 return $this->list_action($patient_id);
837 } //in this case return the document to the queue instead of moving it
838 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
839 $d = new Document($document_id);
840 $new_path = $this->_config['repository'];
841 $fname = $d->get_url_file();
843 //see if there is an existing file with the same name and rename as necessary
844 if (file_exists($new_path.$d->get_url_file())) {
845 $messages .= "File with same name already exists in the queue.\n";
846 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
847 $messages .= "Current file name was changed to " . $fname ."\n";
850 //now move the file
851 if (rename($d->get_url_filepath(), $new_path.$fname)) {
852 $d->url = "file://" .$new_path.$fname;
853 $d->set_foreign_id("");
854 $d->persist();
855 $d->persist();
856 $d->populate();
858 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
859 $d->_db->Execute($sql);
860 $messages .= "Document returned to queue successfully.\n";
861 } else {
862 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
865 $this->_state = false;
866 $this->assign("messages", $messages);
867 return $this->list_action($patient_id);
870 $this->_state = false;
871 $this->assign("messages", $messages);
872 return $this->view_action($patient_id, $document_id);
875 function validate_action_process($patient_id = "", $document_id)
878 $d = new Document($document_id);
879 if ($d->couch_docid && $d->couch_revid) {
880 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
881 $url = $file_path.$d->get_url();
882 $couch = new CouchDB();
883 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
884 $resp = $couch->retrieve_doc($data);
885 $content = $resp->data;
886 //--------Temporarily writing the file for calculating the hash--------//
887 //-----------Will be removed after calculating the hash value----------//
888 $temp_file = fopen($url, "w");
889 fwrite($temp_file, base64_decode($content));
890 fclose($temp_file);
891 } else {
892 $url = $d->get_url();
894 //strip url of protocol handler
895 $url = preg_replace("|^(.*)://|", "", $url);
897 //change full path to current webroot. this is for documents that may have
898 //been moved from a different filesystem and the full path in the database
899 //is not current. this is also for documents that may of been moved to
900 //different patients. Note that the path_depth is used to see how far down
901 //the path to go. For example, originally the path_depth was always 1, which
902 //only allowed things like documents/1/<file>, but now can have more structured
903 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
904 // etc.
905 // NOTE that $from_filename and basename($url) are the same thing
906 $from_all = explode("/", $url);
907 $from_filename = array_pop($from_all);
908 $from_pathname_array = array();
909 for ($i=0; $i<$d->get_path_depth(); $i++) {
910 $from_pathname_array[] = array_pop($from_all);
912 $from_pathname_array = array_reverse($from_pathname_array);
913 $from_pathname = implode("/", $from_pathname_array);
914 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
915 if (file_exists($temp_url)) {
916 $url = $temp_url;
919 if ($_POST['process'] != "true") {
920 die("process is '" . $_POST['process'] . "', expected 'true'");
921 return;
924 $d = new Document($document_id);
925 $current_hash = sha1_file($url);
926 $messages = xl('Current Hash').": ".$current_hash."<br>";
927 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
928 if ($d->get_hash() == '') {
929 $d->hash = $current_hash;
930 $d->persist();
931 $d->populate();
932 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
933 } else if ($current_hash != $d->get_hash()) {
934 $messages .= xl('Hash does not match. Data integrity has been compromised.');
935 } else {
936 $messages .= xl('Document passed integrity check.');
938 $this->_state = false;
939 $this->assign("messages", $messages);
940 if ($d->couch_docid && $d->couch_revid) {
941 //Removing the temporary file which is used to create the hash
942 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
944 return $this->view_action($patient_id, $document_id);
947 // Added by Rod for metadata update.
949 function update_action_process($patient_id = "", $document_id)
952 if ($_POST['process'] != "true") {
953 die("process is '" . $_POST['process'] . "', expected 'true'");
954 return;
957 $docdate = $_POST['docdate'];
958 $docname = $_POST['docname'];
959 $issue_id = $_POST['issue_id'];
961 if (is_numeric($document_id)) {
962 $messages = '';
963 $d = new Document($document_id);
964 $file_name = $d->get_url_file();
965 if ($docname != '' &&
966 $docname != $file_name ) {
967 // Ready to rename - check for relocation
968 $old_url = $this->_check_relocation($d->get_url());
969 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
970 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
971 if (rename($old_url, $new_url)) {
972 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
973 if (file_exists($old_url)) {
974 unlink($old_url);
976 $d->url = $new_url;
977 $d->persist();
978 $d->populate();
979 $messages .= xl('Document successfully renamed.')."<br>";
980 } else {
981 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
985 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
986 $docdate = "'$docdate'";
987 } else {
988 $docdate = "NULL";
990 if (!is_numeric($issue_id)) {
991 $issue_id = 0;
993 $couch_docid = $d->get_couch_docid();
994 $couch_revid = $d->get_couch_revid();
995 if ($couch_docid && $couch_revid) {
996 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
997 "list_id = '$issue_id' " .
998 "WHERE id = '$document_id'";
999 $this->tree->_db->Execute($sql);
1000 } else {
1001 $sql = "UPDATE documents SET docdate = $docdate, " .
1002 "list_id = '$issue_id' " .
1003 "WHERE id = '$document_id'";
1004 $this->tree->_db->Execute($sql);
1006 $messages .= xl('Document date and issue updated successfully') . "<br>";
1009 $this->_state = false;
1010 $this->assign("messages", $messages);
1011 return $this->view_action($patient_id, $document_id);
1014 function list_action($patient_id = "")
1016 $this->_last_node = null;
1017 $categories_list = $this->tree->_get_categories_array($patient_id);
1018 //print_r($categories_list);
1020 $menu = new HTML_TreeMenu();
1021 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1022 $menu->addItem($rnode);
1023 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1024 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1026 $this->assign("tree_html", $treeMenu->toHTML());
1028 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1031 /* This is a recursive function to rename a file to something that doesn't already exist.
1032 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1033 * at end) to ensure documents opened correctly by external browser viewers. If the
1034 * counter is at the end of the file, then will use it (to continue to work with older
1035 * files), however all new counters will be placed within filenames.
1037 * Modified to only deal with base file name when renaming, to avoid issues with directory
1038 * names with dots.
1040 function _rename_file($fname, $self = false)
1042 // Allow same routine for new file name check
1043 if (!file_exists($fname)) {
1044 return($fname);
1047 $path = dirname($fname);
1048 $file = basename_international($fname);
1050 $fparts = explode(".", $file);
1051 switch (count($fparts)) {
1052 case 1:
1053 // Has a single node (base file name). Create counter node with value 0
1054 $fparts[1] = '1';
1055 break;
1056 case 2:
1057 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1058 if (is_numeric($fparts[1])) {
1059 $fparts[1] += 1;
1060 } else {
1061 array_push($fparts, $fparts[1]);
1062 $fparts[1] = '1';
1064 break;
1065 default:
1066 // Multiple nodes
1067 $ix_end = count($fparts) - 1;
1068 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1069 // Switch old style to new and check again
1070 $wrk = $fparts[$ix_end - 1];
1071 $fparts[$ix_end - 1] = $fparts[$ix_end];
1072 $fparts[$ix_end] = $wrk;
1073 } else if (is_numeric($fparts[$ix_end - 1])) {
1074 $fparts[$ix_end - 1] += 1;
1075 } else {
1076 array_push($fparts, $fparts[$ix_end]);
1077 $fparts[$ix_end] = '1';
1079 break;
1082 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1084 if (file_exists($fname)) {
1085 return $this->_rename_file($fname, true);
1086 } else {
1087 return($fname);
1091 function &_array_recurse($array, $categories = array())
1093 if (!is_array($array)) {
1094 $array = array();
1096 $node = &$this->_last_node;
1097 $current_node = &$node;
1098 $expandedIcon = 'folder-expanded.gif';
1099 foreach ($array as $id => $ar) {
1100 $icon = 'folder.gif';
1101 if (is_array($ar) || !empty($id)) {
1102 if ($node == null) {
1103 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1104 $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));
1105 $this->_last_node = &$rnode;
1106 $node = &$rnode;
1107 $current_node = &$rnode;
1108 } else {
1109 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1110 $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)));
1111 $current_node = &$this->_last_node;
1114 $this->_array_recurse($ar, $categories);
1115 } else {
1116 if ($id === 0 && !empty($ar)) {
1117 $info = $this->tree->get_node_info($id);
1118 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1119 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1120 } else {
1121 //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
1122 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1123 if ($id !== 0 && is_object($node)) {
1124 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1125 $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)));
1130 // If there are documents in this document category, then add their
1131 // attributes to the current node.
1132 $icon = "file3.png";
1133 if (is_array($categories[$id])) {
1134 foreach ($categories[$id] as $doc) {
1135 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1136 // If user has no access then there will be no link.
1137 if (!acl_check_aco_spec($doc['aco_spec'])) {
1138 $link = '';
1140 if ($this->tree->get_node_name($id) == "CCR") {
1141 $current_node->addItem(new HTML_TreeNode(array(
1142 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1143 'link' => $link,
1144 'icon' => $icon,
1145 'expandedIcon' => $expandedIcon,
1146 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1147 )));
1148 } elseif ($this->tree->get_node_name($id) == "CCD") {
1149 $current_node->addItem(new HTML_TreeNode(array(
1150 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1151 'link' => $link,
1152 'icon' => $icon,
1153 'expandedIcon' => $expandedIcon,
1154 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1155 )));
1156 } else {
1157 $current_node->addItem(new HTML_TreeNode(array(
1158 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1159 'link' => $link,
1160 'icon' => $icon,
1161 'expandedIcon' => $expandedIcon
1162 )));
1167 return $node;
1170 //function for logging the errors in writing file to CouchDB/Hard Disk
1171 function document_upload_download_log($patientid, $content)
1173 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1174 $log_file = 'log.txt';
1175 if (!is_dir($log_path)) {
1176 mkdir($log_path, 0777, true);
1178 $LOG = fopen($log_path.$log_file, 'a');
1179 fwrite($LOG, $content);
1180 fclose($LOG);
1183 function document_send($email, $body, $attfile, $pname)
1185 if (empty($email)) {
1186 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1187 return;
1190 $desc = "Please check the attached patient document.\n Content:".attr($body);
1191 $mail = new MyMailer();
1192 $from_name = $GLOBALS["practice_return_email_path"];
1193 $from = $GLOBALS["practice_return_email_path"];
1194 $mail->AddReplyTo($from, $from_name);
1195 $mail->SetFrom($from, $from);
1196 $to = $email ;
1197 $to_name =$email;
1198 $mail->AddAddress($to, $to_name);
1199 $subject = "Patient documents";
1200 $mail->Subject = $subject;
1201 $mail->Body = $desc;
1202 $mail->AddAttachment($attfile);
1203 if ($mail->Send()) {
1204 $retstatus = "email_sent";
1205 } else {
1206 $email_status = $mail->ErrorInfo;
1207 //echo "EMAIL ERROR: ".$email_status;
1208 $retstatus = "email_fail";
1212 //place to hold optional code
1213 //$first_node = array_keys($t->tree);
1214 //$first_node = $first_node[0];
1215 //$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')"));
1217 //$this->_last_node = &$node1;
1219 // Function to tag a document to an encounter.
1220 function tag_action_process($patient_id = "", $document_id)
1222 if ($_POST['process'] != "true") {
1223 die("process is '" . text($_POST['process']) . "', expected 'true'");
1224 return;
1227 // Create Encounter and Tag it.
1228 $event_date = date('Y-m-d H:i:s');
1229 $encounter_id = $_POST['encounter_id'];
1230 $encounter_check = $_POST['encounter_check'];
1231 $visit_category_id = $_POST['visit_category_id'];
1233 if (is_numeric($document_id)) {
1234 $messages = '';
1235 $d = new Document($document_id);
1236 $file_name = $d->get_url_file();
1237 if (!is_numeric($encounter_id)) {
1238 $encounter_id = 0;
1241 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1242 if ($encounter_check) {
1243 $provider_id = $_SESSION['authUserID'] ;
1245 // Get the logged in user's facility
1246 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1247 $username = $facilityRow['username'];
1248 $facility = $facilityRow['facility'];
1249 $facility_id = $facilityRow['facility_id'];
1250 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1251 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1252 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1254 $conn = $GLOBALS['adodb']['db'];
1255 $encounter = $conn->GenID("sequences");
1256 $query = "INSERT INTO form_encounter SET
1257 date = ?,
1258 reason = ?,
1259 facility = ?,
1260 sensitivity = 'normal',
1261 pc_catid = ?,
1262 facility_id = ?,
1263 billing_facility = ?,
1264 provider_id = ?,
1265 pid = ?,
1266 encounter = ?";
1267 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1268 $formID = sqlInsert($query, $bindArray);
1269 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1270 $d->set_encounter_id($encounter);
1271 $this->image_result_indication($d->id, $encounter);
1272 } else {
1273 $d->set_encounter_id($encounter_id);
1274 $this->image_result_indication($d->id, $encounter_id);
1276 $d->set_encounter_check($encounter_check);
1277 $d->persist();
1279 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1282 $this->_state = false;
1283 $this->assign("messages", $messages);
1285 return $this->view_action($patient_id, $document_id);
1288 function image_procedure_action($patient_id = "", $document_id)
1291 $img_procedure_id = $_POST['image_procedure_id'];
1292 $proc_code = $_POST['procedure_code'];
1294 if (is_numeric($document_id)) {
1295 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1296 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1297 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1298 if ($img_report_id == 0) {
1299 $report_date = date('Y-m-d H:i:s');
1300 $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));
1303 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1304 if (empty($img_result)) {
1305 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));
1308 $this->image_result_indication($document_id, 0, $img_procedure_id);
1310 return $this->view_action($patient_id, $document_id);
1313 function clear_procedure_tag_action($patient_id = "", $document_id)
1315 if (is_numeric($document_id)) {
1316 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1318 return $this->view_action($patient_id, $document_id);
1321 function get_mapped_procedure($document_id)
1323 $map = array();
1324 if (is_numeric($document_id)) {
1325 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1326 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1327 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1328 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1329 where pres.document_id = ?", array($document_id));
1331 return $map;
1334 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1336 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1337 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1339 if ($encounter != 0) {
1340 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1341 } else if ($image_procedure_id != 0) {
1342 $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));
1343 } else {
1344 $ep = array('assigned_to' => $_SESSION['authUser']);
1347 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1348 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1349 setGpRelation(1, $doc_id, 6, $noteid);
1352 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1353 * Also usable for documents that may of been moved to different patients.
1355 * @param string $url - Current url string from database.
1356 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1357 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1359 * @return string
1361 function _check_relocation($url, $new_pid = null, $new_name = null)
1363 //strip url of protocol handler
1364 $url = preg_replace("|^(.*)://|", "", $url);
1365 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1366 while (current($fsnodes) != "documents") {
1367 array_shift($fsnodes);
1369 if ($new_pid) {
1370 $fsnodes[1] = $new_pid;
1372 if ($new_name) {
1373 $fsnodes[count($fsnodes)-1] = $new_name;
1375 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1376 // Make sure the url is available after corrections
1377 if ($new_pid || $new_name) {
1378 $url = $this->_rename_file($url);
1380 //Add full path and remaining nodes
1381 return $url;
1384 //clear encounter tag function
1385 function clear_encounter_tag_action($patient_id = "", $document_id)
1387 if (is_numeric($document_id)) {
1388 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1390 return $this->view_action($patient_id, $document_id);