Patient picture (#926)
[openemr.git] / controllers / C_Document.class.php
blob7a0c2ae77b7325f9ff941dbed764b25f7829b65a
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 {
11 var $template_mod;
12 var $documents;
13 var $document_categories;
14 var $tree;
15 var $_config;
16 var $manual_set_owner=false; // allows manual setting of a document owner/service
17 var $facilityService;
18 var $patientService;
20 function __construct($template_mod = "general")
22 parent::__construct();
23 $this->facilityService = new \services\FacilityService();
24 $this->patientService = new \services\PatientService();
25 $this->documents = array();
26 $this->template_mod = $template_mod;
27 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
28 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
30 //get global config options for this namespace
31 $this->_config = $GLOBALS['oer_config']['documents'];
33 $this->_args = array("patient_id" => $_GET['patient_id']);
35 $this->assign("STYLE", $GLOBALS['style']);
36 $t = new CategoryTree(1);
37 //print_r($t->tree);
38 $this->tree = $t;
39 $this->Document = new Document();
42 function upload_action($patient_id,$category_id)
44 $category_name = $this->tree->get_node_name($category_id);
45 $this->assign("category_id", $category_id);
46 $this->assign("category_name", $category_name);
47 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
48 $this->assign("patient_id", $patient_id);
50 // Added by Rod to support document template download from general_upload.html.
51 // Cloned from similar stuff in manage_document_templates.php.
52 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
53 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
54 if (file_exists($templatedir)) {
55 $dh = opendir($templatedir);
57 if ($dh) {
58 $templateslist = array();
59 while (false !== ($sfname = readdir($dh))) {
60 if (substr($sfname, 0, 1) == '.') continue;
61 $templateslist[$sfname] = $sfname;
63 closedir($dh);
64 ksort($templateslist);
65 foreach ($templateslist as $sfname) {
66 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
67 "'>" . htmlspecialchars($sfname) . "</option>";
70 $this->assign("TEMPLATES_LIST", $templates_options);
72 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
73 $this->assign("activity", $activity);
74 return $this->list_action($patient_id);
77 //Upload multiple files on single click
78 function upload_action_process()
81 // Collect a manually set owner if this has been set
82 // Used when want to manually assign the owning user/service such as the Direct mechanism
83 $non_HTTP_owner=false;
84 if ($this->manual_set_owner) {
85 $non_HTTP_owner=$this->manual_set_owner;
88 $couchDB = false;
89 $harddisk = false;
90 if($GLOBALS['document_storage_method']==0){
91 $harddisk = true;
93 if($GLOBALS['document_storage_method']==1){
94 $couchDB = true;
97 if ($_POST['process'] != "true")
98 return;
100 $doDecryption = false;
101 $encrypted = $_POST['encrypted'];
102 $passphrase = $_POST['passphrase'];
103 if ( !$GLOBALS['hide_document_encryption'] &&
104 $encrypted && $passphrase ) {
105 $doDecryption = true;
108 if (is_numeric($_POST['category_id'])) {
109 $category_id = $_POST['category_id'];
112 $patient_id = 0;
113 if (isset($_GET['patient_id']) && !$couchDB) {
114 $patient_id = $_GET['patient_id'];
116 else if (is_numeric($_POST['patient_id'])) {
117 $patient_id = $_POST['patient_id'];
120 $sentUploadStatus = array();
121 if( count($_FILES['file']['name']) > 0){
122 $upl_inc = 0;
124 foreach($_FILES['file']['name'] as $key => $value){
125 $fname = $value;
126 $err = "";
127 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
128 $fname = $value;
129 if (empty($fname)) {
130 $fname = htmlentities("<empty>");
132 $error = xl("Error number") .": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
133 if ($_FILES['file']['size'][$key] == 0) {
134 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
136 }elseif($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])){
137 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
138 }else{
139 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
140 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
141 fclose($tmpfile);
142 if ($doDecryption) {
143 $filetext = $this->decrypt($filetext, $passphrase);
145 if ( $_POST['destination'] != '' ) {
146 $fname = $_POST['destination'];
148 $d = new Document();
149 $rc = $d->createDocument($patient_id, $category_id, $fname,
150 $_FILES['file']['type'][$key], $filetext,
151 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
152 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
153 $non_HTTP_owner, $_FILES['file']['tmp_name'][$key]);
154 if ($rc) {
155 $error .= $rc . "\n";
157 else {
158 $this->assign("upload_success", "true");
160 $sentUploadStatus[] = $d;
161 $this->assign("file", $sentUploadStatus);
164 // Option to run a custom plugin for each file upload.
165 // This was initially created to delete the original source file in a custom setting.
166 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
167 if (file_exists($upload_plugin)) {
168 include_once($upload_plugin);
170 $upload_plugin_pp = 'documentUploadPostProcess';
171 if (function_exists($upload_plugin_pp)) {
172 $tmp = call_user_func($upload_plugin_pp, $value, $d);
173 if ($tmp) {
174 $error = $tmp;
177 // Following is just an example of code in such a plugin file.
178 /*****************************************************
179 function documentUploadPostProcess($filename, &$d) {
180 $userid = $_SESSION['authUserID'];
181 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
182 $owner = strtolower($row['username']);
183 $dn = '1_' . ucfirst($owner);
184 $filepath = "/shared_network_directory/$dn/$filename";
185 if (@unlink($filepath)) return '';
186 return "Failed to delete '$filepath'.";
188 *****************************************************/
193 $this->assign("error", nl2br($error));
194 //$this->_state = false;
195 $_POST['process'] = "";
196 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
199 function note_action_process($patient_id)
201 // this function is a dual function that will set up a note associated with a document or send a document via email.
203 if ($_POST['process'] != "true")
204 return;
206 $n = new Note();
207 $n->set_owner($_SESSION['authUserID']);
208 parent::populate_object($n);
209 if ($_POST['identifier'] == "no"){
210 // associate a note with a document
211 $n->persist();
212 }elseif ($_POST['identifier'] == "yes"){
213 // send the document via email
214 $d = new Document($_POST['foreign_id']);
215 $url = $d->get_url();
216 $storagemethod = $d->get_storagemethod();
217 $couch_docid = $d->get_couch_docid();
218 $couch_revid = $d->get_couch_revid();
219 if($couch_docid && $couch_revid){
220 $couch = new CouchDB();
221 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
222 $resp = $couch->retrieve_doc($data);
223 $content = $resp->data;
224 if($content=='' && $GLOBALS['couchdb_log']==1){
225 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
226 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
227 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
228 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
229 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
230 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
231 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
232 die(xlt("File retrieval from CouchDB failed"));
234 // place it in a temporary file and will remove the file below after emailed
235 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
236 $fh = fopen($temp_couchdb_url,"w");
237 fwrite($fh,base64_decode($content));
238 fclose($fh);
239 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
240 } else {
241 $url = preg_replace("|^(.*)://|","",$url);
242 // Collect filename and path
243 $from_all = explode("/",$url);
244 $from_filename = array_pop($from_all);
245 $from_pathname_array = array();
246 for ($i=0;$i<$d->get_path_depth();$i++) {
247 $from_pathname_array[] = array_pop($from_all);
249 $from_pathname_array = array_reverse($from_pathname_array);
250 $from_pathname = implode("/",$from_pathname_array);
251 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
253 if (!file_exists($temp_url)) {
254 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;
256 $url = $temp_url;
257 $body_notes = attr($_POST['note']);
258 $pdetails = getPatientData($patient_id);
259 $pname = $pdetails['fname']." ".$pdetails['lname'];
260 $this->document_send($_POST['provide_email'],$body_notes,$url,$pname);
261 if ($couch_docid && $couch_revid) {
262 // remove the temporary couchdb file
263 unlink($temp_couchdb_url);
266 $this->_state = false;
267 $_POST['process'] = "";
268 return $this->view_action($patient_id,$n->get_foreign_id());
271 function default_action()
273 return $this->list_action();
276 function view_action($patient_id="",$doc_id)
278 // Added by Rod to support document delete:
279 global $gacl_object, $phpgacl_location;
280 global $ISSUE_TYPES;
282 require_once(dirname(__FILE__) . "/../library/acl.inc");
283 require_once(dirname(__FILE__) . "/../library/lists.inc");
285 $d = new Document($doc_id);
286 $n = new Note();
288 $notes = $n->notes_factory($doc_id);
290 $this->assign("file", $d);
291 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
292 $this->assign("NOTE_ACTION",$this->_link("note"));
293 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
294 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
296 // Added by Rod to support document delete:
297 $delete_string = '';
298 if (acl_check('admin', 'super')) {
299 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
300 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
302 $this->assign("delete_string", $delete_string);
303 $this->assign("REFRESH_ACTION",$this->_link("list"));
305 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
306 "document_id=" . $d->get_id() . "&process=true");
308 // Added by Rod to support document date update:
309 $this->assign("DOCDATE", $d->get_docdate());
310 $this->assign("UPDATE_ACTION",$this->_link("update") .
311 "document_id=" . $d->get_id() . "&process=true");
313 // Added by Rod to support document issue update:
314 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
315 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
316 "pid = ? " . // AND enddate IS NULL " .
317 "ORDER BY type, begdate", array($patient_id) );
318 while ($irow = sqlFetchArray($ires)) {
319 $desc = $irow['type'];
320 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
321 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
322 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
323 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
325 $this->assign("ISSUES_LIST", $issues_options);
327 // For tagging to encounter
328 // Populate the dropdown with patient's encounter list
329 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
330 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
331 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
332 "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));
333 if ( sqlNumRows($result_docs) > 0)
334 while($row_result_docs = sqlFetchArray($result_docs)) {
335 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
336 $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>";
338 $this->assign("ENC_LIST", $encOptions);
340 //clear encounter tag
341 if ($d->get_encounter_id() != 0) {
342 $this->assign('clear_encounter_tag',$this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
343 } else {
344 $this->assign('clear_encounter_tag','javascript:void(0)');
347 //Populate the dropdown with category list
348 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
349 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
350 while ($crow = sqlFetchArray($cres)) {
351 $catid = $crow['pc_catid'];
352 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
353 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
355 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
357 $this->assign("notes",$notes);
359 $this->assign("IMG_PROCEDURE_TAG_ACTION",$this->_link("image_procedure") . "document_id=" . $d->get_id());
360 // Populate the dropdown with image procedure order list
361 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
362 $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));
363 $mapping = $this->get_mapped_procedure($d->get_id());
364 if(sqlNumRows($imgOrders) > 0){
365 while($row = sqlFetchArray($imgOrders)) {
366 $sel_proc = '';
367 if((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id']))
368 $sel_proc = 'selected';
369 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
373 $this->assign('IMAGE_PROCEDURE_LIST',$imgOptions);
375 $this->assign('clear_procedure_tag',$this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
377 $this->_last_node = null;
379 $menu = new HTML_TreeMenu();
381 //pass an empty array because we don't want the documents for each category showing up in this list box
382 $rnode = $this->_array_recurse($this->tree->tree,array());
383 $menu->addItem($rnode);
384 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
386 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
388 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
389 $this->assign("activity", $activity);
391 return $this->list_action($patient_id);
394 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
396 $td = mcrypt_module_open( $cypher, '', $mode, '');
397 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
398 mcrypt_generic_init( $td, $key, $iv );
399 $crypttext = mcrypt_generic( $td, $plaintext );
400 mcrypt_generic_deinit( $td );
401 return $iv.$crypttext;
404 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
406 $plaintext = '';
407 $td = mcrypt_module_open( $cypher, '', $mode, '' );
408 $ivsize = mcrypt_enc_get_iv_size( $td) ;
409 $iv = substr( $crypttext, 0, $ivsize );
410 $crypttext = substr( $crypttext, $ivsize );
411 if( $iv )
413 mcrypt_generic_init( $td, $key, $iv );
414 $plaintext = mdecrypt_generic( $td, $crypttext );
416 return $plaintext;
420 * Retrieve file from hard disk / CouchDB.
421 * In case that file isn't download this function will return thumbnail image (if exist).
422 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
423 * @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.
424 * */
425 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false,$show_original=false,$context="normal")
427 $encrypted = $_POST['encrypted'];
428 $passphrase = $_POST['passphrase'];
429 $doEncryption = false;
430 if ( !$GLOBALS['hide_document_encryption'] &&
431 $encrypted == "true" &&
432 $passphrase ) {
433 $doEncryption = true;
436 //controller function ruins booleans, so need to manually re-convert to booleans
437 if ($as_file == "true") {
438 $as_file=true;
440 else if ($as_file == "false") {
441 $as_file=false;
443 if ($original_file == "true") {
444 $original_file=true;
446 else if ($original_file == "false") {
447 $original_file=false;
449 if ($disable_exit == "true") {
450 $disable_exit=true;
452 else if ($disable_exit == "false") {
453 $disable_exit=false;
455 if ($show_original == "true") {
456 $show_original=true;
458 else if ($show_original == "false") {
459 $show_original=false;
462 switch ($context) {
463 case "patient_picture":
464 $this->patientService->setPid($patient_id);
465 $document_id = $this->patientService->getPatientPictureDocumentId();
466 break;
469 $d = new Document($document_id);
470 $url = $d->get_url();
471 $th_url = $d->get_thumb_url();
473 $storagemethod = $d->get_storagemethod();
474 $couch_docid = $d->get_couch_docid();
475 $couch_revid = $d->get_couch_revid();
477 if($couch_docid && $couch_revid && $original_file){
478 $couch = new CouchDB();
479 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
480 $resp = $couch->retrieve_doc($data);
481 //Take thumbnail file when is not null and file is presented online
482 if (!$as_file && !is_null($th_url) && !$show_original) {
483 $content = $resp->th_data;
484 } else {
485 $content = $resp->data;
487 if($content=='' && $GLOBALS['couchdb_log']==1){
488 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
489 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
490 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
491 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
492 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
493 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
494 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
495 die(xl("File retrieval from CouchDB failed"));
497 if($disable_exit == true) {
498 return base64_decode($content);
500 header('Content-Description: File Transfer');
501 header('Content-Transfer-Encoding: binary');
502 header('Expires: 0');
503 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
504 header('Pragma: public');
505 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
506 $fh = fopen($tmpcouchpath,"w");
507 fwrite($fh,base64_decode($content));
508 fclose($fh);
509 $f = fopen($tmpcouchpath,"r");
510 if ( $doEncryption ) {
511 $filetext = fread( $f, filesize($tmpcouchpath) );
512 $ciphertext = $this->encrypt( $filetext, $passphrase );
513 $tmpfilepath = $GLOBALS['temporary_files_dir'];
514 $tmpfilename = "/encrypted_".$d->get_url_file();
515 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
516 fwrite( $tmpfile, $ciphertext );
517 fclose( $tmpfile );
518 header('Content-Disposition: attachment; filename='.$tmpfilename );
519 header("Content-Type: application/octet-stream" );
520 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
521 ob_clean();
522 flush();
523 readfile( $tmpfilepath.$tmpfilename );
524 unlink( $tmpfilepath.$tmpfilename );
525 } else {
526 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
527 header("Content-Type: " . $d->get_mimetype());
528 header("Content-Length: " . filesize($tmpcouchpath));
529 fpassthru($f);
531 fclose($f);
532 if($content!='')
533 unlink($tmpcouchpath);
534 exit;//exits only if file download from CouchDB is successfull.
537 //Take thumbnail file when is not null and file is presented online
538 if(!$as_file && !is_null($th_url) && !$show_original) {
539 $url = $th_url;
542 //strip url of protocol handler
543 $url = preg_replace("|^(.*)://|","",$url);
545 //change full path to current webroot. this is for documents that may have
546 //been moved from a different filesystem and the full path in the database
547 //is not current. this is also for documents that may of been moved to
548 //different patients. Note that the path_depth is used to see how far down
549 //the path to go. For example, originally the path_depth was always 1, which
550 //only allowed things like documents/1/<file>, but now can have more structured
551 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
552 // etc.
553 // NOTE that $from_filename and basename($url) are the same thing
554 $from_all = explode("/",$url);
555 $from_filename = array_pop($from_all);
556 $from_pathname_array = array();
557 for ($i=0;$i<$d->get_path_depth();$i++) {
558 $from_pathname_array[] = array_pop($from_all);
560 $from_pathname_array = array_reverse($from_pathname_array);
561 $from_pathname = implode("/",$from_pathname_array);
562 if($couch_docid && $couch_revid){
563 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
564 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
567 else{
568 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
571 if (file_exists($temp_url)) {
572 $url = $temp_url;
576 if (!file_exists($url)) {
577 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;
580 else {
581 if ($original_file) {
582 //normal case when serving the file referenced in database
583 if($disable_exit == true) {
584 $f = fopen($url,"r");
585 $filetext = fread( $f, filesize($url) );
586 return $filetext;
588 header('Content-Description: File Transfer');
589 header('Content-Transfer-Encoding: binary');
590 header('Expires: 0');
591 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
592 header('Pragma: public');
593 $f = fopen($url,"r");
594 if ( $doEncryption ) {
595 $filetext = fread( $f, filesize($url) );
596 $ciphertext = $this->encrypt( $filetext, $passphrase );
597 $tmpfilepath = $GLOBALS['temporary_files_dir'];
598 $tmpfilename = "/encrypted_".$d->get_url_file();
599 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
600 fwrite( $tmpfile, $ciphertext );
601 fclose( $tmpfile );
602 header('Content-Disposition: attachment; filename='.$tmpfilename );
603 header("Content-Type: application/octet-stream" );
604 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
605 ob_clean();
606 flush();
607 readfile( $tmpfilepath.$tmpfilename );
608 unlink( $tmpfilepath.$tmpfilename );
609 } else {
610 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
611 header("Content-Type: " . $d->get_mimetype());
612 header("Content-Length: " . filesize($url));
613 fpassthru($f);
615 exit;
617 else {
618 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
619 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
620 if($couch_docid && $couch_revid){
621 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
623 else{
624 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
626 if($disable_exit == true) {
627 return ;
629 header("Pragma: public");
630 header("Expires: 0");
631 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
632 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
633 header("Content-Type: image/jpeg");
634 header("Content-Length: " . filesize($url));
635 $f = fopen($url,"r");
636 fpassthru($f);
637 if($couch_docid && $couch_revid){
638 fclose($f);
639 unlink($url);
640 $url=str_replace("_converted.jpg",'.pdf',$url);
641 unlink($url);
643 exit;
648 function queue_action($patient_id="")
650 $messages = $this->_tpl_vars['messages'];
651 $queue_files = array();
653 //see if the repository exists and it is a directory else error
654 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
655 $dir = opendir($this->_config['repository']);
656 //read each entry in the directory
657 while (($file = readdir($dir)) !== false) {
658 //concat the filename and path
659 $file = $this->_config['repository'] .$file;
660 $file_info = array();
661 //if the filename is a file get its info and put into a tmp array
662 if (is_file($file) && strpos(basename_international($file),".") !== 0) {
663 $file_info['filename'] = basename_international($file);
664 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
665 $d = $this->Document->document_factory_url("file://" . $file);
666 preg_match("/^([0-9]+)_/",basename_international($file),$patient_match);
667 $file_info['patient_id'] = $patient_match[1];
668 $file_info['document_id'] = $d->get_id();
669 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
671 //merge the tmp array into the larger array
672 $queue_files[] = $file_info;
675 closedir($dir);
677 else {
678 $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";
682 $this->assign("queue_files",$queue_files);
683 $this->_last_node = null;
685 $menu = new HTML_TreeMenu();
687 //pass an empty array because we don't want the documents for each category showing up in this list box
688 $rnode = $this->_array_recurse($this->tree->tree,array());
689 $menu->addItem($rnode);
690 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
692 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
694 $this->assign("messages",nl2br($messages));
695 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
698 function queue_action_process()
700 if ($_POST['process'] != "true")
701 return;
703 $messages = $this->_tpl_vars['messages'];
705 //build a category tree so we can have a list of category ids that are valid
706 $ct = new CategoryTree(1);
707 $categories = $ct->_id_name;
709 //see if there were and posted files and assign them
710 $files = null;
711 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
713 //loop through posted files
714 foreach($files as $doc_id=> $file) {
715 //only operate on files checked as active
716 if (!$file['active']) continue;
718 //run basic validation checks
719 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
720 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
721 continue;
724 //validate that the pod exists
725 $d = new Document($doc_id);
726 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
727 $result = $d->_db->Execute($sql);
729 if (!$result || $result->EOF) {
730 //patient id does not exist
731 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
732 continue;
735 //validate that the category id exists
736 if (!isset($categories[$file['category_id']])) {
737 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
738 continue;
741 //now do the work of moving the file
742 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
744 //see if the patient dir exists in the repository and create if not
745 if (!file_exists($new_path)) {
746 if (!mkdir($new_path,0700)) {
747 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
748 continue;
752 //fname is the name of the file after it is moved
753 $fname = $file['name'];
755 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
756 preg_match("/^([0-9]+)_/",basename_international($fname),$patient_match);
757 if ($patient_match[1] == $file['patient_id']) {
758 $fname = preg_replace("/^([0-9]+)_/","",$fname);
761 //filenames should not have funny chars
762 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
764 //see if there is an existing file with the same name and rename as necessary
765 if (file_exists($new_path.$file['name'])) {
766 $messages .= "File with same name already exists at location: " . $new_path . "\n";
767 $fname = basename_international($this->_rename_file($new_path.$file['name']));
768 $messages .= "Current file name was changed to " . $fname ."\n";
771 //now move the file
772 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
773 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
774 $d->url = "file://" .$new_path.$fname;
775 $d->set_foreign_id($file['patient_id']);
776 $d->set_mimetype($mimetype);
777 $d->persist();
778 $d->populate();
780 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
781 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
782 $d->_db->Execute($sql);
785 else {
786 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
789 $this->assign("messages",$messages);
790 $_POST['process'] = "";
793 function move_action_process($patient_id="",$document_id)
795 if ($_POST['process'] != "true")
796 return;
798 $new_category_id = $_POST['new_category_id'];
799 $new_patient_id = $_POST['new_patient_id'];
801 //move to new category
802 if (is_numeric($new_category_id) && is_numeric($document_id)) {
803 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
804 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
805 //echo $sql;
806 $this->tree->_db->Execute($sql);
809 //move to new patient
810 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
811 $d = new Document($document_id);
812 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
813 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
814 $result = $d->_db->Execute($sql);
816 if (!$result || $result->EOF) {
817 //patient id does not exist
818 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
820 else {
821 $couchsavefailed = !$d->change_patient($new_patient_id);
823 $this->_state = false;
824 if(!$couchsavefailed){
826 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
828 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);
836 //in this case return the document to the queue instead of moving it
837 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
838 $d = new Document($document_id);
839 $new_path = $this->_config['repository'];
840 $fname = $d->get_url_file();
842 //see if there is an existing file with the same name and rename as necessary
843 if (file_exists($new_path.$d->get_url_file())) {
844 $messages .= "File with same name already exists in the queue.\n";
845 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
846 $messages .= "Current file name was changed to " . $fname ."\n";
849 //now move the file
850 if (rename($d->get_url_filepath(),$new_path.$fname)) {
851 $d->url = "file://" .$new_path.$fname;
852 $d->set_foreign_id("");
853 $d->persist();
854 $d->persist();
855 $d->populate();
857 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
858 $d->_db->Execute($sql);
859 $messages .= "Document returned to queue successfully.\n";
862 else {
863 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
866 $this->_state = false;
867 $this->assign("messages",$messages);
868 return $this->list_action($patient_id);
871 $this->_state = false;
872 $this->assign("messages",$messages);
873 return $this->view_action($patient_id,$document_id);
876 function validate_action_process($patient_id="", $document_id)
879 $d = new Document($document_id);
880 if($d->couch_docid && $d->couch_revid){
881 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
882 $url = $file_path.$d->get_url();
883 $couch = new CouchDB();
884 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
885 $resp = $couch->retrieve_doc($data);
886 $content = $resp->data;
887 //--------Temporarily writing the file for calculating the hash--------//
888 //-----------Will be removed after calculating the hash value----------//
889 $temp_file = fopen($url,"w");
890 fwrite($temp_file,base64_decode($content));
891 fclose($temp_file);
893 else{
894 $url = $d->get_url();
896 //strip url of protocol handler
897 $url = preg_replace("|^(.*)://|","",$url);
899 //change full path to current webroot. this is for documents that may have
900 //been moved from a different filesystem and the full path in the database
901 //is not current. this is also for documents that may of been moved to
902 //different patients. Note that the path_depth is used to see how far down
903 //the path to go. For example, originally the path_depth was always 1, which
904 //only allowed things like documents/1/<file>, but now can have more structured
905 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
906 // etc.
907 // NOTE that $from_filename and basename($url) are the same thing
908 $from_all = explode("/",$url);
909 $from_filename = array_pop($from_all);
910 $from_pathname_array = array();
911 for ($i=0;$i<$d->get_path_depth();$i++) {
912 $from_pathname_array[] = array_pop($from_all);
914 $from_pathname_array = array_reverse($from_pathname_array);
915 $from_pathname = implode("/",$from_pathname_array);
916 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
917 if (file_exists($temp_url)) {
918 $url = $temp_url;
921 if ($_POST['process'] != "true") {
922 die("process is '" . $_POST['process'] . "', expected 'true'");
923 return;
926 $d = new Document( $document_id );
927 $current_hash = sha1_file( $url );
928 $messages = xl('Current Hash').": ".$current_hash."<br>";
929 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
930 if ( $d->get_hash() == '' ) {
931 $d->hash = $current_hash;
932 $d->persist();
933 $d->populate();
934 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
935 } else if ( $current_hash != $d->get_hash() ) {
936 $messages .= xl('Hash does not match. Data integrity has been compromised.');
937 } else {
938 $messages .= xl('Document passed integrity check.');
940 $this->_state = false;
941 $this->assign("messages", $messages);
942 if($d->couch_docid && $d->couch_revid){
943 //Removing the temporary file which is used to create the hash
944 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
946 return $this->view_action($patient_id, $document_id);
949 // Added by Rod for metadata update.
951 function update_action_process($patient_id="", $document_id)
954 if ($_POST['process'] != "true") {
955 die("process is '" . $_POST['process'] . "', expected 'true'");
956 return;
959 $docdate = $_POST['docdate'];
960 $docname = $_POST['docname'];
961 $issue_id = $_POST['issue_id'];
963 if (is_numeric($document_id)) {
964 $messages = '';
965 $d = new Document( $document_id );
966 $file_name = $d->get_url_file();
967 if ( $docname != '' &&
968 $docname != $file_name ) {
969 // Ready to rename - check for relocation
970 $old_url = $this->_check_relocation($d->get_url());
971 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
972 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
973 if ( rename( $old_url, $new_url ) ) {
974 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
975 if ( file_exists( $old_url ) ) {
976 unlink( $old_url );
978 $d->url = $new_url;
979 $d->persist();
980 $d->populate();
981 $messages .= xl('Document successfully renamed.')."<br>";
982 } else {
983 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
987 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
988 $docdate = "'$docdate'";
989 } else {
990 $docdate = "NULL";
992 if (!is_numeric($issue_id)) {
993 $issue_id = 0;
995 $couch_docid = $d->get_couch_docid();
996 $couch_revid = $d->get_couch_revid();
997 if($couch_docid && $couch_revid ){
998 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
999 "list_id = '$issue_id' " .
1000 "WHERE id = '$document_id'";
1001 $this->tree->_db->Execute($sql);
1004 else{
1005 $sql = "UPDATE documents SET docdate = $docdate, " .
1006 "list_id = '$issue_id' " .
1007 "WHERE id = '$document_id'";
1008 $this->tree->_db->Execute($sql);
1010 $messages .= xl('Document date and issue updated successfully') . "<br>";
1013 $this->_state = false;
1014 $this->assign("messages", $messages);
1015 return $this->view_action($patient_id, $document_id);
1018 function list_action($patient_id = "")
1020 $this->_last_node = null;
1021 $categories_list = $this->tree->_get_categories_array($patient_id);
1022 //print_r($categories_list);
1024 $menu = new HTML_TreeMenu();
1025 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
1026 $menu->addItem($rnode);
1027 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1028 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1030 $this->assign("tree_html",$treeMenu->toHTML());
1032 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1035 /* This is a recursive function to rename a file to something that doesn't already exist.
1036 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1037 * at end) to ensure documents opened correctly by external browser viewers. If the
1038 * counter is at the end of the file, then will use it (to continue to work with older
1039 * files), however all new counters will be placed within filenames.
1041 * Modified to only deal with base file name when renaming, to avoid issues with directory
1042 * names with dots.
1044 function _rename_file($fname, $self=false)
1046 // Allow same routine for new file name check
1047 if (!file_exists($fname)) return($fname);
1049 $path = dirname($fname);
1050 $file = basename_international($fname);
1052 $fparts = explode(".",$file);
1053 switch (count($fparts)) {
1054 case 1:
1055 // Has a single node (base file name). Create counter node with value 0
1056 $fparts[1] = '1';
1057 break;
1058 case 2:
1059 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1060 if (is_numeric($fparts[1])) {
1061 $fparts[1] += 1;
1062 } else {
1063 array_push($fparts, $fparts[1]);
1064 $fparts[1] = '1';
1066 break;
1067 default:
1068 // Multiple nodes
1069 $ix_end = count($fparts) - 1;
1070 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1071 // Switch old style to new and check again
1072 $wrk = $fparts[$ix_end - 1];
1073 $fparts[$ix_end - 1] = $fparts[$ix_end];
1074 $fparts[$ix_end] = $wrk;
1075 } else if (is_numeric($fparts[$ix_end - 1])) {
1076 $fparts[$ix_end - 1] += 1;
1077 } else {
1078 array_push($fparts, $fparts[$ix_end]);
1079 $fparts[$ix_end] = '1';
1081 break;
1084 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1086 if (file_exists($fname)) {
1087 return $this->_rename_file($fname, true);
1088 } else {
1089 return($fname);
1093 function &_array_recurse($array,$categories = array())
1095 if (!is_array($array)) {
1096 $array = array();
1098 $node = &$this->_last_node;
1099 $current_node = &$node;
1100 $expandedIcon = 'folder-expanded.gif';
1101 foreach($array as $id => $ar) {
1102 $icon = 'folder.gif';
1103 if (is_array($ar) || !empty($id)) {
1104 if ($node == null) {
1105 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1106 $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));
1107 $this->_last_node = &$rnode;
1108 $node = &$rnode;
1109 $current_node = &$rnode;
1111 else {
1112 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1113 $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)));
1114 $current_node = &$this->_last_node;
1117 $this->_array_recurse($ar,$categories);
1119 else {
1120 if ($id === 0 && !empty($ar)) {
1121 $info = $this->tree->get_node_info($id);
1122 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1123 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1125 else {
1126 //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
1127 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1128 if ($id !== 0 && is_object($node)) {
1129 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1130 $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)));
1136 // If there are documents in this document category, then add their
1137 // attributes to the current node.
1138 $icon = "file3.png";
1139 if (is_array($categories[$id])) {
1140 foreach ($categories[$id] as $doc) {
1141 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1142 // If user has no access then there will be no link.
1143 if (!acl_check_aco_spec($doc['aco_spec'])) $link = '';
1144 if($this->tree->get_node_name($id) == "CCR"){
1145 $current_node->addItem(new HTML_TreeNode(array(
1146 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1147 'link' => $link,
1148 'icon' => $icon,
1149 'expandedIcon' => $expandedIcon,
1150 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1151 )));
1152 }elseif($this->tree->get_node_name($id) == "CCD"){
1153 $current_node->addItem(new HTML_TreeNode(array(
1154 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1155 'link' => $link,
1156 'icon' => $icon,
1157 'expandedIcon' => $expandedIcon,
1158 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1159 )));
1160 }else{
1161 $current_node->addItem(new HTML_TreeNode(array(
1162 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1163 'link' => $link,
1164 'icon' => $icon,
1165 'expandedIcon' => $expandedIcon
1166 )));
1172 return $node;
1175 //function for logging the errors in writing file to CouchDB/Hard Disk
1176 function document_upload_download_log($patientid,$content)
1178 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1179 $log_file = 'log.txt';
1180 if(!is_dir($log_path))
1181 mkdir($log_path,0777,true);
1182 $LOG = fopen($log_path.$log_file,'a');
1183 fwrite($LOG,$content);
1184 fclose($LOG);
1187 function document_send($email,$body,$attfile,$pname)
1189 if (empty($email)) {
1190 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1191 return;
1194 $desc = "Please check the attached patient document.\n Content:".attr($body);
1195 $mail = new MyMailer();
1196 $from_name = $GLOBALS["practice_return_email_path"];
1197 $from = $GLOBALS["practice_return_email_path"];
1198 $mail->AddReplyTo($from,$from_name);
1199 $mail->SetFrom($from,$from );
1200 $to = $email ;
1201 $to_name =$email;
1202 $mail->AddAddress($to, $to_name);
1203 $subject = "Patient documents";
1204 $mail->Subject = $subject;
1205 $mail->Body = $desc;
1206 $mail->AddAttachment($attfile);
1207 if ($mail->Send()) {
1208 $retstatus = "email_sent";
1209 } else {
1210 $email_status = $mail->ErrorInfo;
1211 //echo "EMAIL ERROR: ".$email_status;
1212 $retstatus = "email_fail";
1216 //place to hold optional code
1217 //$first_node = array_keys($t->tree);
1218 //$first_node = $first_node[0];
1219 //$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')"));
1221 //$this->_last_node = &$node1;
1223 // Function to tag a document to an encounter.
1224 function tag_action_process($patient_id="", $document_id)
1226 if ($_POST['process'] != "true") {
1227 die("process is '" . text($_POST['process']) . "', expected 'true'");
1228 return;
1231 // Create Encounter and Tag it.
1232 $event_date = date('Y-m-d H:i:s');
1233 $encounter_id = $_POST['encounter_id'];
1234 $encounter_check = $_POST['encounter_check'];
1235 $visit_category_id = $_POST['visit_category_id'];
1237 if (is_numeric($document_id)) {
1238 $messages = '';
1239 $d = new Document( $document_id );
1240 $file_name = $d->get_url_file();
1241 if (!is_numeric($encounter_id)) {
1242 $encounter_id = 0;
1245 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1246 if ($encounter_check) {
1247 $provider_id = $_SESSION['authUserID'] ;
1249 // Get the logged in user's facility
1250 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1251 $username = $facilityRow['username'];
1252 $facility = $facilityRow['facility'];
1253 $facility_id = $facilityRow['facility_id'];
1254 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1255 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1256 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1258 $conn = $GLOBALS['adodb']['db'];
1259 $encounter = $conn->GenID("sequences");
1260 $query = "INSERT INTO form_encounter SET
1261 date = ?,
1262 reason = ?,
1263 facility = ?,
1264 sensitivity = 'normal',
1265 pc_catid = ?,
1266 facility_id = ?,
1267 billing_facility = ?,
1268 provider_id = ?,
1269 pid = ?,
1270 encounter = ?";
1271 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1272 $formID = sqlInsert($query,$bindArray);
1273 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1274 $d->set_encounter_id($encounter);
1275 $this->image_result_indication($d->id, $encounter);
1277 } else {
1278 $d->set_encounter_id($encounter_id);
1279 $this->image_result_indication($d->id, $encounter_id);
1281 $d->set_encounter_check($encounter_check);
1282 $d->persist();
1284 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1287 $this->_state = false;
1288 $this->assign("messages", $messages);
1290 return $this->view_action($patient_id, $document_id);
1293 function image_procedure_action($patient_id="",$document_id)
1296 $img_procedure_id = $_POST['image_procedure_id'];
1297 $proc_code = $_POST['procedure_code'];
1299 if(is_numeric($document_id)){
1301 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ",array($img_procedure_id,$proc_code));
1302 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ",array($img_procedure_id,$img_order['procedure_order_seq']));
1303 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1304 if($img_report_id == 0){
1305 $report_date = date('Y-m-d H:i:s');
1306 $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));
1309 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?",array($img_report_id,$document_id));
1310 if(empty($img_result)){
1311 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));
1314 $this->image_result_indication($document_id, 0,$img_procedure_id);
1316 return $this->view_action($patient_id, $document_id);
1319 function clear_procedure_tag_action($patient_id="",$document_id)
1321 if(is_numeric($document_id)){
1322 sqlStatement("delete from procedure_result where document_id = ?",$document_id);
1324 return $this->view_action($patient_id, $document_id);
1327 function get_mapped_procedure($document_id)
1329 $map = array();
1330 if(is_numeric($document_id)){
1331 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1332 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1333 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1334 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1335 where pres.document_id = ?",array($document_id));
1337 return $map;
1340 function image_result_indication($doc_id,$encounter,$image_procedure_id = 0)
1342 $doc_notes = sqlQuery("select note from notes where foreign_id = ?",array($doc_id));
1343 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1345 if($encounter != 0) {
1346 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?",array($encounter));
1348 else if($image_procedure_id != 0){
1349 $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));
1351 else{
1352 $ep = array('assigned_to' => $_SESSION['authUser']);
1355 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1356 $noteid = addPnote($_SESSION['pid'],'New Image Report received '.$narration,0,1,'Image Results',$encounter_provider,'','New','');
1357 setGpRelation(1, $doc_id, 6, $noteid);
1360 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1361 * Also usable for documents that may of been moved to different patients.
1363 * @param string $url - Current url string from database.
1364 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1365 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1367 * @return string
1369 function _check_relocation($url, $new_pid = null, $new_name = null)
1371 //strip url of protocol handler
1372 $url = preg_replace("|^(.*)://|","",$url);
1373 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1374 while (current($fsnodes) != "documents") {
1375 array_shift($fsnodes);
1377 if ($new_pid) {
1378 $fsnodes[1] = $new_pid;
1380 if ($new_name) {
1381 $fsnodes[count($fsnodes)-1] = $new_name;
1383 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1384 // Make sure the url is available after corrections
1385 if ($new_pid || $new_name) {
1386 $url = $this->_rename_file($url);
1388 //Add full path and remaining nodes
1389 return $url;
1392 //clear encounter tag function
1393 function clear_encounter_tag_action($patient_id="",$document_id)
1395 if (is_numeric($document_id)) {
1396 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?",array($patient_id,$document_id));
1398 return $this->view_action($patient_id, $document_id);