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
{
21 var $document_categories;
24 var $manual_set_owner=false; // allows manual setting of a document owner/service
26 function C_Document($template_mod = "general") {
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);
44 function upload_action($patient_id,$category_id) {
45 $category_name = $this->tree
->get_node_name($category_id);
46 $this->assign("category_id", $category_id);
47 $this->assign("category_name", $category_name);
48 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
49 $this->assign("patient_id", $patient_id);
51 // Added by Rod to support document template download from general_upload.html.
52 // Cloned from similar stuff in manage_document_templates.php.
53 $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';
54 $templates_options = "<option value=''>-- " . xl('Select Template') . " --</option>";
55 $dh = opendir($templatedir);
57 $templateslist = array();
58 while (false !== ($sfname = readdir($dh))) {
59 if (substr($sfname, 0, 1) == '.') continue;
60 $templateslist[$sfname] = $sfname;
63 ksort($templateslist);
64 foreach ($templateslist as $sfname) {
65 $templates_options .= "<option value='" . htmlspecialchars($sfname, ENT_QUOTES
) .
66 "'>" . htmlspecialchars($sfname) . "</option>";
69 $this->assign("TEMPLATES_LIST", $templates_options);
71 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_upload.html");
72 $this->assign("activity", $activity);
73 return $this->list_action($patient_id);
76 //Upload multiple files on single click
77 function upload_action_process() {
79 // Collect a manually set owner if this has been set
80 // Used when want to manually assign the owning user/service such as the Direct mechanism
81 $non_HTTP_owner=false;
82 if ($this->manual_set_owner
) {
83 $non_HTTP_owner=$this->manual_set_owner
;
88 if($GLOBALS['document_storage_method']==0){
91 if($GLOBALS['document_storage_method']==1){
95 if ($_POST['process'] != "true")
98 $doDecryption = false;
99 $encrypted = $_POST['encrypted'];
100 $passphrase = $_POST['passphrase'];
101 if ( !$GLOBALS['hide_document_encryption'] &&
102 $encrypted && $passphrase ) {
103 $doDecryption = true;
106 if (is_numeric($_POST['category_id'])) {
107 $category_id = $_POST['category_id'];
111 if (isset($_GET['patient_id']) && !$couchDB) {
112 $patient_id = $_GET['patient_id'];
114 else if (is_numeric($_POST['patient_id'])) {
115 $patient_id = $_POST['patient_id'];
118 $sentUploadStatus = array();
119 if( count($_FILES['file']['name']) > 0){
121 foreach($_FILES['file']['name'] as $key => $value){
124 if ($_FILES['file']['error'][$key] > 0 ||
empty($fname) ||
$_FILES['file']['size'][$key] == 0) {
127 $fname = htmlentities("<empty>");
129 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
130 if ($_FILES['file']['size'][$key] == 0) {
131 $error .= "The system does not permit uploading files of with size 0.\n";
134 $tmpfile = fopen($_FILES['file']['tmp_name'][$key], "r");
135 $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);
138 $filetext = $this->decrypt($filetext, $passphrase);
140 if ( $_POST['destination'] != '' ) {
141 $fname = $_POST['destination'];
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'],
150 $error .= $rc . "\n";
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);
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")
201 $n->set_owner($_SESSION['authUserID']);
202 parent
::populate_object($n);
203 if ($_POST['identifier'] == "no"){
204 // associate a note with a document
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));
233 $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens
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;
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;
274 require_once(dirname(__FILE__
) . "/../library/acl.inc");
275 require_once(dirname(__FILE__
) . "/../library/lists.inc");
277 $d = new Document($doc_id);
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:
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($row_result_docs['pc_catname'])."</option>";
330 $this->assign("ENC_LIST", $encOptions);
332 //Populate the dropdown with category list
333 $visit_category_list = "<option value='0'>-- " . xlt('Select One') . " --</option>";
334 $cres = sqlStatement("SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname");
335 while ($crow = sqlFetchArray($cres)) {
336 $catid = $crow['pc_catid'];
337 if ($catid < 9 && $catid != 5) continue; // Applying same logic as in new encounter page.
338 $visit_category_list .="<option value='".attr($catid)."'>" . text(xl_appt_category($crow['pc_catname'])) . "</option>\n";
340 $this->assign("VISIT_CATEGORY_LIST", $visit_category_list);
342 $this->assign("notes",$notes);
344 $this->_last_node
= null;
346 $menu = new HTML_TreeMenu();
348 //pass an empty array because we don't want the documents for each category showing up in this list box
349 $rnode = $this->_array_recurse($this->tree
->tree
,array());
350 $menu->addItem($rnode);
351 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
353 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
355 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_view.html");
356 $this->assign("activity", $activity);
358 return $this->list_action($patient_id);
361 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
363 $td = mcrypt_module_open( $cypher, '', $mode, '');
364 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND
);
365 mcrypt_generic_init( $td, $key, $iv );
366 $crypttext = mcrypt_generic( $td, $plaintext );
367 mcrypt_generic_deinit( $td );
368 return $iv.$crypttext;
371 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
374 $td = mcrypt_module_open( $cypher, '', $mode, '' );
375 $ivsize = mcrypt_enc_get_iv_size( $td) ;
376 $iv = substr( $crypttext, 0, $ivsize );
377 $crypttext = substr( $crypttext, $ivsize );
380 mcrypt_generic_init( $td, $key, $iv );
381 $plaintext = mdecrypt_generic( $td, $crypttext );
387 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true,$disable_exit=false) {
389 $encrypted = $_POST['encrypted'];
390 $passphrase = $_POST['passphrase'];
391 $doEncryption = false;
392 if ( !$GLOBALS['hide_document_encryption'] &&
393 $encrypted == "true" &&
395 $doEncryption = true;
398 //controller function ruins booleans, so need to manually re-convert to booleans
399 if ($as_file == "true") {
402 else if ($as_file == "false") {
405 if ($original_file == "true") {
408 else if ($original_file == "false") {
409 $original_file=false;
411 if ($disable_exit == "true") {
414 else if ($disable_exit == "false") {
418 $d = new Document($document_id);
419 $url = $d->get_url();
420 $storagemethod = $d->get_storagemethod();
421 $couch_docid = $d->get_couch_docid();
422 $couch_revid = $d->get_couch_revid();
424 if($couch_docid && $couch_revid && $original_file){
425 $couch = new CouchDB();
426 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
427 $resp = $couch->retrieve_doc($data);
428 $content = $resp->data
;
429 if($content=='' && $GLOBALS['couchdb_log']==1){
430 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
431 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
432 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
433 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
434 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
435 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
436 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
437 die(xl("File retrieval from CouchDB failed"));
439 if($disable_exit == true) {
440 return base64_decode($content);
442 header('Content-Description: File Transfer');
443 header('Content-Transfer-Encoding: binary');
444 header('Expires: 0');
445 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
446 header('Pragma: public');
447 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
448 $fh = fopen($tmpcouchpath,"w");
449 fwrite($fh,base64_decode($content));
451 $f = fopen($tmpcouchpath,"r");
452 if ( $doEncryption ) {
453 $filetext = fread( $f, filesize($tmpcouchpath) );
454 $ciphertext = $this->encrypt( $filetext, $passphrase );
455 $tmpfilepath = $GLOBALS['temporary_files_dir'];
456 $tmpfilename = "/encrypted_".$d->get_url_file();
457 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
458 fwrite( $tmpfile, $ciphertext );
460 header('Content-Disposition: attachment; filename='.$tmpfilename );
461 header("Content-Type: application/octet-stream" );
462 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
465 readfile( $tmpfilepath.$tmpfilename );
466 unlink( $tmpfilepath.$tmpfilename );
468 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
469 header("Content-Type: " . $d->get_mimetype());
470 header("Content-Length: " . filesize($tmpcouchpath));
475 unlink($tmpcouchpath);
476 exit;//exits only if file download from CouchDB is successfull.
478 //strip url of protocol handler
479 $url = preg_replace("|^(.*)://|","",$url);
481 //change full path to current webroot. this is for documents that may have
482 //been moved from a different filesystem and the full path in the database
483 //is not current. this is also for documents that may of been moved to
484 //different patients. Note that the path_depth is used to see how far down
485 //the path to go. For example, originally the path_depth was always 1, which
486 //only allowed things like documents/1/<file>, but now can have more structured
487 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
489 // NOTE that $from_filename and basename($url) are the same thing
490 $from_all = explode("/",$url);
491 $from_filename = array_pop($from_all);
492 $from_pathname_array = array();
493 for ($i=0;$i<$d->get_path_depth();$i++
) {
494 $from_pathname_array[] = array_pop($from_all);
496 $from_pathname_array = array_reverse($from_pathname_array);
497 $from_pathname = implode("/",$from_pathname_array);
498 if($couch_docid && $couch_revid){
499 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
500 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
504 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
507 if (file_exists($temp_url)) {
512 if (!file_exists($url)) {
513 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;
517 if ($original_file) {
518 //normal case when serving the file referenced in database
519 if($disable_exit == true) {
520 $f = fopen($url,"r");
521 $filetext = fread( $f, filesize($url) );
524 header('Content-Description: File Transfer');
525 header('Content-Transfer-Encoding: binary');
526 header('Expires: 0');
527 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
528 header('Pragma: public');
529 $f = fopen($url,"r");
530 if ( $doEncryption ) {
531 $filetext = fread( $f, filesize($url) );
532 $ciphertext = $this->encrypt( $filetext, $passphrase );
533 $tmpfilepath = $GLOBALS['temporary_files_dir'];
534 $tmpfilename = "/encrypted_".$d->get_url_file();
535 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
536 fwrite( $tmpfile, $ciphertext );
538 header('Content-Disposition: attachment; filename='.$tmpfilename );
539 header("Content-Type: application/octet-stream" );
540 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
543 readfile( $tmpfilepath.$tmpfilename );
544 unlink( $tmpfilepath.$tmpfilename );
546 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
547 header("Content-Type: " . $d->get_mimetype());
548 header("Content-Length: " . filesize($url));
554 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
555 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
556 if($couch_docid && $couch_revid){
557 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
560 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
562 if($disable_exit == true) {
565 header("Pragma: public");
566 header("Expires: 0");
567 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
568 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
569 header("Content-Type: image/jpeg");
570 header("Content-Length: " . filesize($url));
571 $f = fopen($url,"r");
573 if($couch_docid && $couch_revid){
576 $url=str_replace("_converted.jpg",'.pdf',$url);
584 function queue_action($patient_id="") {
585 $messages = $this->_tpl_vars
['messages'];
586 $queue_files = array();
588 //see if the repository exists and it is a directory else error
589 if (file_exists($this->_config
['repository']) && is_dir($this->_config
['repository'])) {
590 $dir = opendir($this->_config
['repository']);
591 //read each entry in the directory
592 while (($file = readdir($dir)) !== false) {
593 //concat the filename and path
594 $file = $this->_config
['repository'] .$file;
595 $file_info = array();
596 //if the filename is a file get its info and put into a tmp array
597 if (is_file($file) && strpos(basename($file),".") !== 0) {
598 $file_info['filename'] = basename($file);
599 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
600 $d = Document
::document_factory_url("file://" . $file);
601 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
602 $file_info['patient_id'] = $patient_match[1];
603 $file_info['document_id'] = $d->get_id();
604 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
606 //merge the tmp array into the larger array
607 $queue_files[] = $file_info;
613 $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";
617 $this->assign("queue_files",$queue_files);
618 $this->_last_node
= null;
620 $menu = new HTML_TreeMenu();
622 //pass an empty array because we don't want the documents for each category showing up in this list box
623 $rnode = $this->_array_recurse($this->tree
->tree
,array());
624 $menu->addItem($rnode);
625 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
627 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
629 $this->assign("messages",nl2br($messages));
630 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_queue.html");
633 function queue_action_process() {
634 if ($_POST['process'] != "true")
637 $messages = $this->_tpl_vars
['messages'];
639 //build a category tree so we can have a list of category ids that are valid
640 $ct = new CategoryTree(1);
641 $categories = $ct->_id_name
;
643 //see if there were and posted files and assign them
645 is_array($_POST['files']) ?
$files = $_POST['files']: $files = array();
647 //loop through posted files
648 foreach($files as $doc_id=> $file) {
649 //only operate on files checked as active
650 if (!$file['active']) continue;
652 //run basic validation checks
653 if (!is_numeric($file['patient_id']) ||
!is_numeric($file['category_id']) ||
!is_numeric($doc_id)) {
654 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
658 //validate that the pod exists
659 $d = new Document($doc_id);
660 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
661 $result = $d->_db
->Execute($sql);
663 if (!$result ||
$result->EOF
) {
664 //patient id does not exist
665 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
669 //validate that the category id exists
670 if (!isset($categories[$file['category_id']])) {
671 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
675 //now do the work of moving the file
676 $new_path = $this->_config
['repository'] . $file['patient_id'] ."/";
678 //see if the patient dir exists in the repository and create if not
679 if (!file_exists($new_path)) {
680 if (!mkdir($new_path,0700)) {
681 $messages .= "The system was unable to create the directory for this upload, '" . $new_path . "'.\n";
686 //fname is the name of the file after it is moved
687 $fname = $file['name'];
689 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
690 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
691 if ($patient_match[1] == $file['patient_id']) {
692 $fname = preg_replace("/^([0-9]+)_/","",$fname);
695 //filenames should not have funny chars
696 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
698 //see if there is an existing file with the same name and rename as necessary
699 if (file_exists($new_path.$file['name'])) {
700 $messages .= "File with same name already exists at location: " . $new_path . "\n";
701 $fname = basename($this->_rename_file($new_path.$file['name']));
702 $messages .= "Current file name was changed to " . $fname ."\n";
706 if (rename($this->_config
['repository'].$file['name'],$new_path.$fname)) {
707 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
708 $d->url
= "file://" .$new_path.$fname;
709 $d->set_foreign_id($file['patient_id']);
710 $d->set_mimetype($mimetype);
714 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
715 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
716 $d->_db
->Execute($sql);
720 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
723 $this->assign("messages",$messages);
724 $_POST['process'] = "";
727 function move_action_process($patient_id="",$document_id) {
728 if ($_POST['process'] != "true")
731 $new_category_id = $_POST['new_category_id'];
732 $new_patient_id = $_POST['new_patient_id'];
734 //move to new category
735 if (is_numeric($new_category_id) && is_numeric($document_id)) {
736 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
737 $messages .= xl('Document moved to new category','','',' \'') . $this->tree
->_id_name
[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
739 $this->tree
->_db
->Execute($sql);
742 //move to new patient
743 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
744 $d = new Document($document_id);
745 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
746 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
747 $result = $d->_db
->Execute($sql);
749 if (!$result ||
$result->EOF
) {
750 //patient id does not exist
751 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
754 $couchsavefailed = !$d->change_patient($new_patient_id);
756 $this->_state
= false;
757 if(!$couchsavefailed){
759 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
763 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
765 $this->assign("messages",$messages);
766 return $this->list_action($patient_id);
769 //in this case return the document to the queue instead of moving it
770 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
771 $d = new Document($document_id);
772 $new_path = $this->_config
['repository'];
773 $fname = $d->get_url_file();
775 //see if there is an existing file with the same name and rename as necessary
776 if (file_exists($new_path.$d->get_url_file())) {
777 $messages .= "File with same name already exists in the queue.\n";
778 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
779 $messages .= "Current file name was changed to " . $fname ."\n";
783 if (rename($d->get_url_filepath(),$new_path.$fname)) {
784 $d->url
= "file://" .$new_path.$fname;
785 $d->set_foreign_id("");
790 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db
->qstr($document_id);
791 $d->_db
->Execute($sql);
792 $messages .= "Document returned to queue successfully.\n";
796 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
799 $this->_state
= false;
800 $this->assign("messages",$messages);
801 return $this->list_action($patient_id);
804 $this->_state
= false;
805 $this->assign("messages",$messages);
806 return $this->view_action($patient_id,$document_id);
809 function validate_action_process($patient_id="", $document_id) {
811 $d = new Document($document_id);
812 if($d->couch_docid
&& $d->couch_revid
){
813 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
814 $url = $file_path.$d->get_url();
815 $couch = new CouchDB();
816 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid
);
817 $resp = $couch->retrieve_doc($data);
818 $content = $resp->data
;
819 //--------Temporarily writing the file for calculating the hash--------//
820 //-----------Will be removed after calculating the hash value----------//
821 $temp_file = fopen($url,"w");
822 fwrite($temp_file,base64_decode($content));
826 $url = $d->get_url();
828 //strip url of protocol handler
829 $url = preg_replace("|^(.*)://|","",$url);
831 //change full path to current webroot. this is for documents that may have
832 //been moved from a different filesystem and the full path in the database
833 //is not current. this is also for documents that may of been moved to
834 //different patients. Note that the path_depth is used to see how far down
835 //the path to go. For example, originally the path_depth was always 1, which
836 //only allowed things like documents/1/<file>, but now can have more structured
837 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
839 // NOTE that $from_filename and basename($url) are the same thing
840 $from_all = explode("/",$url);
841 $from_filename = array_pop($from_all);
842 $from_pathname_array = array();
843 for ($i=0;$i<$d->get_path_depth();$i++
) {
844 $from_pathname_array[] = array_pop($from_all);
846 $from_pathname_array = array_reverse($from_pathname_array);
847 $from_pathname = implode("/",$from_pathname_array);
848 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
849 if (file_exists($temp_url)) {
853 if ($_POST['process'] != "true") {
854 die("process is '" . $_POST['process'] . "', expected 'true'");
858 $d = new Document( $document_id );
859 $current_hash = sha1_file( $url );
860 $messages = xl('Current Hash').": ".$current_hash."<br>";
861 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
862 if ( $d->get_hash() == '' ) {
863 $d->hash
= $current_hash;
866 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
867 } else if ( $current_hash != $d->get_hash() ) {
868 $messages .= xl('Hash does not match. Data integrity has been compromised.');
870 $messages .= xl('Document passed integrity check.');
872 $this->_state
= false;
873 $this->assign("messages", $messages);
874 if($d->couch_docid
&& $d->couch_revid
){
875 //Removing the temporary file which is used to create the hash
876 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
878 return $this->view_action($patient_id, $document_id);
881 // Added by Rod for metadata update.
883 function update_action_process($patient_id="", $document_id) {
885 if ($_POST['process'] != "true") {
886 die("process is '" . $_POST['process'] . "', expected 'true'");
890 $docdate = $_POST['docdate'];
891 $docname = $_POST['docname'];
892 $issue_id = $_POST['issue_id'];
894 if (is_numeric($document_id)) {
896 $d = new Document( $document_id );
897 $file_name = $d->get_url_file();
898 if ( $docname != '' &&
899 $docname != $file_name ) {
900 $path = $d->get_url_filepath();
901 $path = str_replace( $file_name, "", $path );
902 $new_url = $this->_rename_file( $path.$docname );
903 if ( rename( $d->get_url(), $new_url ) ) {
904 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
905 $url = preg_replace("|^(.*)://|","",$d->get_url());
906 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
907 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
908 if ( file_exists( $url ) ) {
914 $messages .= xl('Document successfully renamed.')."<br>";
916 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
920 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
921 $docdate = "'$docdate'";
925 if (!is_numeric($issue_id)) {
928 $couch_docid = $d->get_couch_docid();
929 $couch_revid = $d->get_couch_revid();
930 if($couch_docid && $couch_revid ){
931 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
932 "list_id = '$issue_id' " .
933 "WHERE id = '$document_id'";
934 $this->tree
->_db
->Execute($sql);
938 $sql = "UPDATE documents SET docdate = $docdate, " .
939 "list_id = '$issue_id' " .
940 "WHERE id = '$document_id'";
941 $this->tree
->_db
->Execute($sql);
943 $messages .= xl('Document date and issue updated successfully') . "<br>";
946 $this->_state
= false;
947 $this->assign("messages", $messages);
948 return $this->view_action($patient_id, $document_id);
951 function list_action($patient_id = "") {
952 $this->_last_node
= null;
953 $categories_list = $this->tree
->_get_categories_array($patient_id);
954 //print_r($categories_list);
956 $menu = new HTML_TreeMenu();
957 $rnode = $this->_array_recurse($this->tree
->tree
,$categories_list);
958 $menu->addItem($rnode);
959 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
960 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
962 $this->assign("tree_html",$treeMenu->toHTML());
964 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_list.html");
967 /* This is a recursive function to rename a file to something that doesn't already exist.
968 * Modified in version 3.2.0 to place a counter within the filename (previously was placed
969 * at end) to ensure documents opened correctly by external browser viewers. If the
970 * counter is at the end of the file, then will use it (to continue to work with older
971 * files), however all new counters will be placed within filenames.
973 * Modified to only deal with base file name when renaming, to avoid issues with directory
976 function _rename_file($fname) {
977 $path = dirname($fname);
978 $file = basename($fname);
980 $fparts = split("\.",$file);
982 if (count($fparts) > 1) {
983 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
984 //increment the counter in filename
985 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] +
1;
986 } elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
987 //increment counter at end of filename (so compatible with previous openemr version files
988 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] +
1;
989 } elseif (is_numeric($fparts[count($fparts) -1])) {
990 //leave date at end and place counter in filename
991 array_splice($fparts, -1, 0, "1");
993 //add the counter to filename
994 array_splice($fparts, -1, 0, "1");
996 } else { // (count($fparts) == 1)
997 //place counter at end of filename
998 array_push($fparts, "1");
1001 $fname = $path.DIRECTORY_SEPARATOR
.join(".", $fparts);
1003 if (file_exists($fname)) {
1004 return $this->_rename_file($fname);
1010 function &_array_recurse($array,$categories = array()) {
1011 if (!is_array($array)) {
1014 $node = &$this->_last_node
;
1015 $current_node = &$node;
1016 $expandedIcon = 'folder-expanded.gif';
1017 foreach($array as $id => $ar) {
1018 $icon = 'folder.gif';
1019 if (is_array($ar) ||
!empty($id)) {
1020 if ($node == null) {
1021 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1022 $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));
1023 $this->_last_node
= &$rnode;
1025 $current_node = &$rnode;
1028 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1029 $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)));
1030 $current_node = &$this->_last_node
;
1033 $this->_array_recurse($ar,$categories);
1036 if ($id === 0 && !empty($ar)) {
1037 $info = $this->tree
->get_node_info($id);
1038 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1039 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1042 //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
1043 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1044 if ($id !== 0 && is_object($node)) {
1045 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1046 $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)));
1052 // If there are documents in this document category, then add their
1053 // attributes to the current node.
1054 $icon = "file3.png";
1055 if (is_array($categories[$id])) {
1056 foreach ($categories[$id] as $doc) {
1057 if($this->tree
->get_node_name($id) == "CCR"){
1058 $current_node->addItem(new HTML_TreeNode(array(
1059 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1060 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1062 'expandedIcon' => $expandedIcon,
1063 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1065 }elseif($this->tree
->get_node_name($id) == "CCD"){
1066 $current_node->addItem(new HTML_TreeNode(array(
1067 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1068 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1070 'expandedIcon' => $expandedIcon,
1071 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1074 $current_node->addItem(new HTML_TreeNode(array(
1075 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1076 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1078 'expandedIcon' => $expandedIcon
1088 //function for logging the errors in writing file to CouchDB/Hard Disk
1089 function document_upload_download_log($patientid,$content){
1090 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1091 $log_file = 'log.txt';
1092 if(!is_dir($log_path))
1093 mkdir($log_path,0777,true);
1094 $LOG = fopen($log_path.$log_file,'a');
1095 fwrite($LOG,$content);
1099 function document_send($email,$body,$attfile,$pname) {
1100 if (empty($email)) {
1101 $this->assign("process_result","Email could not be sent, the address supplied: '$email' was empty or invalid.");
1105 $desc = "Please check the attached patient document.\n Content:".attr($body);
1106 $mail = new MyMailer();
1107 $from_name = $GLOBALS["practice_return_email_path"];
1108 $from = $GLOBALS["practice_return_email_path"];
1109 $mail->AddReplyTo($from,$from_name);
1110 $mail->SetFrom($from,$from );
1111 $to = $email ; $to_name =$email;
1112 $mail->AddAddress($to, $to_name);
1113 $subject = "Patient documents";
1114 $mail->Subject
= $subject;
1115 $mail->Body
= $desc;
1116 $mail->AddAttachment($attfile);
1117 if ($mail->Send()) {
1118 $retstatus = "email_sent";
1120 $email_status = $mail->ErrorInfo
;
1121 //echo "EMAIL ERROR: ".$email_status;
1122 $retstatus = "email_fail";
1126 //place to hold optional code
1127 //$first_node = array_keys($t->tree);
1128 //$first_node = $first_node[0];
1129 //$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')"));
1131 //$this->_last_node = &$node1;
1133 // Function to tag a document to an encounter.
1134 function tag_action_process($patient_id="", $document_id) {
1135 if ($_POST['process'] != "true") {
1136 die("process is '" . text($_POST['process']) . "', expected 'true'");
1140 // Create Encounter and Tag it.
1141 $event_date = date('Y-m-d H:i:s');
1142 $encounter_id = $_POST['encounter_id'];
1143 $encounter_check = $_POST['encounter_check'];
1144 $visit_category_id = $_POST['visit_category_id'];
1146 if (is_numeric($document_id)) {
1148 $d = new Document( $document_id );
1149 $file_name = $d->get_url_file();
1150 if (!is_numeric($encounter_id)) {
1154 $encounter_check = ( $encounter_check == 'on') ?
1 : 0;
1155 if ($encounter_check) {
1156 $provider_id = $_SESSION['authUserID'] ;
1158 // Get the logged in user's facility
1159 $facilityRow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array("$provider_id"));
1160 $username = $facilityRow['username'];
1161 $facility = $facilityRow['facility'];
1162 $facility_id = $facilityRow['facility_id'];
1163 // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility
1164 $billingFacility = sqlQuery("SELECT id FROM facility WHERE primary_business_entity = 1");
1165 $billingFacilityID = ( $billingFacility['id'] ) ?
$billingFacility['id'] : $facility_id;
1167 $conn = $GLOBALS['adodb']['db'];
1168 $encounter = $conn->GenID("sequences");
1169 $query = "INSERT INTO form_encounter SET
1173 sensitivity = 'normal',
1176 billing_facility = ?,
1180 $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);
1181 $formID = sqlInsert($query,$bindArray);
1182 addForm($encounter, "New Patient Encounter",$formID,"newpatient", $patient_id, "1", date("Y-m-d H:i:s"), $username );
1183 $d->set_encounter_id($encounter);
1186 $d->set_encounter_id($encounter_id);
1188 $d->set_encounter_check($encounter_check);
1191 $messages .= xlt('Document tagged to Encounter successfully') . "<br>";
1194 $this->_state
= false;
1195 $this->assign("messages", $messages);
1197 return $this->view_action($patient_id, $document_id);