Document module improvements, take 3.
[openemr.git] / controllers / C_Document.class.php
blobda37285ea683b4b3a3a1ffe4caedf9261f16575e
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");
14 class C_Document extends Controller {
16 var $template_mod;
17 var $documents;
18 var $document_categories;
19 var $tree;
20 var $_config;
21 var $file_path;
24 function C_Document($template_mod = "general") {
25 parent::Controller();
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/';
36 else{
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;
53 else {
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);
62 //print_r($t->tree);
63 $this->tree = $t;
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) {
81 $couchDB = false;
82 $harddisk = false;
83 if($GLOBALS['document_storage_method']==0){
84 $harddisk = true;
86 if($GLOBALS['document_storage_method']==1){
87 $couchDB = true;
90 if ($_POST['process'] != "true")
91 return;
93 $doDecryption = false;
94 $encrypted = $_POST['encrypted'];
95 $passphrase = $_POST['passphrase'];
96 if ( !$GLOBALS['hide_document_encryption'] &&
97 $encrypted && $passphrase ) {
98 $doDecryption = true;
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){
110 $upl_inc = 0;
111 foreach($_FILES['file']['name'] as $key => $value){
112 $fname = $value;
113 $err = "";
114 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
115 $fname = $value;
116 if (empty($fname)) {
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";
123 }else{
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 );
146 fclose($tmpfile);
147 unlink( $_FILES['file']['tmp_name'][$key] );
148 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "w+" );
149 fwrite( $tmpfile, $plaintext );
150 fclose( $tmpfile );
151 $_FILES['file']['size'][$key] = filesize( $_FILES['file']['tmp_name'][$key] );
154 $docid = '';
155 $resp = '';
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] );
162 fclose( $tmpfile );
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);
167 fclose($temp_file);
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);
177 $docid = $resp->_id;
178 $revid = $resp->_rev;
180 else{
181 $docid = $resp->id;
182 $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){
187 ob_start();
188 var_dump($resp);
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 if($harddisk == true){
201 $uploadSuccess = false;
202 $move_cmd = ($non_HTTP_owner ? "rename" : "move_uploaded_file");
203 if($move_cmd($_FILES['file']['tmp_name'][$key],$this->file_path.$fname)){
204 $uploadSuccess = true;
206 else{
207 $error .= xl("The file could not be succesfully stored, this error is usually related to permissions problems on the storage system")."\n";
211 $this->assign("upload_success", "true");
212 $d = new Document();
213 $d->storagemethod = $GLOBALS['document_storage_method'];
214 if($harddisk == true) {
215 $d->url = "file://" .$this->file_path.$fname;
216 if (is_numeric($_POST['path_depth'])) {
217 // this is for when directory structure is more than one level
218 $d->path_depth = $_POST['path_depth'];
221 else {
222 $d->url = $fname;
224 if($couchDB == true){
225 $d->couch_docid = $docid;
226 $d->couch_revid = $revid;
228 if ($_FILES['file']['type'][$key] == 'text/xml') {
229 $d->mimetype = 'application/xml';
231 else {
232 $d->mimetype = $_FILES['file']['type'][$key];
234 $d->size = $_FILES['file']['size'][$key];
235 $d->owner = $non_HTTP_owner ? $non_HTTP_owner : $_SESSION['authUserID'];
236 $sha1Hash = sha1_file( $this->file_path.$fname );
237 if($couchDB == true){
238 //Removing the temporary file which is used to create the hash
239 unlink($this->file_path.$fname);
241 $d->hash = $sha1Hash;
242 $d->type = $d->type_array['file_url'];
243 $d->set_foreign_id($patient_id);
244 if($harddisk == true || ($couchDB == true && $docid && $revid)){
245 $d->persist();
246 $d->populate();
248 $sentUploadStatus[] = $d;
249 $this->assign("file",$sentUploadStatus);
251 if (is_numeric($d->get_id()) && is_numeric($category_id)){
252 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
253 $d->_db->Execute($sql);
255 if($GLOBALS['couchdb_log']==1 && $log_content!=''){
256 $log_content .= "\r\n\r\n";
257 $this->document_upload_download_log($patient_id,$log_content);
263 $this->assign("error", nl2br($error));
264 //$this->_state = false;
265 $_POST['process'] = "";
266 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
269 function note_action_process($patient_id) {
271 if ($_POST['process'] != "true")
272 return;
274 $n = new Note();
275 $n->set_owner($_SESSION['authUserID']);
276 parent::populate_object($n);
277 $n->persist();
279 $this->_state = false;
280 $_POST['process'] = "";
281 return $this->view_action($patient_id,$n->get_foreign_id());
284 function default_action() {
285 return $this->list_action();
288 function view_action($patient_id="",$doc_id) {
289 // Added by Rod to support document delete:
290 global $gacl_object, $phpgacl_location;
291 global $ISSUE_TYPES;
293 require_once(dirname(__FILE__) . "/../library/acl.inc");
294 require_once(dirname(__FILE__) . "/../library/lists.inc");
296 $d = new Document($doc_id);
297 $n = new Note();
299 $notes = $n->notes_factory($doc_id);
301 $this->assign("file", $d);
302 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
303 $this->assign("NOTE_ACTION",$this->_link("note"));
304 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
305 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
307 // Added by Rod to support document delete:
308 $delete_string = '';
309 if (acl_check('admin', 'super')) {
310 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
311 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
313 $this->assign("delete_string", $delete_string);
314 $this->assign("REFRESH_ACTION",$this->_link("list"));
316 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
317 "document_id=" . $d->get_id() . "&process=true");
319 // Added by Rod to support document date update:
320 $this->assign("DOCDATE", $d->get_docdate());
321 $this->assign("UPDATE_ACTION",$this->_link("update") .
322 "document_id=" . $d->get_id() . "&process=true");
324 // Added by Rod to support document issue update:
325 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
326 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
327 "pid = $patient_id " . // AND enddate IS NULL " .
328 "ORDER BY type, begdate");
329 while ($irow = sqlFetchArray($ires)) {
330 $desc = $irow['type'];
331 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
332 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
333 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
334 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
336 $this->assign("ISSUES_LIST", $issues_options);
338 $this->assign("notes",$notes);
340 $this->_last_node = null;
342 $menu = new HTML_TreeMenu();
344 //pass an empty array because we don't want the documents for each category showing up in this list box
345 $rnode = $this->_array_recurse($this->tree->tree,array());
346 $menu->addItem($rnode);
347 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
349 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
351 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
352 $this->assign("activity", $activity);
354 return $this->list_action($patient_id);
357 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
359 $td = mcrypt_module_open( $cypher, '', $mode, '');
360 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
361 mcrypt_generic_init( $td, $key, $iv );
362 $crypttext = mcrypt_generic( $td, $plaintext );
363 mcrypt_generic_deinit( $td );
364 return $iv.$crypttext;
367 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
369 $plaintext = '';
370 $td = mcrypt_module_open( $cypher, '', $mode, '' );
371 $ivsize = mcrypt_enc_get_iv_size( $td) ;
372 $iv = substr( $crypttext, 0, $ivsize );
373 $crypttext = substr( $crypttext, $ivsize );
374 if( $iv )
376 mcrypt_generic_init( $td, $key, $iv );
377 $plaintext = mdecrypt_generic( $td, $crypttext );
379 return $plaintext;
383 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
385 $encrypted = $_POST['encrypted'];
386 $passphrase = $_POST['passphrase'];
387 $doEncryption = false;
388 if ( !$GLOBALS['hide_document_encryption'] &&
389 $encrypted == "true" &&
390 $passphrase ) {
391 $doEncryption = true;
394 //controller function ruins booleans, so need to manually re-convert to booleans
395 if ($as_file == "true") {
396 $as_file=true;
398 else if ($as_file == "false") {
399 $as_file=false;
401 if ($original_file == "true") {
402 $original_file=true;
404 else if ($original_file == "false") {
405 $original_file=false;
408 $d = new Document($document_id);
409 $url = $d->get_url();
410 $storagemethod = $d->get_storagemethod();
411 $couch_docid = $d->get_couch_docid();
412 $couch_revid = $d->get_couch_revid();
414 if($couch_docid && $couch_revid && $original_file){
415 $couch = new CouchDB();
416 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
417 $resp = $couch->retrieve_doc($data);
418 $content = $resp->data;
419 if($content=='' && $GLOBALS['couchdb_log']==1){
420 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
421 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
422 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
423 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
424 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
425 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
426 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
427 die(xl("File retrieval from CouchDB failed"));
429 header('Content-Description: File Transfer');
430 header('Content-Transfer-Encoding: binary');
431 header('Expires: 0');
432 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
433 header('Pragma: public');
434 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
435 $fh = fopen($tmpcouchpath,"w");
436 fwrite($fh,base64_decode($content));
437 fclose($fh);
438 $f = fopen($tmpcouchpath,"r");
439 if ( $doEncryption ) {
440 $filetext = fread( $f, filesize($tmpcouchpath) );
441 $ciphertext = $this->encrypt( $filetext, $passphrase );
442 $tmpfilepath = $GLOBALS['temporary_files_dir'];
443 $tmpfilename = "/encrypted_".$d->get_url_file();
444 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
445 fwrite( $tmpfile, $ciphertext );
446 fclose( $tmpfile );
447 header('Content-Disposition: attachment; filename='.$tmpfilename );
448 header("Content-Type: application/octet-stream" );
449 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
450 ob_clean();
451 flush();
452 readfile( $tmpfilepath.$tmpfilename );
453 unlink( $tmpfilepath.$tmpfilename );
454 } else {
455 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
456 header("Content-Type: " . $d->get_mimetype());
457 header("Content-Length: " . filesize($tmpcouchpath));
458 fpassthru($f);
460 fclose($f);
461 if($content!='')
462 unlink($tmpcouchpath);
463 exit;//exits only if file download from CouchDB is successfull.
465 //strip url of protocol handler
466 $url = preg_replace("|^(.*)://|","",$url);
468 //change full path to current webroot. this is for documents that may have
469 //been moved from a different filesystem and the full path in the database
470 //is not current. this is also for documents that may of been moved to
471 //different patients. Note that the path_depth is used to see how far down
472 //the path to go. For example, originally the path_depth was always 1, which
473 //only allowed things like documents/1/<file>, but now can have more structured
474 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
475 // etc.
476 // NOTE that $from_filename and basename($url) are the same thing
477 $from_all = explode("/",$url);
478 $from_filename = array_pop($from_all);
479 $from_pathname_array = array();
480 for ($i=0;$i<$d->get_path_depth();$i++) {
481 $from_pathname_array[] = array_pop($from_all);
483 $from_pathname_array = array_reverse($from_pathname_array);
484 $from_pathname = implode("/",$from_pathname_array);
485 if($couch_docid && $couch_revid){
486 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
487 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
490 else{
491 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
494 if (file_exists($temp_url)) {
495 $url = $temp_url;
499 if (!file_exists($url)) {
500 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;
503 else {
504 if ($original_file) {
505 //normal case when serving the file referenced in database
506 header('Content-Description: File Transfer');
507 header('Content-Transfer-Encoding: binary');
508 header('Expires: 0');
509 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
510 header('Pragma: public');
511 $f = fopen($url,"r");
512 if ( $doEncryption ) {
513 $filetext = fread( $f, filesize($url) );
514 $ciphertext = $this->encrypt( $filetext, $passphrase );
515 $tmpfilepath = $GLOBALS['temporary_files_dir'];
516 $tmpfilename = "/encrypted_".$d->get_url_file();
517 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
518 fwrite( $tmpfile, $ciphertext );
519 fclose( $tmpfile );
520 header('Content-Disposition: attachment; filename='.$tmpfilename );
521 header("Content-Type: application/octet-stream" );
522 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
523 ob_clean();
524 flush();
525 readfile( $tmpfilepath.$tmpfilename );
526 unlink( $tmpfilepath.$tmpfilename );
527 } else {
528 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
529 header("Content-Type: " . $d->get_mimetype());
530 header("Content-Length: " . filesize($url));
531 fpassthru($f);
533 exit;
535 else {
536 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
537 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
538 if($couch_docid && $couch_revid){
539 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
541 else{
542 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;
544 header("Pragma: public");
545 header("Expires: 0");
546 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
547 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
548 header("Content-Type: image/jpeg");
549 header("Content-Length: " . filesize($url));
550 $f = fopen($url,"r");
551 fpassthru($f);
552 if($couch_docid && $couch_revid){
553 fclose($f);
554 unlink($url);
555 $url=str_replace("_converted.jpg",'.pdf',$url);
556 unlink($url);
558 exit;
563 function queue_action($patient_id="") {
564 $messages = $this->_tpl_vars['messages'];
565 $queue_files = array();
567 //see if the repository exists and it is a directory else error
568 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
569 $dir = opendir($this->_config['repository']);
570 //read each entry in the directory
571 while (($file = readdir($dir)) !== false) {
572 //concat the filename and path
573 $file = $this->_config['repository'] .$file;
574 $file_info = array();
575 //if the filename is a file get its info and put into a tmp array
576 if (is_file($file) && strpos(basename($file),".") !== 0) {
577 $file_info['filename'] = basename($file);
578 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
579 $d = Document::document_factory_url("file://" . $file);
580 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
581 $file_info['patient_id'] = $patient_match[1];
582 $file_info['document_id'] = $d->get_id();
583 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
585 //merge the tmp array into the larger array
586 $queue_files[] = $file_info;
589 closedir($dir);
591 else {
592 $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";
596 $this->assign("queue_files",$queue_files);
597 $this->_last_node = null;
599 $menu = new HTML_TreeMenu();
601 //pass an empty array because we don't want the documents for each category showing up in this list box
602 $rnode = $this->_array_recurse($this->tree->tree,array());
603 $menu->addItem($rnode);
604 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
606 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
608 $this->assign("messages",nl2br($messages));
609 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
612 function queue_action_process() {
613 if ($_POST['process'] != "true")
614 return;
616 $messages = $this->_tpl_vars['messages'];
618 //build a category tree so we can have a list of category ids that are valid
619 $ct = new CategoryTree(1);
620 $categories = $ct->_id_name;
622 //see if there were and posted files and assign them
623 $files = null;
624 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
626 //loop through posted files
627 foreach($files as $doc_id=> $file) {
628 //only operate on files checked as active
629 if (!$file['active']) continue;
631 //run basic validation checks
632 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
633 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
634 continue;
637 //validate that the pod exists
638 $d = new Document($doc_id);
639 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
640 $result = $d->_db->Execute($sql);
642 if (!$result || $result->EOF) {
643 //patient id does not exist
644 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
645 continue;
648 //validate that the category id exists
649 if (!isset($categories[$file['category_id']])) {
650 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
651 continue;
654 //now do the work of moving the file
655 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
657 //see if the patient dir exists in the repository and create if not
658 if (!file_exists($new_path)) {
659 if (!mkdir($new_path,0700)) {
660 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
661 continue;
665 //fname is the name of the file after it is moved
666 $fname = $file['name'];
668 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
669 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
670 if ($patient_match[1] == $file['patient_id']) {
671 $fname = preg_replace("/^([0-9]+)_/","",$fname);
674 //filenames should not have funny chars
675 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
677 //see if there is an existing file with the same name and rename as necessary
678 if (file_exists($new_path.$file['name'])) {
679 $messages .= "File with same name already exists at location: " . $new_path . "\n";
680 $fname = basename($this->_rename_file($new_path.$file['name']));
681 $messages .= "Current file name was changed to " . $fname ."\n";
684 //now move the file
685 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
686 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
687 $d->url = "file://" .$new_path.$fname;
688 $d->set_foreign_id($file['patient_id']);
689 $d->set_mimetype($mimetype);
690 $d->persist();
691 $d->populate();
693 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
694 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
695 $d->_db->Execute($sql);
698 else {
699 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
702 $this->assign("messages",$messages);
703 $_POST['process'] = "";
706 function move_action_process($patient_id="",$document_id) {
707 if ($_POST['process'] != "true")
708 return;
710 $new_category_id = $_POST['new_category_id'];
711 $new_patient_id = $_POST['new_patient_id'];
713 //move to new category
714 if (is_numeric($new_category_id) && is_numeric($document_id)) {
715 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
716 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
717 //echo $sql;
718 $this->tree->_db->Execute($sql);
721 //move to new patient
722 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
723 $d = new Document($document_id);
724 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
725 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
726 $result = $d->_db->Execute($sql);
728 if (!$result || $result->EOF) {
729 //patient id does not exist
730 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
732 else {
733 $couchsavefailed = !$d->change_patient($new_patient_id);
735 $this->_state = false;
736 if(!$couchsavefailed){
738 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
740 else{
742 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
744 $this->assign("messages",$messages);
745 return $this->list_action($patient_id);
748 //in this case return the document to the queue instead of moving it
749 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
750 $d = new Document($document_id);
751 $new_path = $this->_config['repository'];
752 $fname = $d->get_url_file();
754 //see if there is an existing file with the same name and rename as necessary
755 if (file_exists($new_path.$d->get_url_file())) {
756 $messages .= "File with same name already exists in the queue.\n";
757 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
758 $messages .= "Current file name was changed to " . $fname ."\n";
761 //now move the file
762 if (rename($d->get_url_filepath(),$new_path.$fname)) {
763 $d->url = "file://" .$new_path.$fname;
764 $d->set_foreign_id("");
765 $d->persist();
766 $d->persist();
767 $d->populate();
769 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
770 $d->_db->Execute($sql);
771 $messages .= "Document returned to queue successfully.\n";
774 else {
775 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
778 $this->_state = false;
779 $this->assign("messages",$messages);
780 return $this->list_action($patient_id);
783 $this->_state = false;
784 $this->assign("messages",$messages);
785 return $this->view_action($patient_id,$document_id);
788 function validate_action_process($patient_id="", $document_id) {
790 $d = new Document($document_id);
791 if($d->couch_docid && $d->couch_revid){
792 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
793 $url = $file_path.$d->get_url();
794 $couch = new CouchDB();
795 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
796 $resp = $couch->retrieve_doc($data);
797 $content = $resp->data;
798 //--------Temporarily writing the file for calculating the hash--------//
799 //-----------Will be removed after calculating the hash value----------//
800 $temp_file = fopen($url,"w");
801 fwrite($temp_file,base64_decode($content));
802 fclose($temp_file);
804 else{
805 $url = $d->get_url();
807 //strip url of protocol handler
808 $url = preg_replace("|^(.*)://|","",$url);
810 //change full path to current webroot. this is for documents that may have
811 //been moved from a different filesystem and the full path in the database
812 //is not current. this is also for documents that may of been moved to
813 //different patients. Note that the path_depth is used to see how far down
814 //the path to go. For example, originally the path_depth was always 1, which
815 //only allowed things like documents/1/<file>, but now can have more structured
816 //directories. For example a path_depth of 2 can give documents/encounters/1/<file>
817 // etc.
818 // NOTE that $from_filename and basename($url) are the same thing
819 $from_all = explode("/",$url);
820 $from_filename = array_pop($from_all);
821 $from_pathname_array = array();
822 for ($i=0;$i<$d->get_path_depth();$i++) {
823 $from_pathname_array[] = array_pop($from_all);
825 $from_pathname_array = array_reverse($from_pathname_array);
826 $from_pathname = implode("/",$from_pathname_array);
827 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;
828 if (file_exists($temp_url)) {
829 $url = $temp_url;
832 if ($_POST['process'] != "true") {
833 die("process is '" . $_POST['process'] . "', expected 'true'");
834 return;
837 $d = new Document( $document_id );
838 $current_hash = sha1_file( $url );
839 $messages = xl('Current Hash').": ".$current_hash."<br>";
840 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
841 if ( $d->get_hash() == '' ) {
842 $d->hash = $current_hash;
843 $d->persist();
844 $d->populate();
845 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
846 } else if ( $current_hash != $d->get_hash() ) {
847 $messages .= xl('Hash does not match. Data integrity has been compromised.');
848 } else {
849 $messages .= xl('Document passed integrity check.');
851 $this->_state = false;
852 $this->assign("messages", $messages);
853 if($d->couch_docid && $d->couch_revid){
854 //Removing the temporary file which is used to create the hash
855 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
857 return $this->view_action($patient_id, $document_id);
860 // Added by Rod for metadata update.
862 function update_action_process($patient_id="", $document_id) {
864 if ($_POST['process'] != "true") {
865 die("process is '" . $_POST['process'] . "', expected 'true'");
866 return;
869 $docdate = $_POST['docdate'];
870 $docname = $_POST['docname'];
871 $issue_id = $_POST['issue_id'];
873 if (is_numeric($document_id)) {
874 $messages = '';
875 $d = new Document( $document_id );
876 $file_name = $d->get_url_file();
877 if ( $docname != '' &&
878 $docname != $file_name ) {
879 $path = $d->get_url_filepath();
880 $path = str_replace( $file_name, "", $path );
881 $new_url = $this->_rename_file( $path.$docname );
882 if ( rename( $d->get_url(), $new_url ) ) {
883 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
884 $url = preg_replace("|^(.*)://|","",$d->get_url());
885 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
886 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
887 if ( file_exists( $url ) ) {
888 unlink( $url );
890 $d->url = $new_url;
891 $d->persist();
892 $d->populate();
893 $messages .= xl('Document successfully renamed.')."<br>";
894 } else {
895 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
899 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
900 $docdate = "'$docdate'";
901 } else {
902 $docdate = "NULL";
904 if (!is_numeric($issue_id)) {
905 $issue_id = 0;
907 $couch_docid = $d->get_couch_docid();
908 $couch_revid = $d->get_couch_revid();
909 if($couch_docid && $couch_revid ){
910 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
911 "list_id = '$issue_id' " .
912 "WHERE id = '$document_id'";
913 $this->tree->_db->Execute($sql);
916 else{
917 $sql = "UPDATE documents SET docdate = $docdate, " .
918 "list_id = '$issue_id' " .
919 "WHERE id = '$document_id'";
920 $this->tree->_db->Execute($sql);
922 $messages .= xl('Document date and issue updated successfully') . "<br>";
925 $this->_state = false;
926 $this->assign("messages", $messages);
927 return $this->view_action($patient_id, $document_id);
930 function list_action($patient_id = "") {
931 $this->_last_node = null;
932 $categories_list = $this->tree->_get_categories_array($patient_id);
933 //print_r($categories_list);
935 $menu = new HTML_TreeMenu();
936 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
937 $menu->addItem($rnode);
938 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
939 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
941 $this->assign("tree_html",$treeMenu->toHTML());
943 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
947 * This is a recursive function to rename a file to something that doesn't already exist.
948 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
949 * to ensure documents opened correctly by external browser viewers. If the counter is at the
950 * end of the file, then will use it (to continue to work with older files), however all new
951 * counters will be placed within filenames.
953 function _rename_file($fname) {
954 $file = basename($fname);
955 $fparts = split("\.",$fname);
956 $path = dirname($fname);
957 if (count($fparts) > 1) {
958 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
959 //increment the counter in filename
960 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
961 $fname = join(".",$fparts);
963 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
964 //increment counter at end of filename (so compatible with previous openemr version files
965 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
966 $fname = join(".",$fparts);
968 elseif (is_numeric($fparts[count($fparts) -1])) {
969 //leave date at end and place counter in filename
970 array_splice($fparts, -1, 0, "1");
971 $fname = join(".",$fparts);
973 else {
974 //add the counter to filename
975 array_splice($fparts, -1, 0, "1");
976 $fname = join(".",$fparts);
979 else { // (count($fparts) == 1)
980 //place counter at end of filename
981 array_push($fparts,"1");
982 $fname = join(".",$fparts);
985 if (file_exists($fname)) {
986 return $this->_rename_file($fname);
988 else {
989 return($fname);
993 function &_array_recurse($array,$categories = array()) {
994 if (!is_array($array)) {
995 $array = array();
997 $node = &$this->_last_node;
998 $current_node = &$node;
999 $expandedIcon = 'folder-expanded.gif';
1000 foreach($array as $id => $ar) {
1001 $icon = 'folder.gif';
1002 if (is_array($ar) || !empty($id)) {
1003 if ($node == null) {
1004 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
1005 $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));
1006 $this->_last_node = &$rnode;
1007 $node = &$rnode;
1008 $current_node = &$rnode;
1010 else {
1011 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
1012 $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)));
1013 $current_node = &$this->_last_node;
1016 $this->_array_recurse($ar,$categories);
1018 else {
1019 if ($id === 0 && !empty($ar)) {
1020 $info = $this->tree->get_node_info($id);
1021 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
1022 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1024 else {
1025 //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
1026 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1027 if ($id !== 0 && is_object($node)) {
1028 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1029 $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)));
1035 // If there are documents in this document category, then add their
1036 // attributes to the current node.
1037 $icon = "file3.png";
1038 if (is_array($categories[$id])) {
1039 foreach ($categories[$id] as $doc) {
1040 if($this->tree->get_node_name($id) == "CCR"){
1041 $current_node->addItem(new HTML_TreeNode(array(
1042 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1043 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1044 'icon' => $icon,
1045 'expandedIcon' => $expandedIcon,
1046 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1047 )));
1048 }elseif($this->tree->get_node_name($id) == "CCD"){
1049 $current_node->addItem(new HTML_TreeNode(array(
1050 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1051 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1052 'icon' => $icon,
1053 'expandedIcon' => $expandedIcon,
1054 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1055 )));
1056 }else{
1057 $current_node->addItem(new HTML_TreeNode(array(
1058 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1059 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1060 'icon' => $icon,
1061 'expandedIcon' => $expandedIcon
1062 )));
1068 return $node;
1071 //function for logging the errors in writing file to CouchDB/Hard Disk
1072 function document_upload_download_log($patientid,$content){
1073 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1074 $log_file = 'log.txt';
1075 if(!is_dir($log_path))
1076 mkdir($log_path,0777,true);
1077 $LOG = fopen($log_path.$log_file,'a');
1078 fwrite($LOG,$content);
1079 fclose($LOG);
1083 //place to hold optional code
1084 //$first_node = array_keys($t->tree);
1085 //$first_node = $first_node[0];
1086 //$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')"));
1088 //$this->_last_node = &$node1;