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");
14 class C_Document
extends Controller
{
18 var $document_categories;
24 function C_Document($template_mod = "general") {
26 $this->documents
= array();
27 $this->template_mod
= $template_mod;
28 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
29 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
31 //get global config options for this namespace
32 $this->_config
= $GLOBALS['oer_config']['documents'];
33 if($GLOBALS['document_storage_method']==1){
34 $this->file_path
= $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
37 if ( (!empty($_GET['higher_level_path'])) && (is_numeric($_GET['patient_id']) && $_GET['patient_id']>0) ) {
38 // Allow higher level directory structure in documents directory and a patient is mapped
39 $this->file_path
= $this->_config
['repository'] . preg_replace("/[^A-Za-z0-9\/]/","_",$_GET['higher_level_path']) . "/";
41 else if (!empty($_GET['higher_level_path'])) {
42 // Allow higher level directory structure in documents directory and there is no patient mapping
43 // (Since a patient is not mapped, will create up to 10000 random directories and increment the path_depth by 1)
44 $this->file_path
= $this->_config
['repository'] . preg_replace("/[^A-Za-z0-9\/]/","_",$_GET['higher_level_path']) . "/" . rand(1,10000) . "/";
45 $_POST['path_depth'] = $_POST['path_depth'] +
1;
47 else if ( !(is_numeric($_GET['patient_id'])) ||
!($_GET['patient_id']>0) ) {
48 // This is the default action except there is no patient mapping (when patient_id is 00 or direct)
49 // (Since a patient is not mapped, will create up to 10000 random directories and set the path_depth to 2)
50 $this->file_path
= $this->_config
['repository'] . preg_replace("/[^A-Za-z0-9]/","_",$_GET['patient_id']) . "/" . rand(1,10000) . "/";
51 $_POST['path_depth'] = 2;
54 // This is the default action where the patient is is used as one level directory structure in documents directory
55 $this->file_path
= $this->_config
['repository'] . preg_replace("/[^A-Za-z0-9]/","_",$_GET['patient_id']) . "/";
58 $this->_args
= array("patient_id" => $_GET['patient_id']);
60 $this->assign("STYLE", $GLOBALS['style']);
61 $t = new CategoryTree(1);
66 function upload_action($patient_id,$category_id) {
67 $category_name = $this->tree
->get_node_name($category_id);
68 $this->assign("category_id", $category_id);
69 $this->assign("category_name", $category_name);
70 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
71 $this->assign("patient_id", $patient_id);
72 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_upload.html");
73 $this->assign("activity", $activity);
74 return $this->list_action($patient_id);
77 //Upload multiple files on single click
78 //2013-02-10 EMR Direct: added $non_HTTP_owner to allow storage of Direct Message attachments
79 //through this mechanism, and is set to the user_id for the background process adding the document
80 function upload_action_process($non_HTTP_owner=false) {
83 if($GLOBALS['document_storage_method']==0){
86 if($GLOBALS['document_storage_method']==1){
90 if ($_POST['process'] != "true")
93 $doDecryption = false;
94 $encrypted = $_POST['encrypted'];
95 $passphrase = $_POST['passphrase'];
96 if ( !$GLOBALS['hide_document_encryption'] &&
97 $encrypted && $passphrase ) {
101 if (is_numeric($_POST['category_id'])) {
102 $category_id = $_POST['category_id'];
104 if (is_numeric($_POST['patient_id'])) {
105 $patient_id = $_POST['patient_id'];
108 $sentUploadStatus = array();
109 if( count($_FILES['file']['name']) > 0){
111 foreach($_FILES['file']['name'] as $key => $value){
114 if ($_FILES['file']['error'][$key] > 0 ||
empty($fname) ||
$_FILES['file']['size'][$key] == 0) {
117 $fname = htmlentities("<empty>");
119 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
120 if ($_FILES['file']['size'][$key] == 0) {
121 $error .= "The system does not permit uploading files of with size 0.\n";
125 if (!file_exists($this->file_path
)) {
126 if (!mkdir($this->file_path
,0700,true)) {
127 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path
. "'.\n";
131 if ( $_POST['destination'] != '' ) {
132 $fname = $_POST['destination'];
134 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
135 if (file_exists($this->file_path
.$fname)) {
136 $error .= xl('File with same name already exists at location:','','',' ') . $this->file_path
. "\n";
137 $fname = basename($this->_rename_file($this->file_path
.$fname));
138 $_FILES['file']['name'][$key] = $fname;
139 $error .= xl('Current file name was changed to','','',' ') . $fname ."\n";
142 if ( $doDecryption ) {
143 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key] , "r" );
144 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
145 $plaintext = $this->decrypt( $filetext, $passphrase );
147 unlink( $_FILES['file']['tmp_name'][$key] );
148 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "w+" );
149 fwrite( $tmpfile, $plaintext );
151 $_FILES['file']['size'][$key] = filesize( $_FILES['file']['tmp_name'][$key] );
156 if($couchDB == true){
157 $couch = new CouchDB();
158 $docname = $_SESSION['authId'].$patient_id.$encounter.$fname.date("%Y-%m-%d H:i:s");
159 $docid = $couch->stringToId($docname);
160 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "rb" );
161 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
163 //--------Temporarily writing the file for calculating the hash--------//
164 //-----------Will be removed after calculating the hash value----------//
165 $temp_file = fopen($this->file_path
.$fname,"w");
166 fwrite($temp_file,$filetext);
168 //---------------------------------------------------------------------//
170 $json = json_encode(base64_encode($filetext));
171 $db = $GLOBALS['couchdb_dbase'];
172 $data = array($db,$docid,$patient_id,$encounter,$_FILES['file']['type'][$key],$json);
173 $resp = $couch->check_saveDOC($data);
174 if(!$resp->id ||
!$resp->_rev
){
175 $data = array($db,$docid,$patient_id,$encounter);
176 $resp = $couch->retrieve_doc($data);
178 $revid = $resp->_rev
;
184 if(!$docid && !$revid){ //if couchdb save failed
185 $error .= "<font color='red'><b>".xl("The file could not be saved to CouchDB.") . "</b></font>\n";
186 if($GLOBALS['couchdb_log']==1){
189 $couchError=ob_get_clean();
190 $log_content = date('Y-m-d H:i:s')." ==> Uploading document: ".$fname."\r\n";
191 $log_content .= date('Y-m-d H:i:s')." ==> Failed to Store document content to CouchDB.\r\n";
192 $log_content .= date('Y-m-d H:i:s')." ==> Document ID: ".$docid."\r\n";
193 $log_content .= date('Y-m-d H:i:s')." ==> ".print_r($data,1)."\r\n";
194 $log_content .= $couchError;
195 $this->document_upload_download_log($patient_id,$log_content);//log error if any, for testing phase only
200 $this->assign("upload_success", "true");
204 if($harddisk == true){
205 $uploadSuccess = false;
206 $move_cmd = ($non_HTTP_owner ?
"rename" : "move_uploaded_file");
207 if($move_cmd($_FILES['file']['tmp_name'][$key],$this->file_path
.$fname)){
208 $uploadSuccess = true;
209 $this->assign("upload_success", "true");
212 $error .= xl("The file could not be succesfully stored, this error is usually related to permissions problems on the storage system")."\n";
217 $d->storagemethod
= $GLOBALS['document_storage_method'];
218 if($harddisk == true) {
219 $d->url
= "file://" .$this->file_path
.$fname;
220 if (is_numeric($_POST['path_depth'])) {
221 // this is for when directory structure is more than one level
222 $d->path_depth
= $_POST['path_depth'];
228 if($couchDB == true){
229 $d->couch_docid
= $docid;
230 $d->couch_revid
= $revid;
232 if ($_FILES['file']['type'][$key] == 'text/xml') {
233 $d->mimetype
= 'application/xml';
236 $d->mimetype
= $_FILES['file']['type'][$key];
238 $d->size
= $_FILES['file']['size'][$key];
239 $d->owner
= $non_HTTP_owner ?
$non_HTTP_owner : $_SESSION['authUserID'];
240 $sha1Hash = sha1_file( $this->file_path
.$fname );
241 if($couchDB == true){
242 //Removing the temporary file which is used to create the hash
243 unlink($this->file_path
.$fname);
245 $d->hash
= $sha1Hash;
246 $d->type
= $d->type_array
['file_url'];
247 $d->set_foreign_id($patient_id);
248 if(( ($harddisk == true) && $uploadSuccess ) ||
($couchDB == true && $docid && $revid)){
252 $sentUploadStatus[] = $d;
253 $this->assign("file",$sentUploadStatus);
255 if (is_numeric($d->get_id()) && is_numeric($category_id)){
256 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
257 $d->_db
->Execute($sql);
259 if($GLOBALS['couchdb_log']==1 && $log_content!=''){
260 $log_content .= "\r\n\r\n";
261 $this->document_upload_download_log($patient_id,$log_content);
267 $this->assign("error", nl2br($error));
268 //$this->_state = false;
269 $_POST['process'] = "";
270 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
273 function note_action_process($patient_id) {
275 if ($_POST['process'] != "true")
279 $n->set_owner($_SESSION['authUserID']);
280 parent
::populate_object($n);
283 $this->_state
= false;
284 $_POST['process'] = "";
285 return $this->view_action($patient_id,$n->get_foreign_id());
288 function default_action() {
289 return $this->list_action();
292 function view_action($patient_id="",$doc_id) {
293 // Added by Rod to support document delete:
294 global $gacl_object, $phpgacl_location;
297 require_once(dirname(__FILE__
) . "/../library/acl.inc");
298 require_once(dirname(__FILE__
) . "/../library/lists.inc");
300 $d = new Document($doc_id);
303 $notes = $n->notes_factory($doc_id);
305 $this->assign("file", $d);
306 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
307 $this->assign("NOTE_ACTION",$this->_link("note"));
308 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
309 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
311 // Added by Rod to support document delete:
313 if (acl_check('admin', 'super')) {
314 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
315 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
317 $this->assign("delete_string", $delete_string);
318 $this->assign("REFRESH_ACTION",$this->_link("list"));
320 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
321 "document_id=" . $d->get_id() . "&process=true");
323 // Added by Rod to support document date update:
324 $this->assign("DOCDATE", $d->get_docdate());
325 $this->assign("UPDATE_ACTION",$this->_link("update") .
326 "document_id=" . $d->get_id() . "&process=true");
328 // Added by Rod to support document issue update:
329 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
330 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
331 "pid = $patient_id " . // AND enddate IS NULL " .
332 "ORDER BY type, begdate");
333 while ($irow = sqlFetchArray($ires)) {
334 $desc = $irow['type'];
335 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
336 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
337 $sel = ($irow['id'] == $d->get_list_id()) ?
' selected' : '';
338 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
340 $this->assign("ISSUES_LIST", $issues_options);
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) {
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;
412 $d = new Document($document_id);
413 $url = $d->get_url();
414 $storagemethod = $d->get_storagemethod();
415 $couch_docid = $d->get_couch_docid();
416 $couch_revid = $d->get_couch_revid();
418 if($couch_docid && $couch_revid && $original_file){
419 $couch = new CouchDB();
420 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
421 $resp = $couch->retrieve_doc($data);
422 $content = $resp->data
;
423 if($content=='' && $GLOBALS['couchdb_log']==1){
424 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
425 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
426 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
427 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
428 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
429 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
430 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
431 die(xl("File retrieval from CouchDB failed"));
433 header('Content-Description: File Transfer');
434 header('Content-Transfer-Encoding: binary');
435 header('Expires: 0');
436 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
437 header('Pragma: public');
438 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
439 $fh = fopen($tmpcouchpath,"w");
440 fwrite($fh,base64_decode($content));
442 $f = fopen($tmpcouchpath,"r");
443 if ( $doEncryption ) {
444 $filetext = fread( $f, filesize($tmpcouchpath) );
445 $ciphertext = $this->encrypt( $filetext, $passphrase );
446 $tmpfilepath = $GLOBALS['temporary_files_dir'];
447 $tmpfilename = "/encrypted_".$d->get_url_file();
448 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
449 fwrite( $tmpfile, $ciphertext );
451 header('Content-Disposition: attachment; filename='.$tmpfilename );
452 header("Content-Type: application/octet-stream" );
453 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
456 readfile( $tmpfilepath.$tmpfilename );
457 unlink( $tmpfilepath.$tmpfilename );
459 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
460 header("Content-Type: " . $d->get_mimetype());
461 header("Content-Length: " . filesize($tmpcouchpath));
466 unlink($tmpcouchpath);
467 exit;//exits only if file download from CouchDB is successfull.
469 //strip url of protocol handler
470 $url = preg_replace("|^(.*)://|","",$url);
472 //change full path to current webroot. this is for documents that may have
473 //been moved from a different filesystem and the full path in the database
474 //is not current. this is also for documents that may of been moved to
475 //different patients. Note that the path_depth is used to see how far down
476 //the path to go. For example, originally the path_depth was always 1, which
477 //only allowed things like documents/1/<file>, but now can have more structured
478 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
480 // NOTE that $from_filename and basename($url) are the same thing
481 $from_all = explode("/",$url);
482 $from_filename = array_pop($from_all);
483 $from_pathname_array = array();
484 for ($i=0;$i<$d->get_path_depth();$i++
) {
485 $from_pathname_array[] = array_pop($from_all);
487 $from_pathname_array = array_reverse($from_pathname_array);
488 $from_pathname = implode("/",$from_pathname_array);
489 if($couch_docid && $couch_revid){
490 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
491 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
495 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
498 if (file_exists($temp_url)) {
503 if (!file_exists($url)) {
504 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;
508 if ($original_file) {
509 //normal case when serving the file referenced in database
510 header('Content-Description: File Transfer');
511 header('Content-Transfer-Encoding: binary');
512 header('Expires: 0');
513 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
514 header('Pragma: public');
515 $f = fopen($url,"r");
516 if ( $doEncryption ) {
517 $filetext = fread( $f, filesize($url) );
518 $ciphertext = $this->encrypt( $filetext, $passphrase );
519 $tmpfilepath = $GLOBALS['temporary_files_dir'];
520 $tmpfilename = "/encrypted_".$d->get_url_file();
521 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
522 fwrite( $tmpfile, $ciphertext );
524 header('Content-Disposition: attachment; filename='.$tmpfilename );
525 header("Content-Type: application/octet-stream" );
526 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
529 readfile( $tmpfilepath.$tmpfilename );
530 unlink( $tmpfilepath.$tmpfilename );
532 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
533 header("Content-Type: " . $d->get_mimetype());
534 header("Content-Length: " . filesize($url));
540 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
541 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
542 if($couch_docid && $couch_revid){
543 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
546 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
548 header("Pragma: public");
549 header("Expires: 0");
550 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
551 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
552 header("Content-Type: image/jpeg");
553 header("Content-Length: " . filesize($url));
554 $f = fopen($url,"r");
556 if($couch_docid && $couch_revid){
559 $url=str_replace("_converted.jpg",'.pdf',$url);
567 function queue_action($patient_id="") {
568 $messages = $this->_tpl_vars
['messages'];
569 $queue_files = array();
571 //see if the repository exists and it is a directory else error
572 if (file_exists($this->_config
['repository']) && is_dir($this->_config
['repository'])) {
573 $dir = opendir($this->_config
['repository']);
574 //read each entry in the directory
575 while (($file = readdir($dir)) !== false) {
576 //concat the filename and path
577 $file = $this->_config
['repository'] .$file;
578 $file_info = array();
579 //if the filename is a file get its info and put into a tmp array
580 if (is_file($file) && strpos(basename($file),".") !== 0) {
581 $file_info['filename'] = basename($file);
582 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
583 $d = Document
::document_factory_url("file://" . $file);
584 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
585 $file_info['patient_id'] = $patient_match[1];
586 $file_info['document_id'] = $d->get_id();
587 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
589 //merge the tmp array into the larger array
590 $queue_files[] = $file_info;
596 $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";
600 $this->assign("queue_files",$queue_files);
601 $this->_last_node
= null;
603 $menu = new HTML_TreeMenu();
605 //pass an empty array because we don't want the documents for each category showing up in this list box
606 $rnode = $this->_array_recurse($this->tree
->tree
,array());
607 $menu->addItem($rnode);
608 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
610 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
612 $this->assign("messages",nl2br($messages));
613 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_queue.html");
616 function queue_action_process() {
617 if ($_POST['process'] != "true")
620 $messages = $this->_tpl_vars
['messages'];
622 //build a category tree so we can have a list of category ids that are valid
623 $ct = new CategoryTree(1);
624 $categories = $ct->_id_name
;
626 //see if there were and posted files and assign them
628 is_array($_POST['files']) ?
$files = $_POST['files']: $files = array();
630 //loop through posted files
631 foreach($files as $doc_id=> $file) {
632 //only operate on files checked as active
633 if (!$file['active']) continue;
635 //run basic validation checks
636 if (!is_numeric($file['patient_id']) ||
!is_numeric($file['category_id']) ||
!is_numeric($doc_id)) {
637 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
641 //validate that the pod exists
642 $d = new Document($doc_id);
643 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
644 $result = $d->_db
->Execute($sql);
646 if (!$result ||
$result->EOF
) {
647 //patient id does not exist
648 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
652 //validate that the category id exists
653 if (!isset($categories[$file['category_id']])) {
654 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
658 //now do the work of moving the file
659 $new_path = $this->_config
['repository'] . $file['patient_id'] ."/";
661 //see if the patient dir exists in the repository and create if not
662 if (!file_exists($new_path)) {
663 if (!mkdir($new_path,0700)) {
664 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path
. "'.\n";
669 //fname is the name of the file after it is moved
670 $fname = $file['name'];
672 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
673 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
674 if ($patient_match[1] == $file['patient_id']) {
675 $fname = preg_replace("/^([0-9]+)_/","",$fname);
678 //filenames should not have funny chars
679 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
681 //see if there is an existing file with the same name and rename as necessary
682 if (file_exists($new_path.$file['name'])) {
683 $messages .= "File with same name already exists at location: " . $new_path . "\n";
684 $fname = basename($this->_rename_file($new_path.$file['name']));
685 $messages .= "Current file name was changed to " . $fname ."\n";
689 if (rename($this->_config
['repository'].$file['name'],$new_path.$fname)) {
690 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
691 $d->url
= "file://" .$new_path.$fname;
692 $d->set_foreign_id($file['patient_id']);
693 $d->set_mimetype($mimetype);
697 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
698 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
699 $d->_db
->Execute($sql);
703 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
706 $this->assign("messages",$messages);
707 $_POST['process'] = "";
710 function move_action_process($patient_id="",$document_id) {
711 if ($_POST['process'] != "true")
714 $new_category_id = $_POST['new_category_id'];
715 $new_patient_id = $_POST['new_patient_id'];
717 //move to new category
718 if (is_numeric($new_category_id) && is_numeric($document_id)) {
719 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
720 $messages .= xl('Document moved to new category','','',' \'') . $this->tree
->_id_name
[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
722 $this->tree
->_db
->Execute($sql);
725 //move to new patient
726 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
727 $d = new Document($document_id);
728 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
729 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
730 $result = $d->_db
->Execute($sql);
732 if (!$result ||
$result->EOF
) {
733 //patient id does not exist
734 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
737 $couchsavefailed = !$d->change_patient($new_patient_id);
739 $this->_state
= false;
740 if(!$couchsavefailed){
742 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
746 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
748 $this->assign("messages",$messages);
749 return $this->list_action($patient_id);
752 //in this case return the document to the queue instead of moving it
753 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
754 $d = new Document($document_id);
755 $new_path = $this->_config
['repository'];
756 $fname = $d->get_url_file();
758 //see if there is an existing file with the same name and rename as necessary
759 if (file_exists($new_path.$d->get_url_file())) {
760 $messages .= "File with same name already exists in the queue.\n";
761 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
762 $messages .= "Current file name was changed to " . $fname ."\n";
766 if (rename($d->get_url_filepath(),$new_path.$fname)) {
767 $d->url
= "file://" .$new_path.$fname;
768 $d->set_foreign_id("");
773 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db
->qstr($document_id);
774 $d->_db
->Execute($sql);
775 $messages .= "Document returned to queue successfully.\n";
779 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
782 $this->_state
= false;
783 $this->assign("messages",$messages);
784 return $this->list_action($patient_id);
787 $this->_state
= false;
788 $this->assign("messages",$messages);
789 return $this->view_action($patient_id,$document_id);
792 function validate_action_process($patient_id="", $document_id) {
794 $d = new Document($document_id);
795 if($d->couch_docid
&& $d->couch_revid
){
796 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
797 $url = $file_path.$d->get_url();
798 $couch = new CouchDB();
799 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid
);
800 $resp = $couch->retrieve_doc($data);
801 $content = $resp->data
;
802 //--------Temporarily writing the file for calculating the hash--------//
803 //-----------Will be removed after calculating the hash value----------//
804 $temp_file = fopen($url,"w");
805 fwrite($temp_file,base64_decode($content));
809 $url = $d->get_url();
811 //strip url of protocol handler
812 $url = preg_replace("|^(.*)://|","",$url);
814 //change full path to current webroot. this is for documents that may have
815 //been moved from a different filesystem and the full path in the database
816 //is not current. this is also for documents that may of been moved to
817 //different patients. Note that the path_depth is used to see how far down
818 //the path to go. For example, originally the path_depth was always 1, which
819 //only allowed things like documents/1/<file>, but now can have more structured
820 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
822 // NOTE that $from_filename and basename($url) are the same thing
823 $from_all = explode("/",$url);
824 $from_filename = array_pop($from_all);
825 $from_pathname_array = array();
826 for ($i=0;$i<$d->get_path_depth();$i++
) {
827 $from_pathname_array[] = array_pop($from_all);
829 $from_pathname_array = array_reverse($from_pathname_array);
830 $from_pathname = implode("/",$from_pathname_array);
831 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
832 if (file_exists($temp_url)) {
836 if ($_POST['process'] != "true") {
837 die("process is '" . $_POST['process'] . "', expected 'true'");
841 $d = new Document( $document_id );
842 $current_hash = sha1_file( $url );
843 $messages = xl('Current Hash').": ".$current_hash."<br>";
844 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
845 if ( $d->get_hash() == '' ) {
846 $d->hash
= $current_hash;
849 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
850 } else if ( $current_hash != $d->get_hash() ) {
851 $messages .= xl('Hash does not match. Data integrity has been compromised.');
853 $messages .= xl('Document passed integrity check.');
855 $this->_state
= false;
856 $this->assign("messages", $messages);
857 if($d->couch_docid
&& $d->couch_revid
){
858 //Removing the temporary file which is used to create the hash
859 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
861 return $this->view_action($patient_id, $document_id);
864 // Added by Rod for metadata update.
866 function update_action_process($patient_id="", $document_id) {
868 if ($_POST['process'] != "true") {
869 die("process is '" . $_POST['process'] . "', expected 'true'");
873 $docdate = $_POST['docdate'];
874 $docname = $_POST['docname'];
875 $issue_id = $_POST['issue_id'];
877 if (is_numeric($document_id)) {
879 $d = new Document( $document_id );
880 $file_name = $d->get_url_file();
881 if ( $docname != '' &&
882 $docname != $file_name ) {
883 $path = $d->get_url_filepath();
884 $path = str_replace( $file_name, "", $path );
885 $new_url = $this->_rename_file( $path.$docname );
886 if ( rename( $d->get_url(), $new_url ) ) {
887 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
888 $url = preg_replace("|^(.*)://|","",$d->get_url());
889 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
890 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
891 if ( file_exists( $url ) ) {
897 $messages .= xl('Document successfully renamed.')."<br>";
899 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
903 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
904 $docdate = "'$docdate'";
908 if (!is_numeric($issue_id)) {
911 $couch_docid = $d->get_couch_docid();
912 $couch_revid = $d->get_couch_revid();
913 if($couch_docid && $couch_revid ){
914 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
915 "list_id = '$issue_id' " .
916 "WHERE id = '$document_id'";
917 $this->tree
->_db
->Execute($sql);
921 $sql = "UPDATE documents SET docdate = $docdate, " .
922 "list_id = '$issue_id' " .
923 "WHERE id = '$document_id'";
924 $this->tree
->_db
->Execute($sql);
926 $messages .= xl('Document date and issue updated successfully') . "<br>";
929 $this->_state
= false;
930 $this->assign("messages", $messages);
931 return $this->view_action($patient_id, $document_id);
934 function list_action($patient_id = "") {
935 $this->_last_node
= null;
936 $categories_list = $this->tree
->_get_categories_array($patient_id);
937 //print_r($categories_list);
939 $menu = new HTML_TreeMenu();
940 $rnode = $this->_array_recurse($this->tree
->tree
,$categories_list);
941 $menu->addItem($rnode);
942 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
943 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
945 $this->assign("tree_html",$treeMenu->toHTML());
947 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_list.html");
951 * This is a recursive function to rename a file to something that doesn't already exist.
952 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
953 * to ensure documents opened correctly by external browser viewers. If the counter is at the
954 * end of the file, then will use it (to continue to work with older files), however all new
955 * counters will be placed within filenames.
957 function _rename_file($fname) {
958 $file = basename($fname);
959 $fparts = split("\.",$fname);
960 $path = dirname($fname);
961 if (count($fparts) > 1) {
962 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
963 //increment the counter in filename
964 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] +
1;
965 $fname = join(".",$fparts);
967 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
968 //increment counter at end of filename (so compatible with previous openemr version files
969 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] +
1;
970 $fname = join(".",$fparts);
972 elseif (is_numeric($fparts[count($fparts) -1])) {
973 //leave date at end and place counter in filename
974 array_splice($fparts, -1, 0, "1");
975 $fname = join(".",$fparts);
978 //add the counter to filename
979 array_splice($fparts, -1, 0, "1");
980 $fname = join(".",$fparts);
983 else { // (count($fparts) == 1)
984 //place counter at end of filename
985 array_push($fparts,"1");
986 $fname = join(".",$fparts);
989 if (file_exists($fname)) {
990 return $this->_rename_file($fname);
997 function &_array_recurse($array,$categories = array()) {
998 if (!is_array($array)) {
1001 $node = &$this->_last_node
;
1002 $current_node = &$node;
1003 $expandedIcon = 'folder-expanded.gif';
1004 foreach($array as $id => $ar) {
1005 $icon = 'folder.gif';
1006 if (is_array($ar) ||
!empty($id)) {
1007 if ($node == null) {
1008 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1009 $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));
1010 $this->_last_node
= &$rnode;
1012 $current_node = &$rnode;
1015 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1016 $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)));
1017 $current_node = &$this->_last_node
;
1020 $this->_array_recurse($ar,$categories);
1023 if ($id === 0 && !empty($ar)) {
1024 $info = $this->tree
->get_node_info($id);
1025 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1026 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1029 //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
1030 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1031 if ($id !== 0 && is_object($node)) {
1032 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1033 $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)));
1039 // If there are documents in this document category, then add their
1040 // attributes to the current node.
1041 $icon = "file3.png";
1042 if (is_array($categories[$id])) {
1043 foreach ($categories[$id] as $doc) {
1044 if($this->tree
->get_node_name($id) == "CCR"){
1045 $current_node->addItem(new HTML_TreeNode(array(
1046 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1047 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1049 'expandedIcon' => $expandedIcon,
1050 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1052 }elseif($this->tree
->get_node_name($id) == "CCD"){
1053 $current_node->addItem(new HTML_TreeNode(array(
1054 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1055 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1057 'expandedIcon' => $expandedIcon,
1058 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1061 $current_node->addItem(new HTML_TreeNode(array(
1062 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1063 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1065 'expandedIcon' => $expandedIcon
1075 //function for logging the errors in writing file to CouchDB/Hard Disk
1076 function document_upload_download_log($patientid,$content){
1077 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1078 $log_file = 'log.txt';
1079 if(!is_dir($log_path))
1080 mkdir($log_path,0777,true);
1081 $LOG = fopen($log_path.$log_file,'a');
1082 fwrite($LOG,$content);
1087 //place to hold optional code
1088 //$first_node = array_keys($t->tree);
1089 //$first_node = $first_node[0];
1090 //$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')"));
1092 //$this->_last_node = &$node1;