styling adjustments (#822)
[openemr.git] / controllers / C_Document.class.php
blob60dd264ae92017fc0452324da7118e09c80b916c
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;
19 function __construct($template_mod = "general") {
20 parent::__construct();
21 $this->facilityService = new \services\FacilityService();
22 $this->documents = array();
23 $this->template_mod = $template_mod;
24 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
25 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
27 //get global config options for this namespace
28 $this->_config = $GLOBALS['oer_config']['documents'];
30 $this->_args = array("patient_id" => $_GET['patient_id']);
32 $this->assign("STYLE", $GLOBALS['style']);
33 $t = new CategoryTree(1);
34 //print_r($t->tree);
35 $this->tree = $t;
36 $this->Document = new Document();
39 function upload_action($patient_id,$category_id) {
40 $category_name = $this->tree->get_node_name($category_id);
41 $this->assign("category_id", $category_id);
42 $this->assign("category_name", $category_name);
43 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
44 $this->assign("patient_id", $patient_id);
46 // Added by Rod to support document template download from general_upload.html.
47 // Cloned from similar stuff in manage_document_templates.php.
48 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
49 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
50 if (file_exists($templatedir)) {
51 $dh = opendir($templatedir);
53 if ($dh) {
54 $templateslist = array();
55 while (false !== ($sfname = readdir($dh))) {
56 if (substr($sfname, 0, 1) == '.') continue;
57 $templateslist[$sfname] = $sfname;
59 closedir($dh);
60 ksort($templateslist);
61 foreach ($templateslist as $sfname) {
62 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
63 "'>" . htmlspecialchars($sfname) . "</option>";
66 $this->assign("TEMPLATES_LIST", $templates_options);
68 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
69 $this->assign("activity", $activity);
70 return $this->list_action($patient_id);
73 //Upload multiple files on single click
74 function upload_action_process() {
76 // Collect a manually set owner if this has been set
77 // Used when want to manually assign the owning user/service such as the Direct mechanism
78 $non_HTTP_owner=false;
79 if ($this->manual_set_owner) {
80 $non_HTTP_owner=$this->manual_set_owner;
83 $couchDB = false;
84 $harddisk = false;
85 if($GLOBALS['document_storage_method']==0){
86 $harddisk = true;
88 if($GLOBALS['document_storage_method']==1){
89 $couchDB = true;
92 if ($_POST['process'] != "true")
93 return;
95 $doDecryption = false;
96 $encrypted = $_POST['encrypted'];
97 $passphrase = $_POST['passphrase'];
98 if ( !$GLOBALS['hide_document_encryption'] &&
99 $encrypted && $passphrase ) {
100 $doDecryption = true;
103 if (is_numeric($_POST['category_id'])) {
104 $category_id = $_POST['category_id'];
107 $patient_id = 0;
108 if (isset($_GET['patient_id']) && !$couchDB) {
109 $patient_id = $_GET['patient_id'];
111 else if (is_numeric($_POST['patient_id'])) {
112 $patient_id = $_POST['patient_id'];
115 $sentUploadStatus = array();
116 if( count($_FILES['file']['name']) > 0){
117 $upl_inc = 0;
119 foreach($_FILES['file']['name'] as $key => $value){
120 $fname = $value;
121 $err = "";
122 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
123 $fname = $value;
124 if (empty($fname)) {
125 $fname = htmlentities("<empty>");
127 $error = xl("Error number") .": " . $_FILES['file']['error'][$key] . " " . xl("occurred while uploading file named") . ": " . $fname . "\n";
128 if ($_FILES['file']['size'][$key] == 0) {
129 $error .= xl("The system does not permit uploading files of with size 0.") . "\n";
131 }elseif($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])){
132 $error = xl("The system does not permit uploading files with MIME content type") . " - " . mime_content_type($_FILES['file']['tmp_name'][$key]) . ".\n";
133 }else{
134 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
135 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
136 fclose($tmpfile);
137 if ($doDecryption) {
138 $filetext = $this->decrypt($filetext, $passphrase);
140 if ( $_POST['destination'] != '' ) {
141 $fname = $_POST['destination'];
143 $d = new Document();
144 $rc = $d->createDocument($patient_id, $category_id, $fname,
145 $_FILES['file']['type'][$key], $filetext,
146 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
147 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
148 $non_HTTP_owner, $_FILES['file']['tmp_name'][$key]);
149 if ($rc) {
150 $error .= $rc . "\n";
152 else {
153 $this->assign("upload_success", "true");
155 $sentUploadStatus[] = $d;
156 $this->assign("file", $sentUploadStatus);
159 // Option to run a custom plugin for each file upload.
160 // This was initially created to delete the original source file in a custom setting.
161 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
162 if (file_exists($upload_plugin)) {
163 include_once($upload_plugin);
165 $upload_plugin_pp = 'documentUploadPostProcess';
166 if (function_exists($upload_plugin_pp)) {
167 $tmp = call_user_func($upload_plugin_pp, $value, $d);
168 if ($tmp) {
169 $error = $tmp;
172 // Following is just an example of code in such a plugin file.
173 /*****************************************************
174 function documentUploadPostProcess($filename, &$d) {
175 $userid = $_SESSION['authUserID'];
176 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
177 $owner = strtolower($row['username']);
178 $dn = '1_' . ucfirst($owner);
179 $filepath = "/shared_network_directory/$dn/$filename";
180 if (@unlink($filepath)) return '';
181 return "Failed to delete '$filepath'.";
183 *****************************************************/
188 $this->assign("error", nl2br($error));
189 //$this->_state = false;
190 $_POST['process'] = "";
191 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
194 function note_action_process($patient_id) {
195 // this function is a dual function that will set up a note associated with a document or send a document via email.
197 if ($_POST['process'] != "true")
198 return;
200 $n = new Note();
201 $n->set_owner($_SESSION['authUserID']);
202 parent::populate_object($n);
203 if ($_POST['identifier'] == "no"){
204 // associate a note with a document
205 $n->persist();
206 }elseif ($_POST['identifier'] == "yes"){
207 // send the document via email
208 $d = new Document($_POST['foreign_id']);
209 $url = $d->get_url();
210 $storagemethod = $d->get_storagemethod();
211 $couch_docid = $d->get_couch_docid();
212 $couch_revid = $d->get_couch_revid();
213 if($couch_docid && $couch_revid){
214 $couch = new CouchDB();
215 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
216 $resp = $couch->retrieve_doc($data);
217 $content = $resp->data;
218 if($content=='' && $GLOBALS['couchdb_log']==1){
219 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
220 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
221 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
222 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
223 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
224 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
225 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
226 die(xlt("File retrieval from CouchDB failed"));
228 // place it in a temporary file and will remove the file below after emailed
229 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
230 $fh = fopen($temp_couchdb_url,"w");
231 fwrite($fh,base64_decode($content));
232 fclose($fh);
233 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
234 } else {
235 $url = preg_replace("|^(.*)://|","",$url);
236 // Collect filename and path
237 $from_all = explode("/",$url);
238 $from_filename = array_pop($from_all);
239 $from_pathname_array = array();
240 for ($i=0;$i<$d->get_path_depth();$i++) {
241 $from_pathname_array[] = array_pop($from_all);
243 $from_pathname_array = array_reverse($from_pathname_array);
244 $from_pathname = implode("/",$from_pathname_array);
245 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
247 if (!file_exists($temp_url)) {
248 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;
250 $url = $temp_url;
251 $body_notes = attr($_POST['note']);
252 $pdetails = getPatientData($patient_id);
253 $pname = $pdetails['fname']." ".$pdetails['lname'];
254 $this->document_send($_POST['provide_email'],$body_notes,$url,$pname);
255 if ($couch_docid && $couch_revid) {
256 // remove the temporary couchdb file
257 unlink($temp_couchdb_url);
260 $this->_state = false;
261 $_POST['process'] = "";
262 return $this->view_action($patient_id,$n->get_foreign_id());
265 function default_action() {
266 return $this->list_action();
269 function view_action($patient_id="",$doc_id) {
270 // Added by Rod to support document delete:
271 global $gacl_object, $phpgacl_location;
272 global $ISSUE_TYPES;
274 require_once(dirname(__FILE__) . "/../library/acl.inc");
275 require_once(dirname(__FILE__) . "/../library/lists.inc");
277 $d = new Document($doc_id);
278 $n = new Note();
280 $notes = $n->notes_factory($doc_id);
282 $this->assign("file", $d);
283 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
284 $this->assign("NOTE_ACTION",$this->_link("note"));
285 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
286 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
288 // Added by Rod to support document delete:
289 $delete_string = '';
290 if (acl_check('admin', 'super')) {
291 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
292 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
294 $this->assign("delete_string", $delete_string);
295 $this->assign("REFRESH_ACTION",$this->_link("list"));
297 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
298 "document_id=" . $d->get_id() . "&process=true");
300 // Added by Rod to support document date update:
301 $this->assign("DOCDATE", $d->get_docdate());
302 $this->assign("UPDATE_ACTION",$this->_link("update") .
303 "document_id=" . $d->get_id() . "&process=true");
305 // Added by Rod to support document issue update:
306 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
307 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
308 "pid = ? " . // AND enddate IS NULL " .
309 "ORDER BY type, begdate", array($patient_id) );
310 while ($irow = sqlFetchArray($ires)) {
311 $desc = $irow['type'];
312 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
313 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
314 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
315 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
317 $this->assign("ISSUES_LIST", $issues_options);
319 // For tagging to encounter
320 // Populate the dropdown with patient's encounter list
321 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
322 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
323 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
324 "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));
325 if ( sqlNumRows($result_docs) > 0)
326 while($row_result_docs = sqlFetchArray($result_docs)) {
327 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
328 $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>";
330 $this->assign("ENC_LIST", $encOptions);
332 //clear encounter tag
333 if ($d->get_encounter_id() != 0) {
334 $this->assign('clear_encounter_tag',$this->_link('clear_encounter_tag')."document_id=" . $d->get_id());
335 } else {
336 $this->assign('clear_encounter_tag','javascript:void(0)');
339 //Populate the dropdown with category list
340 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
341 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
342 while ($crow = sqlFetchArray($cres)) {
343 $catid = $crow['pc_catid'];
344 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
345 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
347 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
349 $this->assign("notes",$notes);
351 $this->assign("IMG_PROCEDURE_TAG_ACTION",$this->_link("image_procedure") . "document_id=" . $d->get_id());
352 // Populate the dropdown with image procedure order list
353 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
354 $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));
355 $mapping = $this->get_mapped_procedure($d->get_id());
356 if(sqlNumRows($imgOrders) > 0){
357 while($row = sqlFetchArray($imgOrders)) {
358 $sel_proc = '';
359 if((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id']))
360 $sel_proc = 'selected';
361 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
365 $this->assign('IMAGE_PROCEDURE_LIST',$imgOptions);
367 $this->assign('clear_procedure_tag',$this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
369 $this->_last_node = null;
371 $menu = new HTML_TreeMenu();
373 //pass an empty array because we don't want the documents for each category showing up in this list box
374 $rnode = $this->_array_recurse($this->tree->tree,array());
375 $menu->addItem($rnode);
376 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
378 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
380 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
381 $this->assign("activity", $activity);
383 return $this->list_action($patient_id);
386 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
388 $td = mcrypt_module_open( $cypher, '', $mode, '');
389 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
390 mcrypt_generic_init( $td, $key, $iv );
391 $crypttext = mcrypt_generic( $td, $plaintext );
392 mcrypt_generic_deinit( $td );
393 return $iv.$crypttext;
396 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
398 $plaintext = '';
399 $td = mcrypt_module_open( $cypher, '', $mode, '' );
400 $ivsize = mcrypt_enc_get_iv_size( $td) ;
401 $iv = substr( $crypttext, 0, $ivsize );
402 $crypttext = substr( $crypttext, $ivsize );
403 if( $iv )
405 mcrypt_generic_init( $td, $key, $iv );
406 $plaintext = mdecrypt_generic( $td, $crypttext );
408 return $plaintext;
412 * Retrieve file from hard disk / CouchDB.
413 * In case that file isn't download this function will return thumbnail image (if exist).
414 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
415 * */
416 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false,$show_original=false) {
418 $encrypted = $_POST['encrypted'];
419 $passphrase = $_POST['passphrase'];
420 $doEncryption = false;
421 if ( !$GLOBALS['hide_document_encryption'] &&
422 $encrypted == "true" &&
423 $passphrase ) {
424 $doEncryption = true;
427 //controller function ruins booleans, so need to manually re-convert to booleans
428 if ($as_file == "true") {
429 $as_file=true;
431 else if ($as_file == "false") {
432 $as_file=false;
434 if ($original_file == "true") {
435 $original_file=true;
437 else if ($original_file == "false") {
438 $original_file=false;
440 if ($disable_exit == "true") {
441 $disable_exit=true;
443 else if ($disable_exit == "false") {
444 $disable_exit=false;
446 if ($show_original == "true") {
447 $show_original=true;
449 else if ($show_original == "false") {
450 $show_original=false;
453 $d = new Document($document_id);
454 $url = $d->get_url();
455 $th_url = $d->get_thumb_url();
457 $storagemethod = $d->get_storagemethod();
458 $couch_docid = $d->get_couch_docid();
459 $couch_revid = $d->get_couch_revid();
461 if($couch_docid && $couch_revid && $original_file){
462 $couch = new CouchDB();
463 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
464 $resp = $couch->retrieve_doc($data);
465 //Take thumbnail file when is not null and file is presented online
466 if (!$as_file && !is_null($th_url) && !$show_original) {
467 $content = $resp->th_data;
468 } else {
469 $content = $resp->data;
471 if($content=='' && $GLOBALS['couchdb_log']==1){
472 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
473 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
474 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
475 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
476 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
477 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
478 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
479 die(xl("File retrieval from CouchDB failed"));
481 if($disable_exit == true) {
482 return base64_decode($content);
484 header('Content-Description: File Transfer');
485 header('Content-Transfer-Encoding: binary');
486 header('Expires: 0');
487 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
488 header('Pragma: public');
489 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
490 $fh = fopen($tmpcouchpath,"w");
491 fwrite($fh,base64_decode($content));
492 fclose($fh);
493 $f = fopen($tmpcouchpath,"r");
494 if ( $doEncryption ) {
495 $filetext = fread( $f, filesize($tmpcouchpath) );
496 $ciphertext = $this->encrypt( $filetext, $passphrase );
497 $tmpfilepath = $GLOBALS['temporary_files_dir'];
498 $tmpfilename = "/encrypted_".$d->get_url_file();
499 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
500 fwrite( $tmpfile, $ciphertext );
501 fclose( $tmpfile );
502 header('Content-Disposition: attachment; filename='.$tmpfilename );
503 header("Content-Type: application/octet-stream" );
504 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
505 ob_clean();
506 flush();
507 readfile( $tmpfilepath.$tmpfilename );
508 unlink( $tmpfilepath.$tmpfilename );
509 } else {
510 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
511 header("Content-Type: " . $d->get_mimetype());
512 header("Content-Length: " . filesize($tmpcouchpath));
513 fpassthru($f);
515 fclose($f);
516 if($content!='')
517 unlink($tmpcouchpath);
518 exit;//exits only if file download from CouchDB is successfull.
521 //Take thumbnail file when is not null and file is presented online
522 if(!$as_file && !is_null($th_url) && !$show_original) {
523 $url = $th_url;
526 //strip url of protocol handler
527 $url = preg_replace("|^(.*)://|","",$url);
529 //change full path to current webroot. this is for documents that may have
530 //been moved from a different filesystem and the full path in the database
531 //is not current. this is also for documents that may of been moved to
532 //different patients. Note that the path_depth is used to see how far down
533 //the path to go. For example, originally the path_depth was always 1, which
534 //only allowed things like documents/1/<file>, but now can have more structured
535 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
536 // etc.
537 // NOTE that $from_filename and basename($url) are the same thing
538 $from_all = explode("/",$url);
539 $from_filename = array_pop($from_all);
540 $from_pathname_array = array();
541 for ($i=0;$i<$d->get_path_depth();$i++) {
542 $from_pathname_array[] = array_pop($from_all);
544 $from_pathname_array = array_reverse($from_pathname_array);
545 $from_pathname = implode("/",$from_pathname_array);
546 if($couch_docid && $couch_revid){
547 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
548 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
551 else{
552 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
555 if (file_exists($temp_url)) {
556 $url = $temp_url;
560 if (!file_exists($url)) {
561 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;
564 else {
565 if ($original_file) {
566 //normal case when serving the file referenced in database
567 if($disable_exit == true) {
568 $f = fopen($url,"r");
569 $filetext = fread( $f, filesize($url) );
570 return $filetext;
572 header('Content-Description: File Transfer');
573 header('Content-Transfer-Encoding: binary');
574 header('Expires: 0');
575 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
576 header('Pragma: public');
577 $f = fopen($url,"r");
578 if ( $doEncryption ) {
579 $filetext = fread( $f, filesize($url) );
580 $ciphertext = $this->encrypt( $filetext, $passphrase );
581 $tmpfilepath = $GLOBALS['temporary_files_dir'];
582 $tmpfilename = "/encrypted_".$d->get_url_file();
583 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
584 fwrite( $tmpfile, $ciphertext );
585 fclose( $tmpfile );
586 header('Content-Disposition: attachment; filename='.$tmpfilename );
587 header("Content-Type: application/octet-stream" );
588 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
589 ob_clean();
590 flush();
591 readfile( $tmpfilepath.$tmpfilename );
592 unlink( $tmpfilepath.$tmpfilename );
593 } else {
594 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
595 header("Content-Type: " . $d->get_mimetype());
596 header("Content-Length: " . filesize($url));
597 fpassthru($f);
599 exit;
601 else {
602 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
603 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
604 if($couch_docid && $couch_revid){
605 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
607 else{
608 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
610 if($disable_exit == true) {
611 return ;
613 header("Pragma: public");
614 header("Expires: 0");
615 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
616 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
617 header("Content-Type: image/jpeg");
618 header("Content-Length: " . filesize($url));
619 $f = fopen($url,"r");
620 fpassthru($f);
621 if($couch_docid && $couch_revid){
622 fclose($f);
623 unlink($url);
624 $url=str_replace("_converted.jpg",'.pdf',$url);
625 unlink($url);
627 exit;
632 function queue_action($patient_id="") {
633 $messages = $this->_tpl_vars['messages'];
634 $queue_files = array();
636 //see if the repository exists and it is a directory else error
637 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
638 $dir = opendir($this->_config['repository']);
639 //read each entry in the directory
640 while (($file = readdir($dir)) !== false) {
641 //concat the filename and path
642 $file = $this->_config['repository'] .$file;
643 $file_info = array();
644 //if the filename is a file get its info and put into a tmp array
645 if (is_file($file) && strpos(basename_international($file),".") !== 0) {
646 $file_info['filename'] = basename_international($file);
647 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
648 $d = $this->Document->document_factory_url("file://" . $file);
649 preg_match("/^([0-9]+)_/",basename_international($file),$patient_match);
650 $file_info['patient_id'] = $patient_match[1];
651 $file_info['document_id'] = $d->get_id();
652 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
654 //merge the tmp array into the larger array
655 $queue_files[] = $file_info;
658 closedir($dir);
660 else {
661 $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";
665 $this->assign("queue_files",$queue_files);
666 $this->_last_node = null;
668 $menu = new HTML_TreeMenu();
670 //pass an empty array because we don't want the documents for each category showing up in this list box
671 $rnode = $this->_array_recurse($this->tree->tree,array());
672 $menu->addItem($rnode);
673 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
675 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
677 $this->assign("messages",nl2br($messages));
678 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
681 function queue_action_process() {
682 if ($_POST['process'] != "true")
683 return;
685 $messages = $this->_tpl_vars['messages'];
687 //build a category tree so we can have a list of category ids that are valid
688 $ct = new CategoryTree(1);
689 $categories = $ct->_id_name;
691 //see if there were and posted files and assign them
692 $files = null;
693 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
695 //loop through posted files
696 foreach($files as $doc_id=> $file) {
697 //only operate on files checked as active
698 if (!$file['active']) continue;
700 //run basic validation checks
701 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
702 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
703 continue;
706 //validate that the pod exists
707 $d = new Document($doc_id);
708 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
709 $result = $d->_db->Execute($sql);
711 if (!$result || $result->EOF) {
712 //patient id does not exist
713 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
714 continue;
717 //validate that the category id exists
718 if (!isset($categories[$file['category_id']])) {
719 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
720 continue;
723 //now do the work of moving the file
724 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
726 //see if the patient dir exists in the repository and create if not
727 if (!file_exists($new_path)) {
728 if (!mkdir($new_path,0700)) {
729 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
730 continue;
734 //fname is the name of the file after it is moved
735 $fname = $file['name'];
737 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
738 preg_match("/^([0-9]+)_/",basename_international($fname),$patient_match);
739 if ($patient_match[1] == $file['patient_id']) {
740 $fname = preg_replace("/^([0-9]+)_/","",$fname);
743 //filenames should not have funny chars
744 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
746 //see if there is an existing file with the same name and rename as necessary
747 if (file_exists($new_path.$file['name'])) {
748 $messages .= "File with same name already exists at location: " . $new_path . "\n";
749 $fname = basename_international($this->_rename_file($new_path.$file['name']));
750 $messages .= "Current file name was changed to " . $fname ."\n";
753 //now move the file
754 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
755 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
756 $d->url = "file://" .$new_path.$fname;
757 $d->set_foreign_id($file['patient_id']);
758 $d->set_mimetype($mimetype);
759 $d->persist();
760 $d->populate();
762 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
763 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
764 $d->_db->Execute($sql);
767 else {
768 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
771 $this->assign("messages",$messages);
772 $_POST['process'] = "";
775 function move_action_process($patient_id="",$document_id) {
776 if ($_POST['process'] != "true")
777 return;
779 $new_category_id = $_POST['new_category_id'];
780 $new_patient_id = $_POST['new_patient_id'];
782 //move to new category
783 if (is_numeric($new_category_id) && is_numeric($document_id)) {
784 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
785 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
786 //echo $sql;
787 $this->tree->_db->Execute($sql);
790 //move to new patient
791 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
792 $d = new Document($document_id);
793 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
794 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
795 $result = $d->_db->Execute($sql);
797 if (!$result || $result->EOF) {
798 //patient id does not exist
799 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
801 else {
802 $couchsavefailed = !$d->change_patient($new_patient_id);
804 $this->_state = false;
805 if(!$couchsavefailed){
807 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
809 else{
811 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
813 $this->assign("messages",$messages);
814 return $this->list_action($patient_id);
817 //in this case return the document to the queue instead of moving it
818 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
819 $d = new Document($document_id);
820 $new_path = $this->_config['repository'];
821 $fname = $d->get_url_file();
823 //see if there is an existing file with the same name and rename as necessary
824 if (file_exists($new_path.$d->get_url_file())) {
825 $messages .= "File with same name already exists in the queue.\n";
826 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
827 $messages .= "Current file name was changed to " . $fname ."\n";
830 //now move the file
831 if (rename($d->get_url_filepath(),$new_path.$fname)) {
832 $d->url = "file://" .$new_path.$fname;
833 $d->set_foreign_id("");
834 $d->persist();
835 $d->persist();
836 $d->populate();
838 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
839 $d->_db->Execute($sql);
840 $messages .= "Document returned to queue successfully.\n";
843 else {
844 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
847 $this->_state = false;
848 $this->assign("messages",$messages);
849 return $this->list_action($patient_id);
852 $this->_state = false;
853 $this->assign("messages",$messages);
854 return $this->view_action($patient_id,$document_id);
857 function validate_action_process($patient_id="", $document_id) {
859 $d = new Document($document_id);
860 if($d->couch_docid && $d->couch_revid){
861 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
862 $url = $file_path.$d->get_url();
863 $couch = new CouchDB();
864 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
865 $resp = $couch->retrieve_doc($data);
866 $content = $resp->data;
867 //--------Temporarily writing the file for calculating the hash--------//
868 //-----------Will be removed after calculating the hash value----------//
869 $temp_file = fopen($url,"w");
870 fwrite($temp_file,base64_decode($content));
871 fclose($temp_file);
873 else{
874 $url = $d->get_url();
876 //strip url of protocol handler
877 $url = preg_replace("|^(.*)://|","",$url);
879 //change full path to current webroot. this is for documents that may have
880 //been moved from a different filesystem and the full path in the database
881 //is not current. this is also for documents that may of been moved to
882 //different patients. Note that the path_depth is used to see how far down
883 //the path to go. For example, originally the path_depth was always 1, which
884 //only allowed things like documents/1/<file>, but now can have more structured
885 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
886 // etc.
887 // NOTE that $from_filename and basename($url) are the same thing
888 $from_all = explode("/",$url);
889 $from_filename = array_pop($from_all);
890 $from_pathname_array = array();
891 for ($i=0;$i<$d->get_path_depth();$i++) {
892 $from_pathname_array[] = array_pop($from_all);
894 $from_pathname_array = array_reverse($from_pathname_array);
895 $from_pathname = implode("/",$from_pathname_array);
896 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
897 if (file_exists($temp_url)) {
898 $url = $temp_url;
901 if ($_POST['process'] != "true") {
902 die("process is '" . $_POST['process'] . "', expected 'true'");
903 return;
906 $d = new Document( $document_id );
907 $current_hash = sha1_file( $url );
908 $messages = xl('Current Hash').": ".$current_hash."<br>";
909 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
910 if ( $d->get_hash() == '' ) {
911 $d->hash = $current_hash;
912 $d->persist();
913 $d->populate();
914 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
915 } else if ( $current_hash != $d->get_hash() ) {
916 $messages .= xl('Hash does not match. Data integrity has been compromised.');
917 } else {
918 $messages .= xl('Document passed integrity check.');
920 $this->_state = false;
921 $this->assign("messages", $messages);
922 if($d->couch_docid && $d->couch_revid){
923 //Removing the temporary file which is used to create the hash
924 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
926 return $this->view_action($patient_id, $document_id);
929 // Added by Rod for metadata update.
931 function update_action_process($patient_id="", $document_id) {
933 if ($_POST['process'] != "true") {
934 die("process is '" . $_POST['process'] . "', expected 'true'");
935 return;
938 $docdate = $_POST['docdate'];
939 $docname = $_POST['docname'];
940 $issue_id = $_POST['issue_id'];
942 if (is_numeric($document_id)) {
943 $messages = '';
944 $d = new Document( $document_id );
945 $file_name = $d->get_url_file();
946 if ( $docname != '' &&
947 $docname != $file_name ) {
948 // Ready to rename - check for relocation
949 $old_url = $this->_check_relocation($d->get_url());
950 $new_url = $this->_check_relocation($d->get_url(), null, $docname);
951 $messages .= sprintf("%s -> %s<br>", $old_url, $new_url);
952 if ( rename( $old_url, $new_url ) ) {
953 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
954 if ( file_exists( $old_url ) ) {
955 unlink( $old_url );
957 $d->url = $new_url;
958 $d->persist();
959 $d->populate();
960 $messages .= xl('Document successfully renamed.')."<br>";
961 } else {
962 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
966 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
967 $docdate = "'$docdate'";
968 } else {
969 $docdate = "NULL";
971 if (!is_numeric($issue_id)) {
972 $issue_id = 0;
974 $couch_docid = $d->get_couch_docid();
975 $couch_revid = $d->get_couch_revid();
976 if($couch_docid && $couch_revid ){
977 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
978 "list_id = '$issue_id' " .
979 "WHERE id = '$document_id'";
980 $this->tree->_db->Execute($sql);
983 else{
984 $sql = "UPDATE documents SET docdate = $docdate, " .
985 "list_id = '$issue_id' " .
986 "WHERE id = '$document_id'";
987 $this->tree->_db->Execute($sql);
989 $messages .= xl('Document date and issue updated successfully') . "<br>";
992 $this->_state = false;
993 $this->assign("messages", $messages);
994 return $this->view_action($patient_id, $document_id);
997 function list_action($patient_id = "") {
998 $this->_last_node = null;
999 $categories_list = $this->tree->_get_categories_array($patient_id);
1000 //print_r($categories_list);
1002 $menu = new HTML_TreeMenu();
1003 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
1004 $menu->addItem($rnode);
1005 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1006 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1008 $this->assign("tree_html",$treeMenu->toHTML());
1010 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1013 /* This is a recursive function to rename a file to something that doesn't already exist.
1014 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1015 * at end) to ensure documents opened correctly by external browser viewers. If the
1016 * counter is at the end of the file, then will use it (to continue to work with older
1017 * files), however all new counters will be placed within filenames.
1019 * Modified to only deal with base file name when renaming, to avoid issues with directory
1020 * names with dots.
1022 function _rename_file($fname, $self=FALSE) {
1023 // Allow same routine for new file name check
1024 if (!file_exists($fname)) return($fname);
1026 $path = dirname($fname);
1027 $file = basename_international($fname);
1029 $fparts = explode(".",$file);
1030 switch (count($fparts)) {
1031 case 1:
1032 // Has a single node (base file name). Create counter node with value 0
1033 $fparts[1] = '1';
1034 break;
1035 case 2:
1036 // If 2nd node is numeric, assume it is counter and add 1 else insert counter
1037 if (is_numeric($fparts[1])) {
1038 $fparts[1] += 1;
1039 } else {
1040 array_push($fparts, $fparts[1]);
1041 $fparts[1] = '1';
1043 break;
1044 default:
1045 // Multiple nodes
1046 $ix_end = count($fparts) - 1;
1047 if (is_numeric($fparts[$ix_end]) && !is_numeric($fparts[$ix_end - 1])) {
1048 // Switch old style to new and check again
1049 $wrk = $fparts[$ix_end - 1];
1050 $fparts[$ix_end - 1] = $fparts[$ix_end];
1051 $fparts[$ix_end] = $wrk;
1052 } else if (is_numeric($fparts[$ix_end - 1])) {
1053 $fparts[$ix_end - 1] += 1;
1054 } else {
1055 array_push($fparts, $fparts[$ix_end]);
1056 $fparts[$ix_end] = '1';
1058 break;
1061 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1063 if (file_exists($fname)) {
1064 return $this->_rename_file($fname, TRUE);
1065 } else {
1066 return($fname);
1070 function &_array_recurse($array,$categories = array()) {
1071 if (!is_array($array)) {
1072 $array = array();
1074 $node = &$this->_last_node;
1075 $current_node = &$node;
1076 $expandedIcon = 'folder-expanded.gif';
1077 foreach($array as $id => $ar) {
1078 $icon = 'folder.gif';
1079 if (is_array($ar) || !empty($id)) {
1080 if ($node == null) {
1081 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1082 $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));
1083 $this->_last_node = &$rnode;
1084 $node = &$rnode;
1085 $current_node = &$rnode;
1087 else {
1088 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1089 $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)));
1090 $current_node = &$this->_last_node;
1093 $this->_array_recurse($ar,$categories);
1095 else {
1096 if ($id === 0 && !empty($ar)) {
1097 $info = $this->tree->get_node_info($id);
1098 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1099 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1101 else {
1102 //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
1103 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1104 if ($id !== 0 && is_object($node)) {
1105 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1106 $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)));
1112 // If there are documents in this document category, then add their
1113 // attributes to the current node.
1114 $icon = "file3.png";
1115 if (is_array($categories[$id])) {
1116 foreach ($categories[$id] as $doc) {
1117 $link = $this->_link("view") . "doc_id=" . $doc['document_id'] . "&";
1118 // If user has no access then there will be no link.
1119 if (!acl_check_aco_spec($doc['aco_spec'])) $link = '';
1120 if($this->tree->get_node_name($id) == "CCR"){
1121 $current_node->addItem(new HTML_TreeNode(array(
1122 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1123 'link' => $link,
1124 'icon' => $icon,
1125 'expandedIcon' => $expandedIcon,
1126 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1127 )));
1128 }elseif($this->tree->get_node_name($id) == "CCD"){
1129 $current_node->addItem(new HTML_TreeNode(array(
1130 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1131 'link' => $link,
1132 'icon' => $icon,
1133 'expandedIcon' => $expandedIcon,
1134 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1135 )));
1136 }else{
1137 $current_node->addItem(new HTML_TreeNode(array(
1138 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1139 'link' => $link,
1140 'icon' => $icon,
1141 'expandedIcon' => $expandedIcon
1142 )));
1148 return $node;
1151 //function for logging the errors in writing file to CouchDB/Hard Disk
1152 function document_upload_download_log($patientid,$content){
1153 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1154 $log_file = 'log.txt';
1155 if(!is_dir($log_path))
1156 mkdir($log_path,0777,true);
1157 $LOG = fopen($log_path.$log_file,'a');
1158 fwrite($LOG,$content);
1159 fclose($LOG);
1162 function document_send($email,$body,$attfile,$pname) {
1163 if (empty($email)) {
1164 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1165 return;
1168 $desc = "Please check the attached patient document.\n Content:".attr($body);
1169 $mail = new MyMailer();
1170 $from_name = $GLOBALS["practice_return_email_path"];
1171 $from = $GLOBALS["practice_return_email_path"];
1172 $mail->AddReplyTo($from,$from_name);
1173 $mail->SetFrom($from,$from );
1174 $to = $email ; $to_name =$email;
1175 $mail->AddAddress($to, $to_name);
1176 $subject = "Patient documents";
1177 $mail->Subject = $subject;
1178 $mail->Body = $desc;
1179 $mail->AddAttachment($attfile);
1180 if ($mail->Send()) {
1181 $retstatus = "email_sent";
1182 } else {
1183 $email_status = $mail->ErrorInfo;
1184 //echo "EMAIL ERROR: ".$email_status;
1185 $retstatus = "email_fail";
1189 //place to hold optional code
1190 //$first_node = array_keys($t->tree);
1191 //$first_node = $first_node[0];
1192 //$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')"));
1194 //$this->_last_node = &$node1;
1196 // Function to tag a document to an encounter.
1197 function tag_action_process($patient_id="", $document_id) {
1198 if ($_POST['process'] != "true") {
1199 die("process is '" . text($_POST['process']) . "', expected 'true'");
1200 return;
1203 // Create Encounter and Tag it.
1204 $event_date = date('Y-m-d H:i:s');
1205 $encounter_id = $_POST['encounter_id'];
1206 $encounter_check = $_POST['encounter_check'];
1207 $visit_category_id = $_POST['visit_category_id'];
1209 if (is_numeric($document_id)) {
1210 $messages = '';
1211 $d = new Document( $document_id );
1212 $file_name = $d->get_url_file();
1213 if (!is_numeric($encounter_id)) {
1214 $encounter_id = 0;
1217 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1218 if ($encounter_check) {
1219 $provider_id = $_SESSION['authUserID'] ;
1221 // Get the logged in user's facility
1222 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1223 $username = $facilityRow['username'];
1224 $facility = $facilityRow['facility'];
1225 $facility_id = $facilityRow['facility_id'];
1226 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1227 $billingFacility = $this->facilityService->getPrimaryBusinessEntity();
1228 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1230 $conn = $GLOBALS['adodb']['db'];
1231 $encounter = $conn->GenID("sequences");
1232 $query = "INSERT INTO form_encounter SET
1233 date = ?,
1234 reason = ?,
1235 facility = ?,
1236 sensitivity = 'normal',
1237 pc_catid = ?,
1238 facility_id = ?,
1239 billing_facility = ?,
1240 provider_id = ?,
1241 pid = ?,
1242 encounter = ?";
1243 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1244 $formID = sqlInsert($query,$bindArray);
1245 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1246 $d->set_encounter_id($encounter);
1247 $this->image_result_indication($d->id, $encounter);
1249 } else {
1250 $d->set_encounter_id($encounter_id);
1251 $this->image_result_indication($d->id, $encounter_id);
1253 $d->set_encounter_check($encounter_check);
1254 $d->persist();
1256 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1259 $this->_state = false;
1260 $this->assign("messages", $messages);
1262 return $this->view_action($patient_id, $document_id);
1265 function image_procedure_action($patient_id="",$document_id){
1267 $img_procedure_id = $_POST['image_procedure_id'];
1268 $proc_code = $_POST['procedure_code'];
1270 if(is_numeric($document_id)){
1272 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ",array($img_procedure_id,$proc_code));
1273 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ",array($img_procedure_id,$img_order['procedure_order_seq']));
1274 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1275 if($img_report_id == 0){
1276 $report_date = date('Y-m-d H:i:s');
1277 $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));
1280 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?",array($img_report_id,$document_id));
1281 if(empty($img_result)){
1282 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));
1285 $this->image_result_indication($document_id, 0,$img_procedure_id);
1287 return $this->view_action($patient_id, $document_id);
1290 function clear_procedure_tag_action($patient_id="",$document_id){
1291 if(is_numeric($document_id)){
1292 sqlStatement("delete from procedure_result where document_id = ?",$document_id);
1294 return $this->view_action($patient_id, $document_id);
1297 function get_mapped_procedure($document_id){
1298 $map = array();
1299 if(is_numeric($document_id)){
1300 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1301 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1302 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1303 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1304 where pres.document_id = ?",array($document_id));
1306 return $map;
1309 function image_result_indication($doc_id,$encounter,$image_procedure_id = 0){
1310 $doc_notes = sqlQuery("select note from notes where foreign_id = ?",array($doc_id));
1311 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1313 if($encounter != 0) {
1314 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?",array($encounter));
1316 else if($image_procedure_id != 0){
1317 $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));
1319 else{
1320 $ep = array('assigned_to' => $_SESSION['authUser']);
1323 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1324 $noteid = addPnote($_SESSION['pid'],'New Image Report received '.$narration,0,1,'Image Results',$encounter_provider,'','New','');
1325 setGpRelation(1, $doc_id, 6, $noteid);
1328 /** Function to accomodate the relocation of entire "documents" folder to another host or filesystem **
1329 * Also usable for documents that may of been moved to different patients.
1331 * @param string $url - Current url string from database.
1332 * @param string $new_pid - Include pid corrections to receive corrected url during move operation.
1333 * @param string $new_name - Include name corrections to receive corrected url during rename operation.
1335 * @return string
1337 function _check_relocation($url, $new_pid = null, $new_name = null) {
1338 //strip url of protocol handler
1339 $url = preg_replace("|^(.*)://|","",$url);
1340 $fsnodes = explode(DIRECTORY_SEPARATOR, $url);
1341 while (current($fsnodes) != "documents") {
1342 array_shift($fsnodes);
1344 if ($new_pid) {
1345 $fsnodes[1] = $new_pid;
1347 if ($new_name) {
1348 $fsnodes[count($fsnodes)-1] = $new_name;
1350 $url = $GLOBALS['OE_SITE_DIR'].DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $fsnodes);
1351 // Make sure the url is available after corrections
1352 if ($new_pid || $new_name) {
1353 $url = $this->_rename_file($url);
1355 //Add full path and remaining nodes
1356 return $url;
1359 //clear encounter tag function
1360 function clear_encounter_tag_action($patient_id="",$document_id)
1362 if (is_numeric($document_id)) {
1363 sqlStatement("update documents set encounter_id='0' where foreign_id=? and id = ?",array($patient_id,$document_id));
1365 return $this->view_action($patient_id, $document_id);