path fix for public images
[openemr.git] / controllers / C_Document.class.php
blobd04cf11dc4b6aff69bdfb0344e007becfdb05732
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/classes/Controller.class.php");
8 require_once(dirname(__FILE__) . "/../library/classes/Document.class.php");
9 require_once(dirname(__FILE__) . "/../library/classes/CategoryTree.class.php");
10 require_once(dirname(__FILE__) . "/../library/classes/TreeMenu.php");
11 require_once(dirname(__FILE__) . "/../library/classes/Note.class.php");
12 require_once(dirname(__FILE__) . "/../library/classes/CouchDB.class.php");
13 require_once(dirname(__FILE__) . "/../library/forms.inc");
14 require_once(dirname(__FILE__) . "/../library/formatting.inc.php");
15 require_once(dirname(__FILE__) . "/../library/classes/postmaster.php" );
17 class C_Document extends Controller {
19 var $template_mod;
20 var $documents;
21 var $document_categories;
22 var $tree;
23 var $_config;
24 var $manual_set_owner=false; // allows manual setting of a document owner/service
26 function __construct($template_mod = "general") {
27 parent::__construct();
28 $this->documents = array();
29 $this->template_mod = $template_mod;
30 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
31 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
33 //get global config options for this namespace
34 $this->_config = $GLOBALS['oer_config']['documents'];
36 $this->_args = array("patient_id" => $_GET['patient_id']);
38 $this->assign("STYLE", $GLOBALS['style']);
39 $t = new CategoryTree(1);
40 //print_r($t->tree);
41 $this->tree = $t;
42 $this->Document = new Document();
45 function upload_action($patient_id,$category_id) {
46 $category_name = $this->tree->get_node_name($category_id);
47 $this->assign("category_id", $category_id);
48 $this->assign("category_name", $category_name);
49 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
50 $this->assign("patient_id", $patient_id);
52 // Added by Rod to support document template download from general_upload.html.
53 // Cloned from similar stuff in manage_document_templates.php.
54 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
55 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
56 if (file_exists($templatedir)) {
57 $dh = opendir($templatedir);
59 if ($dh) {
60 $templateslist = array();
61 while (false !== ($sfname = readdir($dh))) {
62 if (substr($sfname, 0, 1) == '.') continue;
63 $templateslist[$sfname] = $sfname;
65 closedir($dh);
66 ksort($templateslist);
67 foreach ($templateslist as $sfname) {
68 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES) .
69 "'>" . htmlspecialchars($sfname) . "</option>";
72 $this->assign("TEMPLATES_LIST", $templates_options);
74 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
75 $this->assign("activity", $activity);
76 return $this->list_action($patient_id);
79 //Upload multiple files on single click
80 function upload_action_process() {
82 // Collect a manually set owner if this has been set
83 // Used when want to manually assign the owning user/service such as the Direct mechanism
84 $non_HTTP_owner=false;
85 if ($this->manual_set_owner) {
86 $non_HTTP_owner=$this->manual_set_owner;
89 $couchDB = false;
90 $harddisk = false;
91 if($GLOBALS['document_storage_method']==0){
92 $harddisk = true;
94 if($GLOBALS['document_storage_method']==1){
95 $couchDB = true;
98 if ($_POST['process'] != "true")
99 return;
101 $doDecryption = false;
102 $encrypted = $_POST['encrypted'];
103 $passphrase = $_POST['passphrase'];
104 if ( !$GLOBALS['hide_document_encryption'] &&
105 $encrypted && $passphrase ) {
106 $doDecryption = true;
109 if (is_numeric($_POST['category_id'])) {
110 $category_id = $_POST['category_id'];
113 $patient_id = 0;
114 if (isset($_GET['patient_id']) && !$couchDB) {
115 $patient_id = $_GET['patient_id'];
117 else if (is_numeric($_POST['patient_id'])) {
118 $patient_id = $_POST['patient_id'];
121 $sentUploadStatus = array();
122 if( count($_FILES['file']['name']) > 0){
123 $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 = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
133 if ($_FILES['file']['size'][$key] == 0) {
134 $error .= "The system does not permit uploading files of with size 0.\n";
136 }else{
137 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
138 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
139 fclose($tmpfile);
140 if ($doDecryption) {
141 $filetext = $this->decrypt($filetext, $passphrase);
143 if ( $_POST['destination'] != '' ) {
144 $fname = $_POST['destination'];
146 $d = new Document();
147 $rc = $d->createDocument($patient_id, $category_id, $fname,
148 $_FILES['file']['type'][$key], $filetext,
149 empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],
150 empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],
151 $non_HTTP_owner, $_FILES['file']['tmp_name'][$key]);
152 if ($rc) {
153 $error .= $rc . "\n";
155 else {
156 $this->assign("upload_success", "true");
158 $sentUploadStatus[] = $d;
159 $this->assign("file", $sentUploadStatus);
162 // Option to run a custom plugin for each file upload.
163 // This was initially created to delete the original source file in a custom setting.
164 $upload_plugin = $GLOBALS['OE_SITE_DIR'] . "/documentUpload.plugin.php";
165 if (file_exists($upload_plugin)) {
166 include_once($upload_plugin);
168 $upload_plugin_pp = 'documentUploadPostProcess';
169 if (function_exists($upload_plugin_pp)) {
170 $tmp = call_user_func($upload_plugin_pp, $value, $d);
171 if ($tmp) {
172 $error = $tmp;
175 // Following is just an example of code in such a plugin file.
176 /*****************************************************
177 function documentUploadPostProcess($filename, &$d) {
178 $userid = $_SESSION['authUserID'];
179 $row = sqlQuery("SELECT username FROM users WHERE id = ?", array($userid));
180 $owner = strtolower($row['username']);
181 $dn = '1_' . ucfirst($owner);
182 $filepath = "/shared_network_directory/$dn/$filename";
183 if (@unlink($filepath)) return '';
184 return "Failed to delete '$filepath'.";
186 *****************************************************/
191 $this->assign("error", nl2br($error));
192 //$this->_state = false;
193 $_POST['process'] = "";
194 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
197 function note_action_process($patient_id) {
198 // this function is a dual function that will set up a note associated with a document or send a document via email.
200 if ($_POST['process'] != "true")
201 return;
203 $n = new Note();
204 $n->set_owner($_SESSION['authUserID']);
205 parent::populate_object($n);
206 if ($_POST['identifier'] == "no"){
207 // associate a note with a document
208 $n->persist();
209 }elseif ($_POST['identifier'] == "yes"){
210 // send the document via email
211 $d = new Document($_POST['foreign_id']);
212 $url = $d->get_url();
213 $storagemethod = $d->get_storagemethod();
214 $couch_docid = $d->get_couch_docid();
215 $couch_revid = $d->get_couch_revid();
216 if($couch_docid && $couch_revid){
217 $couch = new CouchDB();
218 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
219 $resp = $couch->retrieve_doc($data);
220 $content = $resp->data;
221 if($content=='' && $GLOBALS['couchdb_log']==1){
222 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
223 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
224 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
225 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
226 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
227 //$log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
228 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
229 die(xlt("File retrieval from CouchDB failed"));
231 // place it in a temporary file and will remove the file below after emailed
232 $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
233 $fh = fopen($temp_couchdb_url,"w");
234 fwrite($fh,base64_decode($content));
235 fclose($fh);
236 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
237 } else {
238 $url = preg_replace("|^(.*)://|","",$url);
239 // Collect filename and path
240 $from_all = explode("/",$url);
241 $from_filename = array_pop($from_all);
242 $from_pathname_array = array();
243 for ($i=0;$i<$d->get_path_depth();$i++) {
244 $from_pathname_array[] = array_pop($from_all);
246 $from_pathname_array = array_reverse($from_pathname_array);
247 $from_pathname = implode("/",$from_pathname_array);
248 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
250 if (!file_exists($temp_url)) {
251 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;
253 $url = $temp_url;
254 $body_notes = attr($_POST['note']);
255 $pdetails = getPatientData($patient_id);
256 $pname = $pdetails['fname']." ".$pdetails['lname'];
257 $this->document_send($_POST['provide_email'],$body_notes,$url,$pname);
258 if ($couch_docid && $couch_revid) {
259 // remove the temporary couchdb file
260 unlink($temp_couchdb_url);
263 $this->_state = false;
264 $_POST['process'] = "";
265 return $this->view_action($patient_id,$n->get_foreign_id());
268 function default_action() {
269 return $this->list_action();
272 function view_action($patient_id="",$doc_id) {
273 // Added by Rod to support document delete:
274 global $gacl_object, $phpgacl_location;
275 global $ISSUE_TYPES;
277 require_once(dirname(__FILE__) . "/../library/acl.inc");
278 require_once(dirname(__FILE__) . "/../library/lists.inc");
280 $d = new Document($doc_id);
281 $n = new Note();
283 $notes = $n->notes_factory($doc_id);
285 $this->assign("file", $d);
286 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
287 $this->assign("NOTE_ACTION",$this->_link("note"));
288 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
289 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
291 // Added by Rod to support document delete:
292 $delete_string = '';
293 if (acl_check('admin', 'super')) {
294 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
295 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
297 $this->assign("delete_string", $delete_string);
298 $this->assign("REFRESH_ACTION",$this->_link("list"));
300 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
301 "document_id=" . $d->get_id() . "&process=true");
303 // Added by Rod to support document date update:
304 $this->assign("DOCDATE", $d->get_docdate());
305 $this->assign("UPDATE_ACTION",$this->_link("update") .
306 "document_id=" . $d->get_id() . "&process=true");
308 // Added by Rod to support document issue update:
309 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
310 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
311 "pid = ? " . // AND enddate IS NULL " .
312 "ORDER BY type, begdate", array($patient_id) );
313 while ($irow = sqlFetchArray($ires)) {
314 $desc = $irow['type'];
315 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
316 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
317 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
318 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
320 $this->assign("ISSUES_LIST", $issues_options);
322 // For tagging to encounter
323 // Populate the dropdown with patient's encounter list
324 $this->assign("TAG_ACTION",$this->_link("tag") . "document_id=" . $d->get_id() . "&process=true");
325 $encOptions = "<option value='0'>-- " . xlt('Select Encounter') . " --</option>";
326 $result_docs = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
327 "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));
328 if ( sqlNumRows($result_docs) > 0)
329 while($row_result_docs = sqlFetchArray($result_docs)) {
330 $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';
331 $encOptions .= "<option value='" . attr($row_result_docs['encounter']) . "' $sel_enc>". oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date']))) . "-" . text($row_result_docs['pc_catname'])."</option>";
333 $this->assign("ENC_LIST", $encOptions);
335 //Populate the dropdown with category list
336 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
337 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
338 while ($crow = sqlFetchArray($cres)) {
339 $catid = $crow['pc_catid'];
340 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
341 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
343 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
345 $this->assign("notes",$notes);
347 $this->assign("IMG_PROCEDURE_TAG_ACTION",$this->_link("image_procedure") . "document_id=" . $d->get_id());
348 // Populate the dropdown with image procedure order list
349 $imgOptions = "<option value='0'>-- " . xlt('Select Image Procedure') . " --</option>";
350 $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));
351 $mapping = $this->get_mapped_procedure($d->get_id());
352 if(sqlNumRows($imgOrders) > 0){
353 while($row = sqlFetchArray($imgOrders)) {
354 $sel_proc = '';
355 if((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id']))
356 $sel_proc = 'selected';
357 $imgOptions .= "<option value='". attr($row['procedure_order_id']). "' data-code='".attr($row['procedure_code'])."' $sel_proc>".text($row['procedure_name'].' - '.$row['procedure_code'])."</option>";
361 $this->assign('IMAGE_PROCEDURE_LIST',$imgOptions);
363 $this->assign('clear_procedure_tag',$this->_link('clear_procedure_tag')."document_id=" . $d->get_id());
365 $this->_last_node = null;
367 $menu = new HTML_TreeMenu();
369 //pass an empty array because we don't want the documents for each category showing up in this list box
370 $rnode = $this->_array_recurse($this->tree->tree,array());
371 $menu->addItem($rnode);
372 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
374 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
376 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
377 $this->assign("activity", $activity);
379 return $this->list_action($patient_id);
382 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
384 $td = mcrypt_module_open( $cypher, '', $mode, '');
385 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
386 mcrypt_generic_init( $td, $key, $iv );
387 $crypttext = mcrypt_generic( $td, $plaintext );
388 mcrypt_generic_deinit( $td );
389 return $iv.$crypttext;
392 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
394 $plaintext = '';
395 $td = mcrypt_module_open( $cypher, '', $mode, '' );
396 $ivsize = mcrypt_enc_get_iv_size( $td) ;
397 $iv = substr( $crypttext, 0, $ivsize );
398 $crypttext = substr( $crypttext, $ivsize );
399 if( $iv )
401 mcrypt_generic_init( $td, $key, $iv );
402 $plaintext = mdecrypt_generic( $td, $crypttext );
404 return $plaintext;
408 * Retrieve file from hard disk / CouchDB.
409 * In case that file isn't download this function will return thumbnail image (if exist).
410 * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.
411 * */
412 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false,$show_original=false) {
414 $encrypted = $_POST['encrypted'];
415 $passphrase = $_POST['passphrase'];
416 $doEncryption = false;
417 if ( !$GLOBALS['hide_document_encryption'] &&
418 $encrypted == "true" &&
419 $passphrase ) {
420 $doEncryption = true;
423 //controller function ruins booleans, so need to manually re-convert to booleans
424 if ($as_file == "true") {
425 $as_file=true;
427 else if ($as_file == "false") {
428 $as_file=false;
430 if ($original_file == "true") {
431 $original_file=true;
433 else if ($original_file == "false") {
434 $original_file=false;
436 if ($disable_exit == "true") {
437 $disable_exit=true;
439 else if ($disable_exit == "false") {
440 $disable_exit=false;
442 if ($show_original == "true") {
443 $show_original=true;
445 else if ($show_original == "false") {
446 $show_original=false;
449 $d = new Document($document_id);
450 $url = $d->get_url();
451 $th_url = $d->get_thumb_url();
453 $storagemethod = $d->get_storagemethod();
454 $couch_docid = $d->get_couch_docid();
455 $couch_revid = $d->get_couch_revid();
457 if($couch_docid && $couch_revid && $original_file){
458 $couch = new CouchDB();
459 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
460 $resp = $couch->retrieve_doc($data);
461 //Take thumbnail file when is not null and file is presented online
462 if (!$as_file && !is_null($th_url) && !$show_original) {
463 $content = $resp->th_data;
464 } else {
465 $content = $resp->data;
467 if($content=='' && $GLOBALS['couchdb_log']==1){
468 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
469 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
470 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
471 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
472 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
473 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
474 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
475 die(xl("File retrieval from CouchDB failed"));
477 if($disable_exit == true) {
478 return base64_decode($content);
480 header('Content-Description: File Transfer');
481 header('Content-Transfer-Encoding: binary');
482 header('Expires: 0');
483 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
484 header('Pragma: public');
485 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
486 $fh = fopen($tmpcouchpath,"w");
487 fwrite($fh,base64_decode($content));
488 fclose($fh);
489 $f = fopen($tmpcouchpath,"r");
490 if ( $doEncryption ) {
491 $filetext = fread( $f, filesize($tmpcouchpath) );
492 $ciphertext = $this->encrypt( $filetext, $passphrase );
493 $tmpfilepath = $GLOBALS['temporary_files_dir'];
494 $tmpfilename = "/encrypted_".$d->get_url_file();
495 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
496 fwrite( $tmpfile, $ciphertext );
497 fclose( $tmpfile );
498 header('Content-Disposition: attachment; filename='.$tmpfilename );
499 header("Content-Type: application/octet-stream" );
500 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
501 ob_clean();
502 flush();
503 readfile( $tmpfilepath.$tmpfilename );
504 unlink( $tmpfilepath.$tmpfilename );
505 } else {
506 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
507 header("Content-Type: " . $d->get_mimetype());
508 header("Content-Length: " . filesize($tmpcouchpath));
509 fpassthru($f);
511 fclose($f);
512 if($content!='')
513 unlink($tmpcouchpath);
514 exit;//exits only if file download from CouchDB is successfull.
517 //Take thumbnail file when is not null and file is presented online
518 if(!$as_file && !is_null($th_url) && !$show_original) {
519 $url = $th_url;
522 //strip url of protocol handler
523 $url = preg_replace("|^(.*)://|","",$url);
525 //change full path to current webroot. this is for documents that may have
526 //been moved from a different filesystem and the full path in the database
527 //is not current. this is also for documents that may of been moved to
528 //different patients. Note that the path_depth is used to see how far down
529 //the path to go. For example, originally the path_depth was always 1, which
530 //only allowed things like documents/1/<file>, but now can have more structured
531 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
532 // etc.
533 // NOTE that $from_filename and basename($url) are the same thing
534 $from_all = explode("/",$url);
535 $from_filename = array_pop($from_all);
536 $from_pathname_array = array();
537 for ($i=0;$i<$d->get_path_depth();$i++) {
538 $from_pathname_array[] = array_pop($from_all);
540 $from_pathname_array = array_reverse($from_pathname_array);
541 $from_pathname = implode("/",$from_pathname_array);
542 if($couch_docid && $couch_revid){
543 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
544 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
547 else{
548 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
551 if (file_exists($temp_url)) {
552 $url = $temp_url;
556 if (!file_exists($url)) {
557 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;
560 else {
561 if ($original_file) {
562 //normal case when serving the file referenced in database
563 if($disable_exit == true) {
564 $f = fopen($url,"r");
565 $filetext = fread( $f, filesize($url) );
566 return $filetext;
568 header('Content-Description: File Transfer');
569 header('Content-Transfer-Encoding: binary');
570 header('Expires: 0');
571 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
572 header('Pragma: public');
573 $f = fopen($url,"r");
574 if ( $doEncryption ) {
575 $filetext = fread( $f, filesize($url) );
576 $ciphertext = $this->encrypt( $filetext, $passphrase );
577 $tmpfilepath = $GLOBALS['temporary_files_dir'];
578 $tmpfilename = "/encrypted_".$d->get_url_file();
579 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
580 fwrite( $tmpfile, $ciphertext );
581 fclose( $tmpfile );
582 header('Content-Disposition: attachment; filename='.$tmpfilename );
583 header("Content-Type: application/octet-stream" );
584 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
585 ob_clean();
586 flush();
587 readfile( $tmpfilepath.$tmpfilename );
588 unlink( $tmpfilepath.$tmpfilename );
589 } else {
590 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($d->get_url()) . "\"");
591 header("Content-Type: " . $d->get_mimetype());
592 header("Content-Length: " . filesize($url));
593 fpassthru($f);
595 exit;
597 else {
598 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
599 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
600 if($couch_docid && $couch_revid){
601 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
603 else{
604 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
606 if($disable_exit == true) {
607 return ;
609 header("Pragma: public");
610 header("Expires: 0");
611 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
612 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename_international($url) . "\"");
613 header("Content-Type: image/jpeg");
614 header("Content-Length: " . filesize($url));
615 $f = fopen($url,"r");
616 fpassthru($f);
617 if($couch_docid && $couch_revid){
618 fclose($f);
619 unlink($url);
620 $url=str_replace("_converted.jpg",'.pdf',$url);
621 unlink($url);
623 exit;
628 function queue_action($patient_id="") {
629 $messages = $this->_tpl_vars['messages'];
630 $queue_files = array();
632 //see if the repository exists and it is a directory else error
633 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
634 $dir = opendir($this->_config['repository']);
635 //read each entry in the directory
636 while (($file = readdir($dir)) !== false) {
637 //concat the filename and path
638 $file = $this->_config['repository'] .$file;
639 $file_info = array();
640 //if the filename is a file get its info and put into a tmp array
641 if (is_file($file) && strpos(basename_international($file),".") !== 0) {
642 $file_info['filename'] = basename_international($file);
643 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
644 $d = $this->Document->document_factory_url("file://" . $file);
645 preg_match("/^([0-9]+)_/",basename_international($file),$patient_match);
646 $file_info['patient_id'] = $patient_match[1];
647 $file_info['document_id'] = $d->get_id();
648 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
650 //merge the tmp array into the larger array
651 $queue_files[] = $file_info;
654 closedir($dir);
656 else {
657 $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";
661 $this->assign("queue_files",$queue_files);
662 $this->_last_node = null;
664 $menu = new HTML_TreeMenu();
666 //pass an empty array because we don't want the documents for each category showing up in this list box
667 $rnode = $this->_array_recurse($this->tree->tree,array());
668 $menu->addItem($rnode);
669 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array());
671 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
673 $this->assign("messages",nl2br($messages));
674 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
677 function queue_action_process() {
678 if ($_POST['process'] != "true")
679 return;
681 $messages = $this->_tpl_vars['messages'];
683 //build a category tree so we can have a list of category ids that are valid
684 $ct = new CategoryTree(1);
685 $categories = $ct->_id_name;
687 //see if there were and posted files and assign them
688 $files = null;
689 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
691 //loop through posted files
692 foreach($files as $doc_id=> $file) {
693 //only operate on files checked as active
694 if (!$file['active']) continue;
696 //run basic validation checks
697 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
698 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
699 continue;
702 //validate that the pod exists
703 $d = new Document($doc_id);
704 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
705 $result = $d->_db->Execute($sql);
707 if (!$result || $result->EOF) {
708 //patient id does not exist
709 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
710 continue;
713 //validate that the category id exists
714 if (!isset($categories[$file['category_id']])) {
715 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
716 continue;
719 //now do the work of moving the file
720 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
722 //see if the patient dir exists in the repository and create if not
723 if (!file_exists($new_path)) {
724 if (!mkdir($new_path,0700)) {
725 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
726 continue;
730 //fname is the name of the file after it is moved
731 $fname = $file['name'];
733 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
734 preg_match("/^([0-9]+)_/",basename_international($fname),$patient_match);
735 if ($patient_match[1] == $file['patient_id']) {
736 $fname = preg_replace("/^([0-9]+)_/","",$fname);
739 //filenames should not have funny chars
740 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
742 //see if there is an existing file with the same name and rename as necessary
743 if (file_exists($new_path.$file['name'])) {
744 $messages .= "File with same name already exists at location: " . $new_path . "\n";
745 $fname = basename_international($this->_rename_file($new_path.$file['name']));
746 $messages .= "Current file name was changed to " . $fname ."\n";
749 //now move the file
750 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
751 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
752 $d->url = "file://" .$new_path.$fname;
753 $d->set_foreign_id($file['patient_id']);
754 $d->set_mimetype($mimetype);
755 $d->persist();
756 $d->populate();
758 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
759 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
760 $d->_db->Execute($sql);
763 else {
764 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
767 $this->assign("messages",$messages);
768 $_POST['process'] = "";
771 function move_action_process($patient_id="",$document_id) {
772 if ($_POST['process'] != "true")
773 return;
775 $new_category_id = $_POST['new_category_id'];
776 $new_patient_id = $_POST['new_patient_id'];
778 //move to new category
779 if (is_numeric($new_category_id) && is_numeric($document_id)) {
780 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
781 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
782 //echo $sql;
783 $this->tree->_db->Execute($sql);
786 //move to new patient
787 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
788 $d = new Document($document_id);
789 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
790 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
791 $result = $d->_db->Execute($sql);
793 if (!$result || $result->EOF) {
794 //patient id does not exist
795 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
797 else {
798 $couchsavefailed = !$d->change_patient($new_patient_id);
800 $this->_state = false;
801 if(!$couchsavefailed){
803 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
805 else{
807 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
809 $this->assign("messages",$messages);
810 return $this->list_action($patient_id);
813 //in this case return the document to the queue instead of moving it
814 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
815 $d = new Document($document_id);
816 $new_path = $this->_config['repository'];
817 $fname = $d->get_url_file();
819 //see if there is an existing file with the same name and rename as necessary
820 if (file_exists($new_path.$d->get_url_file())) {
821 $messages .= "File with same name already exists in the queue.\n";
822 $fname = basename_international($this->_rename_file($new_path.$d->get_url_file()));
823 $messages .= "Current file name was changed to " . $fname ."\n";
826 //now move the file
827 if (rename($d->get_url_filepath(),$new_path.$fname)) {
828 $d->url = "file://" .$new_path.$fname;
829 $d->set_foreign_id("");
830 $d->persist();
831 $d->persist();
832 $d->populate();
834 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
835 $d->_db->Execute($sql);
836 $messages .= "Document returned to queue successfully.\n";
839 else {
840 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
843 $this->_state = false;
844 $this->assign("messages",$messages);
845 return $this->list_action($patient_id);
848 $this->_state = false;
849 $this->assign("messages",$messages);
850 return $this->view_action($patient_id,$document_id);
853 function validate_action_process($patient_id="", $document_id) {
855 $d = new Document($document_id);
856 if($d->couch_docid && $d->couch_revid){
857 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
858 $url = $file_path.$d->get_url();
859 $couch = new CouchDB();
860 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
861 $resp = $couch->retrieve_doc($data);
862 $content = $resp->data;
863 //--------Temporarily writing the file for calculating the hash--------//
864 //-----------Will be removed after calculating the hash value----------//
865 $temp_file = fopen($url,"w");
866 fwrite($temp_file,base64_decode($content));
867 fclose($temp_file);
869 else{
870 $url = $d->get_url();
872 //strip url of protocol handler
873 $url = preg_replace("|^(.*)://|","",$url);
875 //change full path to current webroot. this is for documents that may have
876 //been moved from a different filesystem and the full path in the database
877 //is not current. this is also for documents that may of been moved to
878 //different patients. Note that the path_depth is used to see how far down
879 //the path to go. For example, originally the path_depth was always 1, which
880 //only allowed things like documents/1/<file>, but now can have more structured
881 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
882 // etc.
883 // NOTE that $from_filename and basename($url) are the same thing
884 $from_all = explode("/",$url);
885 $from_filename = array_pop($from_all);
886 $from_pathname_array = array();
887 for ($i=0;$i<$d->get_path_depth();$i++) {
888 $from_pathname_array[] = array_pop($from_all);
890 $from_pathname_array = array_reverse($from_pathname_array);
891 $from_pathname = implode("/",$from_pathname_array);
892 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
893 if (file_exists($temp_url)) {
894 $url = $temp_url;
897 if ($_POST['process'] != "true") {
898 die("process is '" . $_POST['process'] . "', expected 'true'");
899 return;
902 $d = new Document( $document_id );
903 $current_hash = sha1_file( $url );
904 $messages = xl('Current Hash').": ".$current_hash."<br>";
905 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
906 if ( $d->get_hash() == '' ) {
907 $d->hash = $current_hash;
908 $d->persist();
909 $d->populate();
910 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
911 } else if ( $current_hash != $d->get_hash() ) {
912 $messages .= xl('Hash does not match. Data integrity has been compromised.');
913 } else {
914 $messages .= xl('Document passed integrity check.');
916 $this->_state = false;
917 $this->assign("messages", $messages);
918 if($d->couch_docid && $d->couch_revid){
919 //Removing the temporary file which is used to create the hash
920 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
922 return $this->view_action($patient_id, $document_id);
925 // Added by Rod for metadata update.
927 function update_action_process($patient_id="", $document_id) {
929 if ($_POST['process'] != "true") {
930 die("process is '" . $_POST['process'] . "', expected 'true'");
931 return;
934 $docdate = $_POST['docdate'];
935 $docname = $_POST['docname'];
936 $issue_id = $_POST['issue_id'];
938 if (is_numeric($document_id)) {
939 $messages = '';
940 $d = new Document( $document_id );
941 $file_name = $d->get_url_file();
942 if ( $docname != '' &&
943 $docname != $file_name ) {
944 $path = $d->get_url_filepath();
945 $path = str_replace( $file_name, "", $path );
946 $new_url = $this->_rename_file( $path.$docname );
947 if ( rename( $d->get_url(), $new_url ) ) {
948 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
949 $url = preg_replace("|^(.*)://|","",$d->get_url());
950 $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';
951 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
952 if ( file_exists( $url ) ) {
953 unlink( $url );
955 $d->url = $new_url;
956 $d->persist();
957 $d->populate();
958 $messages .= xl('Document successfully renamed.')."<br>";
959 } else {
960 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
964 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
965 $docdate = "'$docdate'";
966 } else {
967 $docdate = "NULL";
969 if (!is_numeric($issue_id)) {
970 $issue_id = 0;
972 $couch_docid = $d->get_couch_docid();
973 $couch_revid = $d->get_couch_revid();
974 if($couch_docid && $couch_revid ){
975 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
976 "list_id = '$issue_id' " .
977 "WHERE id = '$document_id'";
978 $this->tree->_db->Execute($sql);
981 else{
982 $sql = "UPDATE documents SET docdate = $docdate, " .
983 "list_id = '$issue_id' " .
984 "WHERE id = '$document_id'";
985 $this->tree->_db->Execute($sql);
987 $messages .= xl('Document date and issue updated successfully') . "<br>";
990 $this->_state = false;
991 $this->assign("messages", $messages);
992 return $this->view_action($patient_id, $document_id);
995 function list_action($patient_id = "") {
996 $this->_last_node = null;
997 $categories_list = $this->tree->_get_categories_array($patient_id);
998 //print_r($categories_list);
1000 $menu = new HTML_TreeMenu();
1001 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
1002 $menu->addItem($rnode);
1003 $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
1004 $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
1006 $this->assign("tree_html",$treeMenu->toHTML());
1008 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
1011 /* This is a recursive function to rename a file to something that doesn't already exist.
1012 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
1013 * at end) to ensure documents opened correctly by external browser viewers. If the
1014 * counter is at the end of the file, then will use it (to continue to work with older
1015 * files), however all new counters will be placed within filenames.
1017 * Modified to only deal with base file name when renaming, to avoid issues with directory
1018 * names with dots.
1020 function _rename_file($fname) {
1021 $path = dirname($fname);
1022 $file = basename_international($fname);
1024 $fparts = explode("\.",$file);
1026 if (count($fparts) > 1) {
1027 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
1028 //increment the counter in filename
1029 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
1030 } elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
1031 //increment counter at end of filename (so compatible with previous openemr version files
1032 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
1033 } elseif (is_numeric($fparts[count($fparts) -1])) {
1034 //leave date at end and place counter in filename
1035 array_splice($fparts, -1, 0, "1");
1036 } else {
1037 //add the counter to filename
1038 array_splice($fparts, -1, 0, "1");
1040 } else { // (count($fparts) == 1)
1041 //place counter at end of filename
1042 array_push($fparts, "1");
1045 $fname = $path.DIRECTORY_SEPARATOR.join(".", $fparts);
1047 if (file_exists($fname)) {
1048 return $this->_rename_file($fname);
1049 } else {
1050 return($fname);
1054 function &_array_recurse($array,$categories = array()) {
1055 if (!is_array($array)) {
1056 $array = array();
1058 $node = &$this->_last_node;
1059 $current_node = &$node;
1060 $expandedIcon = 'folder-expanded.gif';
1061 foreach($array as $id => $ar) {
1062 $icon = 'folder.gif';
1063 if (is_array($ar) || !empty($id)) {
1064 if ($node == null) {
1065 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1066 $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));
1067 $this->_last_node = &$rnode;
1068 $node = &$rnode;
1069 $current_node = &$rnode;
1071 else {
1072 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1073 $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)));
1074 $current_node = &$this->_last_node;
1077 $this->_array_recurse($ar,$categories);
1079 else {
1080 if ($id === 0 && !empty($ar)) {
1081 $info = $this->tree->get_node_info($id);
1082 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1083 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1085 else {
1086 //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
1087 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1088 if ($id !== 0 && is_object($node)) {
1089 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1090 $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)));
1096 // If there are documents in this document category, then add their
1097 // attributes to the current node.
1098 $icon = "file3.png";
1099 if (is_array($categories[$id])) {
1100 foreach ($categories[$id] as $doc) {
1101 if($this->tree->get_node_name($id) == "CCR"){
1102 $current_node->addItem(new HTML_TreeNode(array(
1103 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1104 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1105 'icon' => $icon,
1106 'expandedIcon' => $expandedIcon,
1107 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1108 )));
1109 }elseif($this->tree->get_node_name($id) == "CCD"){
1110 $current_node->addItem(new HTML_TreeNode(array(
1111 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1112 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1113 'icon' => $icon,
1114 'expandedIcon' => $expandedIcon,
1115 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1116 )));
1117 }else{
1118 $current_node->addItem(new HTML_TreeNode(array(
1119 'text' => $doc['docdate'] . ' ' . basename_international($doc['url']),
1120 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1121 'icon' => $icon,
1122 'expandedIcon' => $expandedIcon
1123 )));
1129 return $node;
1132 //function for logging the errors in writing file to CouchDB/Hard Disk
1133 function document_upload_download_log($patientid,$content){
1134 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1135 $log_file = 'log.txt';
1136 if(!is_dir($log_path))
1137 mkdir($log_path,0777,true);
1138 $LOG = fopen($log_path.$log_file,'a');
1139 fwrite($LOG,$content);
1140 fclose($LOG);
1143 function document_send($email,$body,$attfile,$pname) {
1144 if (empty($email)) {
1145 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1146 return;
1149 $desc = "Please check the attached patient document.\n Content:".attr($body);
1150 $mail = new MyMailer();
1151 $from_name = $GLOBALS["practice_return_email_path"];
1152 $from = $GLOBALS["practice_return_email_path"];
1153 $mail->AddReplyTo($from,$from_name);
1154 $mail->SetFrom($from,$from );
1155 $to = $email ; $to_name =$email;
1156 $mail->AddAddress($to, $to_name);
1157 $subject = "Patient documents";
1158 $mail->Subject = $subject;
1159 $mail->Body = $desc;
1160 $mail->AddAttachment($attfile);
1161 if ($mail->Send()) {
1162 $retstatus = "email_sent";
1163 } else {
1164 $email_status = $mail->ErrorInfo;
1165 //echo "EMAIL ERROR: ".$email_status;
1166 $retstatus = "email_fail";
1170 //place to hold optional code
1171 //$first_node = array_keys($t->tree);
1172 //$first_node = $first_node[0];
1173 //$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')"));
1175 //$this->_last_node = &$node1;
1177 // Function to tag a document to an encounter.
1178 function tag_action_process($patient_id="", $document_id) {
1179 if ($_POST['process'] != "true") {
1180 die("process is '" . text($_POST['process']) . "', expected 'true'");
1181 return;
1184 // Create Encounter and Tag it.
1185 $event_date = date('Y-m-d H:i:s');
1186 $encounter_id = $_POST['encounter_id'];
1187 $encounter_check = $_POST['encounter_check'];
1188 $visit_category_id = $_POST['visit_category_id'];
1190 if (is_numeric($document_id)) {
1191 $messages = '';
1192 $d = new Document( $document_id );
1193 $file_name = $d->get_url_file();
1194 if (!is_numeric($encounter_id)) {
1195 $encounter_id = 0;
1198 $encounter_check = ( $encounter_check == 'on') ? 1 : 0;
1199 if ($encounter_check) {
1200 $provider_id = $_SESSION['authUserID'] ;
1202 // Get the logged in user's facility
1203 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1204 $username = $facilityRow['username'];
1205 $facility = $facilityRow['facility'];
1206 $facility_id = $facilityRow['facility_id'];
1207 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1208 $billingFacility = sqlQuery("SELECT id FROM facility WHERE primary_business_entity = 1");
1209 $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;
1211 $conn = $GLOBALS['adodb']['db'];
1212 $encounter = $conn->GenID("sequences");
1213 $query = "INSERT INTO form_encounter SET
1214 date = ?,
1215 reason = ?,
1216 facility = ?,
1217 sensitivity = 'normal',
1218 pc_catid = ?,
1219 facility_id = ?,
1220 billing_facility = ?,
1221 provider_id = ?,
1222 pid = ?,
1223 encounter = ?";
1224 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1225 $formID = sqlInsert($query,$bindArray);
1226 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1227 $d->set_encounter_id($encounter);
1228 $this->image_result_indication($d->id, $encounter);
1230 } else {
1231 $d->set_encounter_id($encounter_id);
1232 $this->image_result_indication($d->id, $encounter_id);
1234 $d->set_encounter_check($encounter_check);
1235 $d->persist();
1237 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1240 $this->_state = false;
1241 $this->assign("messages", $messages);
1243 return $this->view_action($patient_id, $document_id);
1246 function image_procedure_action($patient_id="",$document_id){
1248 $img_procedure_id = $_POST['image_procedure_id'];
1249 $proc_code = $_POST['procedure_code'];
1251 if(is_numeric($document_id)){
1253 $img_order = sqlQuery("select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? ",array($img_procedure_id,$proc_code));
1254 $img_report = sqlQuery("select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? ",array($img_procedure_id,$img_order['procedure_order_seq']));
1255 $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;
1256 if($img_report_id == 0){
1257 $report_date = date('Y-m-d H:i:s');
1258 $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));
1261 $img_result = sqlQuery("select * from procedure_result where procedure_report_id = ? and document_id = ?",array($img_report_id,$document_id));
1262 if(empty($img_result)){
1263 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));
1266 $this->image_result_indication($document_id, 0,$img_procedure_id);
1268 return $this->view_action($patient_id, $document_id);
1271 function clear_procedure_tag_action($patient_id="",$document_id){
1272 if(is_numeric($document_id)){
1273 sqlStatement("delete from procedure_result where document_id = ?",$document_id);
1275 return $this->view_action($patient_id, $document_id);
1278 function get_mapped_procedure($document_id){
1279 $map = array();
1280 if(is_numeric($document_id)){
1281 $map = sqlQuery("select poc.procedure_order_id,poc.procedure_code from procedure_result pres
1282 inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id
1283 inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)
1284 inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id
1285 where pres.document_id = ?",array($document_id));
1287 return $map;
1290 function image_result_indication($doc_id,$encounter,$image_procedure_id = 0){
1291 $doc_notes = sqlQuery("select note from notes where foreign_id = ?",array($doc_id));
1292 $narration = isset($doc_notes['note']) ? 'With Narration': 'Without Narration';
1294 if($encounter != 0) {
1295 $ep = sqlQuery("select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?",array($encounter));
1297 else if($image_procedure_id != 0){
1298 $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));
1300 else{
1301 $ep = array('assigned_to' => $_SESSION['authUser']);
1304 $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];
1305 $noteid = addPnote($_SESSION['pid'],'New Image Report received '.$narration,0,1,'Image Results',$encounter_provider,'','New','');
1306 setGpRelation(1, $doc_id, 6, $noteid);