document notes
[openemr.git] / controllers / C_Document.class.php
blobbed3c298f4d4e5bd552e6a4ec061f206d98d4850
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 $notes = $d->get_notes();
296 $this->assign("file", $d);
297 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
298 $this->assign("NOTE_ACTION", $this->_link("note"));
299 $this->assign("MOVE_ACTION", $this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
300 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption']);
302 // Added by Rod to support document delete:
303 $delete_string = '';
304 if (acl_check('admin', 'super')) {
305 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
306 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
308 $this->assign("delete_string", $delete_string);
309 $this->assign("REFRESH_ACTION", $this->_link("list"));
311 $this->assign("VALIDATE_ACTION", $this->_link("validate") .
312 "document_id=" . $d->get_id() . "&process=true");
314 // Added by Rod to support document date update:
315 $this->assign("DOCDATE", $d->get_docdate());
316 $this->assign("UPDATE_ACTION", $this->_link("update") .
317 "document_id=" . $d->get_id() . "&process=true");
319 // Added by Rod to support document issue update:
320 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
321 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
322 "pid = ? " . // AND enddate IS NULL " .
323 "ORDER BY type, begdate", array($patient_id));
324 while ($irow = sqlFetchArray($ires)) {
325 $desc = $irow['type'];
326 if ($ISSUE_TYPES[$desc]) {
327 $desc = $ISSUE_TYPES[$desc][2];
329 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
330 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
331 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
333 $this->assign("ISSUES_LIST", $issues_options);
335 // For tagging to encounter
336 // Populate the dropdown with patient's encounter list
337 $this->assign("TAG_ACTION", $this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
338 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
339 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
340 "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));
341 if (sqlNumRows($result_docs) > 0) {
342 while ($row_result_docs = sqlFetchArray($result_docs)) {
343 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
344 $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>";
347 $this->assign("ENC_LIST", $encOptions);
349 //clear encounter tag
350 if ($d->get_encounter_id() != 0) {
351 $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
352 } else {
353 $this->assign('clear_encounter_tag', 'javascript:void(0)');
356 //Populate the dropdown with category list
357 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
358 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
359 while ($crow = sqlFetchArray($cres)) {
360 $catid = $crow['pc_catid'];
361 if ($catid < 9 && $catid != 5) {
362 continue; // Applying same logic as in new encounter page.
364 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
366 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
368 $this->assign("notes", $notes);
370 $this->assign("IMG_PROCEDURE_TAG_ACTION", $this->_link("image_procedure") . "document_id=" . $d->get_id());
371 // Populate the dropdown with image procedure order list
372 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
373 $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));
374 $mapping = $this->get_mapped_procedure($d->get_id());
375 if (sqlNumRows($imgOrders) > 0) {
376 while ($row = sqlFetchArray($imgOrders)) {
377 $sel_proc = '';
378 if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {
379 $sel_proc = 'selected';
381 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
385 $this->assign('IMAGE_PROCEDURE_LIST', $imgOptions);
387 $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
389 $this->_last_node = null;
391 $menu = new HTML_TreeMenu();
393 //pass an empty array because we don't want the documents for each category showing up in this list box
394 $rnode = $this->_array_recurse($this->tree->tree, array());
395 $menu->addItem($rnode);
396 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
398 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
400 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
401 $this->assign("activity", $activity);
403 return $this->list_action($patient_id);
406 function encrypt($plaintext, $key, $cypher = 'tripledes', $mode = 'cfb')
408 $td = mcrypt_module_open($cypher, '', $mode, '');
409 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
410 mcrypt_generic_init($td, $key, $iv);
411 $crypttext = mcrypt_generic($td, $plaintext);
412 mcrypt_generic_deinit($td);
413 return $iv.$crypttext;
416 function decrypt($crypttext, $key, $cypher = 'tripledes', $mode = 'cfb')
418 $plaintext = '';
419 $td = mcrypt_module_open($cypher, '', $mode, '');
420 $ivsize = mcrypt_enc_get_iv_size($td) ;
421 $iv = substr($crypttext, 0, $ivsize);
422 $crypttext = substr($crypttext, $ivsize);
423 if ($iv) {
424 mcrypt_generic_init($td, $key, $iv);
425 $plaintext = mdecrypt_generic($td, $crypttext);
427 return $plaintext;
431 * Retrieve file from hard disk / CouchDB.
432 * In case that file isn't download this function will return thumbnail image (if exist).
433 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
434 * @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.
435 * */
436 function retrieve_action($patient_id = "", $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = "normal")
438 $encrypted = $_POST['encrypted'];
439 $passphrase = $_POST['passphrase'];
440 $doEncryption = false;
441 if (!$GLOBALS['hide_document_encryption'] &&
442 $encrypted == "true" &&
443 $passphrase ) {
444 $doEncryption = true;
447 //controller function ruins booleans, so need to manually re-convert to booleans
448 if ($as_file == "true") {
449 $as_file=true;
450 } else if ($as_file == "false") {
451 $as_file=false;
453 if ($original_file == "true") {
454 $original_file=true;
455 } else if ($original_file == "false") {
456 $original_file=false;
458 if ($disable_exit == "true") {
459 $disable_exit=true;
460 } else if ($disable_exit == "false") {
461 $disable_exit=false;
463 if ($show_original == "true") {
464 $show_original=true;
465 } else if ($show_original == "false") {
466 $show_original=false;
469 switch ($context) {
470 case "patient_picture":
471 $this->patientService->setPid($patient_id);
472 $document_id = $this->patientService->getPatientPictureDocumentId();
473 break;
476 $d = new Document($document_id);
477 $url = $d->get_url();
478 $th_url = $d->get_thumb_url();
480 $storagemethod = $d->get_storagemethod();
481 $couch_docid = $d->get_couch_docid();
482 $couch_revid = $d->get_couch_revid();
484 if ($couch_docid && $couch_revid && $original_file) {
485 $couch = new CouchDB();
486 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
487 $resp = $couch->retrieve_doc($data);
488 //Take thumbnail file when is not null and file is presented online
489 if (!$as_file && !is_null($th_url) && !$show_original) {
490 $content = $resp->th_data;
491 } else {
492 $content = $resp->data;
494 if ($content=='' && $GLOBALS['couchdb_log']==1) {
495 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
496 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
497 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
498 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
499 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
500 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
501 $this->document_upload_download_log($d->get_foreign_id(), $log_content);
502 die(xl("File retrieval from CouchDB failed"));
504 if ($disable_exit == true) {
505 return base64_decode($content);
507 header('Content-Description: File Transfer');
508 header('Content-Transfer-Encoding: binary');
509 header('Expires: 0');
510 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
511 header('Pragma: public');
512 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
513 $fh = fopen($tmpcouchpath, "w");
514 fwrite($fh, base64_decode($content));
515 fclose($fh);
516 $f = fopen($tmpcouchpath, "r");
517 if ($doEncryption) {
518 $filetext = fread($f, filesize($tmpcouchpath));
519 $ciphertext = $this->encrypt($filetext, $passphrase);
520 $tmpfilepath = $GLOBALS['temporary_files_dir'];
521 $tmpfilename = "/encrypted_".$d->get_url_file();
522 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
523 fwrite($tmpfile, $ciphertext);
524 fclose($tmpfile);
525 header('Content-Disposition: attachment; filename='.$tmpfilename);
526 header("Content-Type: application/octet-stream");
527 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
528 ob_clean();
529 flush();
530 readfile($tmpfilepath.$tmpfilename);
531 unlink($tmpfilepath.$tmpfilename);
532 } else {
533 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
534 header("Content-Type: " . $d->get_mimetype());
535 header("Content-Length: " . filesize($tmpcouchpath));
536 fpassthru($f);
538 fclose($f);
539 if ($content!='') {
540 unlink($tmpcouchpath);
542 exit;//exits only if file download from CouchDB is successfull.
545 //Take thumbnail file when is not null and file is presented online
546 if (!$as_file && !is_null($th_url) && !$show_original) {
547 $url = $th_url;
550 //strip url of protocol handler
551 $url = preg_replace("|^(.*)://|", "", $url);
553 //change full path to current webroot. this is for documents that may have
554 //been moved from a different filesystem and the full path in the database
555 //is not current. this is also for documents that may of been moved to
556 //different patients. Note that the path_depth is used to see how far down
557 //the path to go. For example, originally the path_depth was always 1, which
558 //only allowed things like documents/1/<file>, but now can have more structured
559 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
560 // etc.
561 // NOTE that $from_filename and basename($url) are the same thing
562 $from_all = explode("/", $url);
563 $from_filename = array_pop($from_all);
564 $from_pathname_array = array();
565 for ($i=0; $i<$d->get_path_depth(); $i++) {
566 $from_pathname_array[] = array_pop($from_all);
568 $from_pathname_array = array_reverse($from_pathname_array);
569 $from_pathname = implode("/", $from_pathname_array);
570 if ($couch_docid && $couch_revid) {
571 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
572 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
573 } else {
574 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
577 if (file_exists($temp_url)) {
578 $url = $temp_url;
582 if (!file_exists($url)) {
583 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;
584 } else {
585 if ($original_file) {
586 //normal case when serving the file referenced in database
587 if ($disable_exit == true) {
588 $f = fopen($url, "r");
589 $filetext = fread($f, filesize($url));
590 return $filetext;
592 header('Content-Description: File Transfer');
593 header('Content-Transfer-Encoding: binary');
594 header('Expires: 0');
595 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
596 header('Pragma: public');
597 $f = fopen($url, "r");
598 if ($doEncryption) {
599 $filetext = fread($f, filesize($url));
600 $ciphertext = $this->encrypt($filetext, $passphrase);
601 $tmpfilepath = $GLOBALS['temporary_files_dir'];
602 $tmpfilename = "/encrypted_".$d->get_url_file();
603 $tmpfile = fopen($tmpfilepath.$tmpfilename, "w+");
604 fwrite($tmpfile, $ciphertext);
605 fclose($tmpfile);
606 header('Content-Disposition: attachment; filename='.$tmpfilename);
607 header("Content-Type: application/octet-stream");
608 header("Content-Length: " . filesize($tmpfilepath.$tmpfilename));
609 ob_clean();
610 flush();
611 readfile($tmpfilepath.$tmpfilename);
612 unlink($tmpfilepath.$tmpfilename);
613 } else {
614 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
615 header("Content-Type: " . $d->get_mimetype());
616 header("Content-Length: " . filesize($url));
617 fpassthru($f);
619 exit;
620 } else {
621 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
622 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
623 if ($couch_docid && $couch_revid) {
624 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
625 } else {
626 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
628 if ($disable_exit == true) {
629 return ;
631 header("Pragma: public");
632 header("Expires: 0");
633 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
634 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
635 header("Content-Type: image/jpeg");
636 header("Content-Length: " . filesize($url));
637 $f = fopen($url, "r");
638 fpassthru($f);
639 if ($couch_docid && $couch_revid) {
640 fclose($f);
641 unlink($url);
642 $url=str_replace("_converted.jpg", '.pdf', $url);
643 unlink($url);
645 exit;
650 function queue_action($patient_id = "")
652 $messages = $this->_tpl_vars['messages'];
653 $queue_files = array();
655 //see if the repository exists and it is a directory else error
656 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
657 $dir = opendir($this->_config['repository']);
658 //read each entry in the directory
659 while (($file = readdir($dir)) !== false) {
660 //concat the filename and path
661 $file = $this->_config['repository'] .$file;
662 $file_info = array();
663 //if the filename is a file get its info and put into a tmp array
664 if (is_file($file) && strpos(basename_international($file), ".") !== 0) {
665 $file_info['filename'] = basename_international($file);
666 $file_info['mtime'] = date("m/d/Y H:i:s", filemtime($file));
667 $d = $this->Document->document_factory_url("file://" . $file);
668 preg_match("/^([0-9]+)_/", basename_international($file), $patient_match);
669 $file_info['patient_id'] = $patient_match[1];
670 $file_info['document_id'] = $d->get_id();
671 $file_info['web_path'] = $this->_link("retrieve", true) . "document_id=" . $d->get_id() . "&";
673 //merge the tmp array into the larger array
674 $queue_files[] = $file_info;
677 closedir($dir);
678 } else {
679 $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";
683 $this->assign("queue_files", $queue_files);
684 $this->_last_node = null;
686 $menu = new HTML_TreeMenu();
688 //pass an empty array because we don't want the documents for each category showing up in this list box
689 $rnode = $this->_array_recurse($this->tree->tree, array());
690 $menu->addItem($rnode);
691 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
693 $this->assign("tree_html_listbox", $treeMenu_listbox->toHTML());
695 $this->assign("messages", nl2br($messages));
696 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
699 function queue_action_process()
701 if ($_POST['process'] != "true") {
702 return;
705 $messages = $this->_tpl_vars['messages'];
707 //build a category tree so we can have a list of category ids that are valid
708 $ct = new CategoryTree(1);
709 $categories = $ct->_id_name;
711 //see if there were and posted files and assign them
712 $files = null;
713 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
715 //loop through posted files
716 foreach ($files as $doc_id => $file) {
717 //only operate on files checked as active
718 if (!$file['active']) {
719 continue;
722 //run basic validation checks
723 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
724 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
725 continue;
728 //validate that the pod exists
729 $d = new Document($doc_id);
730 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
731 $result = $d->_db->Execute($sql);
733 if (!$result || $result->EOF) {
734 //patient id does not exist
735 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
736 continue;
739 //validate that the category id exists
740 if (!isset($categories[$file['category_id']])) {
741 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
742 continue;
745 //now do the work of moving the file
746 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
748 //see if the patient dir exists in the repository and create if not
749 if (!file_exists($new_path)) {
750 if (!mkdir($new_path, 0700)) {
751 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
752 continue;
756 //fname is the name of the file after it is moved
757 $fname = $file['name'];
759 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
760 preg_match("/^([0-9]+)_/", basename_international($fname), $patient_match);
761 if ($patient_match[1] == $file['patient_id']) {
762 $fname = preg_replace("/^([0-9]+)_/", "", $fname);
765 //filenames should not have funny chars
766 $fname = preg_replace("/[^a-zA-Z0-9_.]/", "_", $fname);
768 //see if there is an existing file with the same name and rename as necessary
769 if (file_exists($new_path.$file['name'])) {
770 $messages .= "File with same name already exists at location: " . $new_path . "\n";
771 $fname = basename_international($this->_rename_file($new_path.$file['name']));
772 $messages .= "Current file name was changed to " . $fname ."\n";
775 //now move the file
776 if (rename($this->_config['repository'].$file['name'], $new_path.$fname)) {
777 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
778 $d->url = "file://" .$new_path.$fname;
779 $d->set_foreign_id($file['patient_id']);
780 $d->set_mimetype($mimetype);
781 $d->persist();
782 $d->populate();
784 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
785 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
786 $d->_db->Execute($sql);
788 } else {
789 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
792 $this->assign("messages", $messages);
793 $_POST['process'] = "";
796 function move_action_process($patient_id = "", $document_id)
798 if ($_POST['process'] != "true") {
799 return;
802 $new_category_id = $_POST['new_category_id'];
803 $new_patient_id = $_POST['new_patient_id'];
805 //move to new category
806 if (is_numeric($new_category_id) && is_numeric($document_id)) {
807 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
808 $messages .= xl('Document moved to new category', '', '', ' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\' ') . "\n";
809 //echo $sql;
810 $this->tree->_db->Execute($sql);
813 //move to new patient
814 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
815 $d = new Document($document_id);
816 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
817 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
818 $result = $d->_db->Execute($sql);
820 if (!$result || $result->EOF) {
821 //patient id does not exist
822 $messages .= xl('Document could not be moved to patient id', '', '', ' \'') . $new_patient_id . xl('because that id does not exist.', '', '\' ') . "\n";
823 } else {
824 $couchsavefailed = !$d->change_patient($new_patient_id);
826 $this->_state = false;
827 if (!$couchsavefailed) {
828 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('successfully.', '', '\' ') . "\n";
829 } else {
830 $messages .= xl('Document moved to patient id', '', '', ' \'') . $new_patient_id . xl('Failed.', '', '\' ') . "\n";
832 $this->assign("messages", $messages);
833 return $this->list_action($patient_id);
835 } //in this case return the document to the queue instead of moving it
836 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
837 $d = new Document($document_id);
838 $new_path = $this->_config['repository'];
839 $fname = $d->get_url_file();
841 //see if there is an existing file with the same name and rename as necessary
842 if (file_exists($new_path.$d->get_url_file())) {
843 $messages .= "File with same name already exists in the queue.\n";
844 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
845 $messages .= "Current file name was changed to " . $fname ."\n";
848 //now move the file
849 if (rename($d->get_url_filepath(), $new_path.$fname)) {
850 $d->url = "file://" .$new_path.$fname;
851 $d->set_foreign_id("");
852 $d->persist();
853 $d->persist();
854 $d->populate();
856 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
857 $d->_db->Execute($sql);
858 $messages .= "Document returned to queue successfully.\n";
859 } else {
860 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
863 $this->_state = false;
864 $this->assign("messages", $messages);
865 return $this->list_action($patient_id);
868 $this->_state = false;
869 $this->assign("messages", $messages);
870 return $this->view_action($patient_id, $document_id);
873 function validate_action_process($patient_id = "", $document_id)
876 $d = new Document($document_id);
877 if ($d->couch_docid && $d->couch_revid) {
878 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
879 $url = $file_path.$d->get_url();
880 $couch = new CouchDB();
881 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
882 $resp = $couch->retrieve_doc($data);
883 $content = $resp->data;
884 //--------Temporarily writing the file for calculating the hash--------//
885 //-----------Will be removed after calculating the hash value----------//
886 $temp_file = fopen($url, "w");
887 fwrite($temp_file, base64_decode($content));
888 fclose($temp_file);
889 } else {
890 $url = $d->get_url();
892 //strip url of protocol handler
893 $url = preg_replace("|^(.*)://|", "", $url);
895 //change full path to current webroot. this is for documents that may have
896 //been moved from a different filesystem and the full path in the database
897 //is not current. this is also for documents that may of been moved to
898 //different patients. Note that the path_depth is used to see how far down
899 //the path to go. For example, originally the path_depth was always 1, which
900 //only allowed things like documents/1/<file>, but now can have more structured
901 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
902 // etc.
903 // NOTE that $from_filename and basename($url) are the same thing
904 $from_all = explode("/", $url);
905 $from_filename = array_pop($from_all);
906 $from_pathname_array = array();
907 for ($i=0; $i<$d->get_path_depth(); $i++) {
908 $from_pathname_array[] = array_pop($from_all);
910 $from_pathname_array = array_reverse($from_pathname_array);
911 $from_pathname = implode("/", $from_pathname_array);
912 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
913 if (file_exists($temp_url)) {
914 $url = $temp_url;
917 if ($_POST['process'] != "true") {
918 die("process is '" . $_POST['process'] . "', expected 'true'");
919 return;
922 $d = new Document($document_id);
923 $current_hash = sha1_file($url);
924 $messages = xl('Current Hash').": ".$current_hash."<br>";
925 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
926 if ($d->get_hash() == '') {
927 $d->hash = $current_hash;
928 $d->persist();
929 $d->populate();
930 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
931 } else if ($current_hash != $d->get_hash()) {
932 $messages .= xl('Hash does not match. Data integrity has been compromised.');
933 } else {
934 $messages .= xl('Document passed integrity check.');
936 $this->_state = false;
937 $this->assign("messages", $messages);
938 if ($d->couch_docid && $d->couch_revid) {
939 //Removing the temporary file which is used to create the hash
940 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
942 return $this->view_action($patient_id, $document_id);
945 // Added by Rod for metadata update.
947 function update_action_process($patient_id = "", $document_id)
950 if ($_POST['process'] != "true") {
951 die("process is '" . $_POST['process'] . "', expected 'true'");
952 return;
955 $docdate = $_POST['docdate'];
956 $docname = $_POST['docname'];
957 $issue_id = $_POST['issue_id'];
959 if (is_numeric($document_id)) {
960 $messages = '';
961 $d = new Document($document_id);
962 $file_name = $d->get_url_file();
963 if ($docname != '' &&
964 $docname != $file_name ) {
965 // Ready to rename - check for relocation
966 $old_url = $this->_check_relocation($d->get_url());
967 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
968 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
969 if (rename($old_url, $new_url)) {
970 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
971 if (file_exists($old_url)) {
972 unlink($old_url);
974 $d->url = $new_url;
975 $d->persist();
976 $d->populate();
977 $messages .= xl('Document successfully renamed.')."<br>";
978 } else {
979 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
983 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
984 $docdate = "'$docdate'";
985 } else {
986 $docdate = "NULL";
988 if (!is_numeric($issue_id)) {
989 $issue_id = 0;
991 $couch_docid = $d->get_couch_docid();
992 $couch_revid = $d->get_couch_revid();
993 if ($couch_docid && $couch_revid) {
994 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
995 "list_id = '$issue_id' " .
996 "WHERE id = '$document_id'";
997 $this->tree->_db->Execute($sql);
998 } else {
999 $sql = "UPDATE documents SET docdate = $docdate, " .
1000 "list_id = '$issue_id' " .
1001 "WHERE id = '$document_id'";
1002 $this->tree->_db->Execute($sql);
1004 $messages .= xl('Document date and issue updated successfully') . "<br>";
1007 $this->_state = false;
1008 $this->assign("messages", $messages);
1009 return $this->view_action($patient_id, $document_id);
1012 function list_action($patient_id = "")
1014 $this->_last_node = null;
1015 $categories_list = $this->tree->_get_categories_array($patient_id);
1016 //print_r($categories_list);
1018 $menu = new HTML_TreeMenu();
1019 $rnode = $this->_array_recurse($this->tree->tree, $categories_list);
1020 $menu->addItem($rnode);
1021 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1022 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1024 $this->assign("tree_html", $treeMenu->toHTML());
1026 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1029 /* This is a recursive function to rename a file to something that doesn't already exist.
1030 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1031 * at end) to ensure documents opened correctly by external browser viewers. If the
1032 * counter is at the end of the file, then will use it (to continue to work with older
1033 * files), however all new counters will be placed within filenames.
1035 * Modified to only deal with base file name when renaming, to avoid issues with directory
1036 * names with dots.
1038 function _rename_file($fname, $self = false)
1040 // Allow same routine for new file name check
1041 if (!file_exists($fname)) {
1042 return($fname);
1045 $path = dirname($fname);
1046 $file = basename_international($fname);
1048 $fparts = explode(".", $file);
1049 switch (count($fparts)) {
1050 case 1:
1051 // Has a single node (base file name). Create counter node with value 0
1052 $fparts[1] = '1';
1053 break;
1054 case 2:
1055 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1056 if (is_numeric($fparts[1])) {
1057 $fparts[1] += 1;
1058 } else {
1059 array_push($fparts, $fparts[1]);
1060 $fparts[1] = '1';
1062 break;
1063 default:
1064 // Multiple nodes
1065 $ix_end = count($fparts) - 1;
1066 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1067 // Switch old style to new and check again
1068 $wrk = $fparts[$ix_end - 1];
1069 $fparts[$ix_end - 1] = $fparts[$ix_end];
1070 $fparts[$ix_end] = $wrk;
1071 } else if (is_numeric($fparts[$ix_end - 1])) {
1072 $fparts[$ix_end - 1] += 1;
1073 } else {
1074 array_push($fparts, $fparts[$ix_end]);
1075 $fparts[$ix_end] = '1';
1077 break;
1080 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1082 if (file_exists($fname)) {
1083 return $this->_rename_file($fname, true);
1084 } else {
1085 return($fname);
1089 function &_array_recurse($array, $categories = array())
1091 if (!is_array($array)) {
1092 $array = array();
1094 $node = &$this->_last_node;
1095 $current_node = &$node;
1096 $expandedIcon = 'folder-expanded.gif';
1097 foreach ($array as $id => $ar) {
1098 $icon = 'folder.gif';
1099 if (is_array($ar) || !empty($id)) {
1100 if ($node == null) {
1101 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1102 $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));
1103 $this->_last_node = &$rnode;
1104 $node = &$rnode;
1105 $current_node = &$rnode;
1106 } else {
1107 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1108 $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)));
1109 $current_node = &$this->_last_node;
1112 $this->_array_recurse($ar, $categories);
1113 } else {
1114 if ($id === 0 && !empty($ar)) {
1115 $info = $this->tree->get_node_info($id);
1116 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1117 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1118 } else {
1119 //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
1120 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1121 if ($id !== 0 && is_object($node)) {
1122 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1123 $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)));
1128 // If there are documents in this document category, then add their
1129 // attributes to the current node.
1130 $icon = "file3.png";
1131 if (is_array($categories[$id])) {
1132 foreach ($categories[$id] as $doc) {
1133 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1134 // If user has no access then there will be no link.
1135 if (!acl_check_aco_spec($doc['aco_spec'])) {
1136 $link = '';
1138 if ($this->tree->get_node_name($id) == "CCR") {
1139 $current_node->addItem(new HTML_TreeNode(array(
1140 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1141 'link' => $link,
1142 'icon' => $icon,
1143 'expandedIcon' => $expandedIcon,
1144 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1145 )));
1146 } elseif ($this->tree->get_node_name($id) == "CCD") {
1147 $current_node->addItem(new HTML_TreeNode(array(
1148 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1149 'link' => $link,
1150 'icon' => $icon,
1151 'expandedIcon' => $expandedIcon,
1152 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1153 )));
1154 } else {
1155 $current_node->addItem(new HTML_TreeNode(array(
1156 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1157 'link' => $link,
1158 'icon' => $icon,
1159 'expandedIcon' => $expandedIcon
1160 )));
1165 return $node;
1168 //function for logging the errors in writing file to CouchDB/Hard Disk
1169 function document_upload_download_log($patientid, $content)
1171 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1172 $log_file = 'log.txt';
1173 if (!is_dir($log_path)) {
1174 mkdir($log_path, 0777, true);
1176 $LOG = fopen($log_path.$log_file, 'a');
1177 fwrite($LOG, $content);
1178 fclose($LOG);
1181 function document_send($email, $body, $attfile, $pname)
1183 if (empty($email)) {
1184 $this->assign("process_result", "Email could not be sent, the address supplied: '$email' was empty or invalid.");
1185 return;
1188 $desc = "Please check the attached patient document.\n Content:".attr($body);
1189 $mail = new MyMailer();
1190 $from_name = $GLOBALS["practice_return_email_path"];
1191 $from = $GLOBALS["practice_return_email_path"];
1192 $mail->AddReplyTo($from, $from_name);
1193 $mail->SetFrom($from, $from);
1194 $to = $email ;
1195 $to_name =$email;
1196 $mail->AddAddress($to, $to_name);
1197 $subject = "Patient documents";
1198 $mail->Subject = $subject;
1199 $mail->Body = $desc;
1200 $mail->AddAttachment($attfile);
1201 if ($mail->Send()) {
1202 $retstatus = "email_sent";
1203 } else {
1204 $email_status = $mail->ErrorInfo;
1205 //echo "EMAIL ERROR: ".$email_status;
1206 $retstatus = "email_fail";
1210 //place to hold optional code
1211 //$first_node = array_keys($t->tree);
1212 //$first_node = $first_node[0];
1213 //$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')"));
1215 //$this->_last_node = &$node1;
1217 // Function to tag a document to an encounter.
1218 function tag_action_process($patient_id = "", $document_id)
1220 if ($_POST['process'] != "true") {
1221 die("process is '" . text($_POST['process']) . "', expected 'true'");
1222 return;
1225 // Create Encounter and Tag it.
1226 $event_date = date('Y-m-d H:i:s');
1227 $encounter_id = $_POST['encounter_id'];
1228 $encounter_check = $_POST['encounter_check'];
1229 $visit_category_id = $_POST['visit_category_id'];
1231 if (is_numeric($document_id)) {
1232 $messages = '';
1233 $d = new Document($document_id);
1234 $file_name = $d->get_url_file();
1235 if (!is_numeric($encounter_id)) {
1236 $encounter_id = 0;
1239 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1240 if ($encounter_check) {
1241 $provider_id = $_SESSION['authUserID'] ;
1243 // Get the logged in user's facility
1244 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1245 $username = $facilityRow['username'];
1246 $facility = $facilityRow['facility'];
1247 $facility_id = $facilityRow['facility_id'];
1248 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1249 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1250 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1252 $conn = $GLOBALS['adodb']['db'];
1253 $encounter = $conn->GenID("sequences");
1254 $query = "INSERT INTO form_encounter SET
1255 date = ?,
1256 reason = ?,
1257 facility = ?,
1258 sensitivity = 'normal',
1259 pc_catid = ?,
1260 facility_id = ?,
1261 billing_facility = ?,
1262 provider_id = ?,
1263 pid = ?,
1264 encounter = ?";
1265 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1266 $formID = sqlInsert($query, $bindArray);
1267 addForm($encounter, "New Patient Encounter", $formID, "newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username);
1268 $d->set_encounter_id($encounter);
1269 $this->image_result_indication($d->id, $encounter);
1270 } else {
1271 $d->set_encounter_id($encounter_id);
1272 $this->image_result_indication($d->id, $encounter_id);
1274 $d->set_encounter_check($encounter_check);
1275 $d->persist();
1277 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1280 $this->_state = false;
1281 $this->assign("messages", $messages);
1283 return $this->view_action($patient_id, $document_id);
1286 function image_procedure_action($patient_id = "", $document_id)
1289 $img_procedure_id = $_POST['image_procedure_id'];
1290 $proc_code = $_POST['procedure_code'];
1292 if (is_numeric($document_id)) {
1293 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ", array($img_procedure_id,$proc_code));
1294 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ", array($img_procedure_id,$img_order['procedure_order_seq']));
1295 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1296 if ($img_report_id == 0) {
1297 $report_date = date('Y-m-d H:i:s');
1298 $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));
1301 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?", array($img_report_id,$document_id));
1302 if (empty($img_result)) {
1303 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));
1306 $this->image_result_indication($document_id, 0, $img_procedure_id);
1308 return $this->view_action($patient_id, $document_id);
1311 function clear_procedure_tag_action($patient_id = "", $document_id)
1313 if (is_numeric($document_id)) {
1314 sqlStatement("delete from procedure_result where document_id = ?", $document_id);
1316 return $this->view_action($patient_id, $document_id);
1319 function get_mapped_procedure($document_id)
1321 $map = array();
1322 if (is_numeric($document_id)) {
1323 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1324 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1325 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1326 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1327 where pres.document_id = ?", array($document_id));
1329 return $map;
1332 function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)
1334 $doc_notes = sqlQuery("select note from notes where foreign_id = ?", array($doc_id));
1335 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1337 if ($encounter != 0) {
1338 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?", array($encounter));
1339 } else if ($image_procedure_id != 0) {
1340 $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));
1341 } else {
1342 $ep = array('assigned_to' => $_SESSION['authUser']);
1345 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1346 $noteid = addPnote($_SESSION['pid'], 'New Image Report received '.$narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');
1347 setGpRelation(1, $doc_id, 6, $noteid);
1350 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1351 * Also usable for documents that may of been moved to different patients.
1353 * @param string $url - Current url string from database.
1354 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1355 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1357 * @return string
1359 function _check_relocation($url, $new_pid = null, $new_name = null)
1361 //strip url of protocol handler
1362 $url = preg_replace("|^(.*)://|", "", $url);
1363 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1364 while (current($fsnodes) != "documents") {
1365 array_shift($fsnodes);
1367 if ($new_pid) {
1368 $fsnodes[1] = $new_pid;
1370 if ($new_name) {
1371 $fsnodes[count($fsnodes)-1] = $new_name;
1373 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1374 // Make sure the url is available after corrections
1375 if ($new_pid || $new_name) {
1376 $url = $this->_rename_file($url);
1378 //Add full path and remaining nodes
1379 return $url;
1382 //clear encounter tag function
1383 function clear_encounter_tag_action($patient_id = "", $document_id)
1385 if (is_numeric($document_id)) {
1386 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?", array($patient_id,$document_id));
1388 return $this->view_action($patient_id, $document_id);