Replaced all "=&$var" with "= &$var" to standardize for later removal of deprecated...
[openemr.git] / controllers / C_Document.class.php
blob5032c96803bbedfbbf0d31fee5d5eeb878a5976d
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 $this->file_path = $this->_config['repository'] . preg_replace("/[^A-Za-z0-9]/","_",$_GET['patient_id']) . "/";
39 $this->_args = array("patient_id" => $_GET['patient_id']);
41 $this->assign("STYLE", $GLOBALS['style']);
42 $t = new CategoryTree(1);
43 //print_r($t->tree);
44 $this->tree = $t;
47 function upload_action($patient_id,$category_id) {
48 $category_name = $this->tree->get_node_name($category_id);
49 $this->assign("category_id", $category_id);
50 $this->assign("category_name", $category_name);
51 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
52 $this->assign("patient_id", $patient_id);
53 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
54 $this->assign("activity", $activity);
55 return $this->list_action($patient_id);
58 //Upload multiple files on single click
59 //2013-02-10 EMR Direct: added $non_HTTP_owner to allow storage of Direct Message attachments
60 //through this mechanism, and is set to the user_id for the background process adding the document
61 function upload_action_process($non_HTTP_owner=false) {
62 $couchDB = false;
63 $harddisk = false;
64 if($GLOBALS['document_storage_method']==0){
65 $harddisk = true;
67 if($GLOBALS['document_storage_method']==1){
68 $couchDB = true;
71 if ($_POST['process'] != "true")
72 return;
74 $doDecryption = false;
75 $encrypted = $_POST['encrypted'];
76 $passphrase = $_POST['passphrase'];
77 if ( !$GLOBALS['hide_document_encryption'] &&
78 $encrypted && $passphrase ) {
79 $doDecryption = true;
82 if (is_numeric($_POST['category_id'])) {
83 $category_id = $_POST['category_id'];
85 if (is_numeric($_POST['patient_id'])) {
86 $patient_id = $_POST['patient_id'];
89 $sentUploadStatus = array();
90 if( count($_FILES['file']['name']) > 0){
91 $upl_inc = 0;
92 foreach($_FILES['file']['name'] as $key => $value){
93 $fname = $value;
94 $err = "";
95 if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {
96 $fname = $value;
97 if (empty($fname)) {
98 $fname = htmlentities("<empty>");
100 $error = "Error number: " . $_FILES['file']['error'][$key] . " occured while uploading file named: " . $fname . "\n";
101 if ($_FILES['file']['size'][$key] == 0) {
102 $error .= "The system does not permit uploading files of with size 0.\n";
104 }else{
106 if (!file_exists($this->file_path)) {
107 if (!mkdir($this->file_path,0700)) {
108 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
112 if ( $_POST['destination'] != '' ) {
113 $fname = $_POST['destination'];
115 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
116 if (file_exists($this->file_path.$fname)) {
117 $error .= xl('File with same name already exists at location:','','',' ') . $this->file_path . "\n";
118 $fname = basename($this->_rename_file($this->file_path.$fname));
119 $_FILES['file']['name'][$key] = $fname;
120 $error .= xl('Current file name was changed to','','',' ') . $fname ."\n";
123 if ( $doDecryption ) {
124 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key] , "r" );
125 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
126 $plaintext = $this->decrypt( $filetext, $passphrase );
127 fclose($tmpfile);
128 unlink( $_FILES['file']['tmp_name'][$key] );
129 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "w+" );
130 fwrite( $tmpfile, $plaintext );
131 fclose( $tmpfile );
132 $_FILES['file']['size'][$key] = filesize( $_FILES['file']['tmp_name'][$key] );
135 $docid = '';
136 $resp = '';
137 if($couchDB == true){
138 $couch = new CouchDB();
139 $docname = $_SESSION['authId'].$patient_id.$encounter.$fname.date("%Y-%m-%d H:i:s");
140 $docid = $couch->stringToId($docname);
141 $tmpfile = fopen( $_FILES['file']['tmp_name'][$key], "rb" );
142 $filetext = fread( $tmpfile, $_FILES['file']['size'][$key] );
143 fclose( $tmpfile );
144 //--------Temporarily writing the file for calculating the hash--------//
145 //-----------Will be removed after calculating the hash value----------//
146 $temp_file = fopen($this->file_path.$fname,"w");
147 fwrite($temp_file,$filetext);
148 fclose($temp_file);
149 //---------------------------------------------------------------------//
151 $json = json_encode(base64_encode($filetext));
152 $db = $GLOBALS['couchdb_dbase'];
153 $data = array($db,$docid,$patient_id,$encounter,$_FILES['file']['type'][$key],$json);
154 $resp = $couch->check_saveDOC($data);
155 if(!$resp->id || !$resp->_rev){
156 $data = array($db,$docid,$patient_id,$encounter);
157 $resp = $couch->retrieve_doc($data);
158 $docid = $resp->_id;
159 $revid = $resp->_rev;
161 else{
162 $docid = $resp->id;
163 $revid = $resp->rev;
165 if(!$docid && !$revid){ //if couchdb save failed
166 $error .= "<font color='red'><b>".xl("The file could not be saved to CouchDB.") . "</b></font>\n";
167 if($GLOBALS['couchdb_log']==1){
168 ob_start();
169 var_dump($resp);
170 $couchError=ob_get_clean();
171 $log_content = date('Y-m-d H:i:s')." ==> Uploading document: ".$fname."\r\n";
172 $log_content .= date('Y-m-d H:i:s')." ==> Failed to Store document content to CouchDB.\r\n";
173 $log_content .= date('Y-m-d H:i:s')." ==> Document ID: ".$docid."\r\n";
174 $log_content .= date('Y-m-d H:i:s')." ==> ".print_r($data,1)."\r\n";
175 $log_content .= $couchError;
176 $this->document_upload_download_log($patient_id,$log_content);//log error if any, for testing phase only
181 if($harddisk == true){
182 $uploadSuccess = false;
183 $move_cmd = ($non_HTTP_owner ? "rename" : "move_uploaded_file");
184 if($move_cmd($_FILES['file']['tmp_name'][$key],$this->file_path.$fname)){
185 $uploadSuccess = true;
187 else{
188 $error .= xl("The file could not be succesfully stored, this error is usually related to permissions problems on the storage system")."\n";
192 $this->assign("upload_success", "true");
193 $d = new Document();
194 $d->storagemethod = $GLOBALS['document_storage_method'];
195 if($harddisk == true)
196 $d->url = "file://" .$this->file_path.$fname;
197 else
198 $d->url = $fname;
199 if($couchDB == true){
200 $d->couch_docid = $docid;
201 $d->couch_revid = $revid;
203 if ($_FILES['file']['type'][$key] == 'text/xml') {
204 $d->mimetype = 'application/xml';
206 else {
207 $d->mimetype = $_FILES['file']['type'][$key];
209 $d->size = $_FILES['file']['size'][$key];
210 $d->owner = $non_HTTP_owner ? $non_HTTP_owner : $_SESSION['authUserID'];
211 $sha1Hash = sha1_file( $this->file_path.$fname );
212 if($couchDB == true){
213 //Removing the temporary file which is used to create the hash
214 unlink($this->file_path.$fname);
216 $d->hash = $sha1Hash;
217 $d->type = $d->type_array['file_url'];
218 $d->set_foreign_id($patient_id);
219 if($harddisk == true || ($couchDB == true && $docid && $revid)){
220 $d->persist();
221 $d->populate();
223 $sentUploadStatus[] = $d;
224 $this->assign("file",$sentUploadStatus);
226 if (is_numeric($d->get_id()) && is_numeric($category_id)){
227 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
228 $d->_db->Execute($sql);
230 if($GLOBALS['couchdb_log']==1 && $log_content!=''){
231 $log_content .= "\r\n\r\n";
232 $this->document_upload_download_log($patient_id,$log_content);
238 $this->assign("error", nl2br($error));
239 //$this->_state = false;
240 $_POST['process'] = "";
241 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
244 function note_action_process($patient_id) {
246 if ($_POST['process'] != "true")
247 return;
249 $n = new Note();
250 $n->set_owner($_SESSION['authUserID']);
251 parent::populate_object($n);
252 $n->persist();
254 $this->_state = false;
255 $_POST['process'] = "";
256 return $this->view_action($patient_id,$n->get_foreign_id());
259 function default_action() {
260 return $this->list_action();
263 function view_action($patient_id="",$doc_id) {
264 // Added by Rod to support document delete:
265 global $gacl_object, $phpgacl_location;
266 global $ISSUE_TYPES;
268 require_once(dirname(__FILE__) . "/../library/acl.inc");
269 require_once(dirname(__FILE__) . "/../library/lists.inc");
271 $d = new Document($doc_id);
272 $n = new Note();
274 $notes = $n->notes_factory($doc_id);
276 $this->assign("file", $d);
277 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
278 $this->assign("NOTE_ACTION",$this->_link("note"));
279 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
280 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
282 // Added by Rod to support document delete:
283 $delete_string = '';
284 if (acl_check('admin', 'super')) {
285 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
286 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
288 $this->assign("delete_string", $delete_string);
289 $this->assign("REFRESH_ACTION",$this->_link("list"));
291 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
292 "document_id=" . $d->get_id() . "&process=true");
294 // Added by Rod to support document date update:
295 $this->assign("DOCDATE", $d->get_docdate());
296 $this->assign("UPDATE_ACTION",$this->_link("update") .
297 "document_id=" . $d->get_id() . "&process=true");
299 // Added by Rod to support document issue update:
300 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
301 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
302 "pid = $patient_id " . // AND enddate IS NULL " .
303 "ORDER BY type, begdate");
304 while ($irow = sqlFetchArray($ires)) {
305 $desc = $irow['type'];
306 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
307 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
308 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
309 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
311 $this->assign("ISSUES_LIST", $issues_options);
313 $this->assign("notes",$notes);
315 $this->_last_node = null;
317 $menu = new HTML_TreeMenu();
319 //pass an empty array because we don't want the documents for each category showing up in this list box
320 $rnode = $this->_array_recurse($this->tree->tree,array());
321 $menu->addItem($rnode);
322 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
324 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
326 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
327 $this->assign("activity", $activity);
329 return $this->list_action($patient_id);
332 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
334 $td = mcrypt_module_open( $cypher, '', $mode, '');
335 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
336 mcrypt_generic_init( $td, $key, $iv );
337 $crypttext = mcrypt_generic( $td, $plaintext );
338 mcrypt_generic_deinit( $td );
339 return $iv.$crypttext;
342 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
344 $plaintext = '';
345 $td = mcrypt_module_open( $cypher, '', $mode, '' );
346 $ivsize = mcrypt_enc_get_iv_size( $td) ;
347 $iv = substr( $crypttext, 0, $ivsize );
348 $crypttext = substr( $crypttext, $ivsize );
349 if( $iv )
351 mcrypt_generic_init( $td, $key, $iv );
352 $plaintext = mdecrypt_generic( $td, $crypttext );
354 return $plaintext;
358 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
360 $encrypted = $_POST['encrypted'];
361 $passphrase = $_POST['passphrase'];
362 $doEncryption = false;
363 if ( !$GLOBALS['hide_document_encryption'] &&
364 $encrypted == "true" &&
365 $passphrase ) {
366 $doEncryption = true;
369 //controller function ruins booleans, so need to manually re-convert to booleans
370 if ($as_file == "true") {
371 $as_file=true;
373 else if ($as_file == "false") {
374 $as_file=false;
376 if ($original_file == "true") {
377 $original_file=true;
379 else if ($original_file == "false") {
380 $original_file=false;
383 $d = new Document($document_id);
384 $url = $d->get_url();
385 $storagemethod = $d->get_storagemethod();
386 $couch_docid = $d->get_couch_docid();
387 $couch_revid = $d->get_couch_revid();
389 if($couch_docid && $couch_revid && $original_file){
390 $couch = new CouchDB();
391 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
392 $resp = $couch->retrieve_doc($data);
393 $content = $resp->data;
394 if($content=='' && $GLOBALS['couchdb_log']==1){
395 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
396 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
397 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
398 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
399 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
400 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
401 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
402 die(xl("File retrieval from CouchDB failed"));
404 header('Content-Description: File Transfer');
405 header('Content-Transfer-Encoding: binary');
406 header('Expires: 0');
407 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
408 header('Pragma: public');
409 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
410 $fh = fopen($tmpcouchpath,"w");
411 fwrite($fh,base64_decode($content));
412 fclose($fh);
413 $f = fopen($tmpcouchpath,"r");
414 if ( $doEncryption ) {
415 $filetext = fread( $f, filesize($tmpcouchpath) );
416 $ciphertext = $this->encrypt( $filetext, $passphrase );
417 $tmpfilepath = $GLOBALS['temporary_files_dir'];
418 $tmpfilename = "/encrypted_".$d->get_url_file();
419 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
420 fwrite( $tmpfile, $ciphertext );
421 fclose( $tmpfile );
422 header('Content-Disposition: attachment; filename='.$tmpfilename );
423 header("Content-Type: application/octet-stream" );
424 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
425 ob_clean();
426 flush();
427 readfile( $tmpfilepath.$tmpfilename );
428 unlink( $tmpfilepath.$tmpfilename );
429 } else {
430 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
431 header("Content-Type: " . $d->get_mimetype());
432 header("Content-Length: " . filesize($tmpcouchpath));
433 fpassthru($f);
435 fclose($f);
436 if($content!='')
437 unlink($tmpcouchpath);
438 exit;//exits only if file download from CouchDB is successfull.
440 //strip url of protocol handler
441 $url = preg_replace("|^(.*)://|","",$url);
443 //change full path to current webroot. this is for documents that may have
444 //been moved from a different filesystem and the full path in the database
445 //is not current. this is also for documents that may of been moved to
446 //different patients
447 // NOTE that $from_filename and basename($url) are the same thing
448 $from_all = explode("/",$url);
449 $from_filename = array_pop($from_all);
450 $from_patientid = array_pop($from_all);
451 if($couch_docid && $couch_revid){
452 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
453 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
456 else{
457 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
460 if (file_exists($temp_url)) {
461 $url = $temp_url;
465 if (!file_exists($url)) {
466 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;
469 else {
470 if ($original_file) {
471 //normal case when serving the file referenced in database
472 header('Content-Description: File Transfer');
473 header('Content-Transfer-Encoding: binary');
474 header('Expires: 0');
475 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
476 header('Pragma: public');
477 $f = fopen($url,"r");
478 if ( $doEncryption ) {
479 $filetext = fread( $f, filesize($url) );
480 $ciphertext = $this->encrypt( $filetext, $passphrase );
481 $tmpfilepath = $GLOBALS['temporary_files_dir'];
482 $tmpfilename = "/encrypted_".$d->get_url_file();
483 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
484 fwrite( $tmpfile, $ciphertext );
485 fclose( $tmpfile );
486 header('Content-Disposition: attachment; filename='.$tmpfilename );
487 header("Content-Type: application/octet-stream" );
488 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
489 ob_clean();
490 flush();
491 readfile( $tmpfilepath.$tmpfilename );
492 unlink( $tmpfilepath.$tmpfilename );
493 } else {
494 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
495 header("Content-Type: " . $d->get_mimetype());
496 header("Content-Length: " . filesize($url));
497 fpassthru($f);
499 exit;
501 else {
502 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
503 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
504 if($couch_docid && $couch_revid){
505 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
507 else{
508 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
510 header("Pragma: public");
511 header("Expires: 0");
512 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
513 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
514 header("Content-Type: image/jpeg");
515 header("Content-Length: " . filesize($url));
516 $f = fopen($url,"r");
517 fpassthru($f);
518 if($couch_docid && $couch_revid){
519 fclose($f);
520 unlink($url);
521 $url=str_replace("_converted.jpg",'.pdf',$url);
522 unlink($url);
524 exit;
529 function queue_action($patient_id="") {
530 $messages = $this->_tpl_vars['messages'];
531 $queue_files = array();
533 //see if the repository exists and it is a directory else error
534 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
535 $dir = opendir($this->_config['repository']);
536 //read each entry in the directory
537 while (($file = readdir($dir)) !== false) {
538 //concat the filename and path
539 $file = $this->_config['repository'] .$file;
540 $file_info = array();
541 //if the filename is a file get its info and put into a tmp array
542 if (is_file($file) && strpos(basename($file),".") !== 0) {
543 $file_info['filename'] = basename($file);
544 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
545 $d = Document::document_factory_url("file://" . $file);
546 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
547 $file_info['patient_id'] = $patient_match[1];
548 $file_info['document_id'] = $d->get_id();
549 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
551 //merge the tmp array into the larger array
552 $queue_files[] = $file_info;
555 closedir($dir);
557 else {
558 $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";
562 $this->assign("queue_files",$queue_files);
563 $this->_last_node = null;
565 $menu = new HTML_TreeMenu();
567 //pass an empty array because we don't want the documents for each category showing up in this list box
568 $rnode = $this->_array_recurse($this->tree->tree,array());
569 $menu->addItem($rnode);
570 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
572 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
574 $this->assign("messages",nl2br($messages));
575 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
578 function queue_action_process() {
579 if ($_POST['process'] != "true")
580 return;
582 $messages = $this->_tpl_vars['messages'];
584 //build a category tree so we can have a list of category ids that are valid
585 $ct = new CategoryTree(1);
586 $categories = $ct->_id_name;
588 //see if there were and posted files and assign them
589 $files = null;
590 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
592 //loop through posted files
593 foreach($files as $doc_id=> $file) {
594 //only operate on files checked as active
595 if (!$file['active']) continue;
597 //run basic validation checks
598 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
599 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
600 continue;
603 //validate that the pod exists
604 $d = new Document($doc_id);
605 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
606 $result = $d->_db->Execute($sql);
608 if (!$result || $result->EOF) {
609 //patient id does not exist
610 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
611 continue;
614 //validate that the category id exists
615 if (!isset($categories[$file['category_id']])) {
616 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
617 continue;
620 //now do the work of moving the file
621 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
623 //see if the patient dir exists in the repository and create if not
624 if (!file_exists($new_path)) {
625 if (!mkdir($new_path,0700)) {
626 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
627 continue;
631 //fname is the name of the file after it is moved
632 $fname = $file['name'];
634 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
635 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
636 if ($patient_match[1] == $file['patient_id']) {
637 $fname = preg_replace("/^([0-9]+)_/","",$fname);
640 //filenames should not have funny chars
641 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
643 //see if there is an existing file with the same name and rename as necessary
644 if (file_exists($new_path.$file['name'])) {
645 $messages .= "File with same name already exists at location: " . $new_path . "\n";
646 $fname = basename($this->_rename_file($new_path.$file['name']));
647 $messages .= "Current file name was changed to " . $fname ."\n";
650 //now move the file
651 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
652 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
653 $d->url = "file://" .$new_path.$fname;
654 $d->set_foreign_id($file['patient_id']);
655 $d->set_mimetype($mimetype);
656 $d->persist();
657 $d->populate();
659 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
660 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
661 $d->_db->Execute($sql);
664 else {
665 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
668 $this->assign("messages",$messages);
669 $_POST['process'] = "";
672 function move_action_process($patient_id="",$document_id) {
673 if ($_POST['process'] != "true")
674 return;
676 $new_category_id = $_POST['new_category_id'];
677 $new_patient_id = $_POST['new_patient_id'];
679 //move to new category
680 if (is_numeric($new_category_id) && is_numeric($document_id)) {
681 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
682 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
683 //echo $sql;
684 $this->tree->_db->Execute($sql);
687 //move to new patient
688 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
689 $d = new Document($document_id);
690 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
691 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
692 $result = $d->_db->Execute($sql);
694 if (!$result || $result->EOF) {
695 //patient id does not exist
696 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
698 else {
699 $couchsavefailed = !$d->change_patient($new_patient_id);
701 $this->_state = false;
702 if(!$couchsavefailed){
704 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
706 else{
708 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
710 $this->assign("messages",$messages);
711 return $this->list_action($patient_id);
714 //in this case return the document to the queue instead of moving it
715 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
716 $d = new Document($document_id);
717 $new_path = $this->_config['repository'];
718 $fname = $d->get_url_file();
720 //see if there is an existing file with the same name and rename as necessary
721 if (file_exists($new_path.$d->get_url_file())) {
722 $messages .= "File with same name already exists in the queue.\n";
723 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
724 $messages .= "Current file name was changed to " . $fname ."\n";
727 //now move the file
728 if (rename($d->get_url_filepath(),$new_path.$fname)) {
729 $d->url = "file://" .$new_path.$fname;
730 $d->set_foreign_id("");
731 $d->persist();
732 $d->persist();
733 $d->populate();
735 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
736 $d->_db->Execute($sql);
737 $messages .= "Document returned to queue successfully.\n";
740 else {
741 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
744 $this->_state = false;
745 $this->assign("messages",$messages);
746 return $this->list_action($patient_id);
749 $this->_state = false;
750 $this->assign("messages",$messages);
751 return $this->view_action($patient_id,$document_id);
754 function validate_action_process($patient_id="", $document_id) {
756 $d = new Document($document_id);
757 if($d->couch_docid && $d->couch_revid){
758 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
759 $url = $file_path.$d->get_url();
760 $couch = new CouchDB();
761 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
762 $resp = $couch->retrieve_doc($data);
763 $content = $resp->data;
764 //--------Temporarily writing the file for calculating the hash--------//
765 //-----------Will be removed after calculating the hash value----------//
766 $temp_file = fopen($url,"w");
767 fwrite($temp_file,base64_decode($content));
768 fclose($temp_file);
770 else{
771 $url = $d->get_url();
773 //strip url of protocol handler
774 $url = preg_replace("|^(.*)://|","",$url);
776 //change full path to current webroot. this is for documents that may have
777 //been moved from a different filesystem and the full path in the database
778 //is not current. this is also for documents that may of been moved to
779 //different patients
780 // NOTE that $from_filename and basename($url) are the same thing
781 $from_all = explode("/",$url);
782 $from_filename = array_pop($from_all);
783 $from_patientid = array_pop($from_all);
784 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
785 if (file_exists($temp_url)) {
786 $url = $temp_url;
789 if ($_POST['process'] != "true") {
790 die("process is '" . $_POST['process'] . "', expected 'true'");
791 return;
794 $d = new Document( $document_id );
795 $current_hash = sha1_file( $url );
796 $messages = xl('Current Hash').": ".$current_hash."<br>";
797 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
798 if ( $d->get_hash() == '' ) {
799 $d->hash = $current_hash;
800 $d->persist();
801 $d->populate();
802 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
803 } else if ( $current_hash != $d->get_hash() ) {
804 $messages .= xl('Hash does not match. Data integrity has been compromised.');
805 } else {
806 $messages .= xl('Document passed integrity check.');
808 $this->_state = false;
809 $this->assign("messages", $messages);
810 if($d->couch_docid && $d->couch_revid){
811 //Removing the temporary file which is used to create the hash
812 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
814 return $this->view_action($patient_id, $document_id);
817 // Added by Rod for metadata update.
819 function update_action_process($patient_id="", $document_id) {
821 if ($_POST['process'] != "true") {
822 die("process is '" . $_POST['process'] . "', expected 'true'");
823 return;
826 $docdate = $_POST['docdate'];
827 $docname = $_POST['docname'];
828 $issue_id = $_POST['issue_id'];
830 if (is_numeric($document_id)) {
831 $messages = '';
832 $d = new Document( $document_id );
833 $file_name = $d->get_url_file();
834 if ( $docname != '' &&
835 $docname != $file_name ) {
836 $path = $d->get_url_filepath();
837 $path = str_replace( $file_name, "", $path );
838 $new_url = $this->_rename_file( $path.$docname );
839 if ( rename( $d->get_url(), $new_url ) ) {
840 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
841 $url = preg_replace("|^(.*)://|","",$d->get_url());
842 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
843 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
844 if ( file_exists( $url ) ) {
845 unlink( $url );
847 $d->url = $new_url;
848 $d->persist();
849 $d->populate();
850 $messages .= xl('Document successfully renamed.')."<br>";
851 } else {
852 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
856 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
857 $docdate = "'$docdate'";
858 } else {
859 $docdate = "NULL";
861 if (!is_numeric($issue_id)) {
862 $issue_id = 0;
864 $couch_docid = $d->get_couch_docid();
865 $couch_revid = $d->get_couch_revid();
866 if($couch_docid && $couch_revid ){
867 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
868 "list_id = '$issue_id' " .
869 "WHERE id = '$document_id'";
870 $this->tree->_db->Execute($sql);
873 else{
874 $sql = "UPDATE documents SET docdate = $docdate, " .
875 "list_id = '$issue_id' " .
876 "WHERE id = '$document_id'";
877 $this->tree->_db->Execute($sql);
879 $messages .= xl('Document date and issue updated successfully') . "<br>";
882 $this->_state = false;
883 $this->assign("messages", $messages);
884 return $this->view_action($patient_id, $document_id);
887 function list_action($patient_id = "") {
888 $this->_last_node = null;
889 $categories_list = $this->tree->_get_categories_array($patient_id);
890 //print_r($categories_list);
892 $menu = new HTML_TreeMenu();
893 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
894 $menu->addItem($rnode);
895 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
896 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
898 $this->assign("tree_html",$treeMenu->toHTML());
900 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
904 * This is a recursive function to rename a file to something that doesn't already exist.
905 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
906 * to ensure documents opened correctly by external browser viewers. If the counter is at the
907 * end of the file, then will use it (to continue to work with older files), however all new
908 * counters will be placed within filenames.
910 function _rename_file($fname) {
911 $file = basename($fname);
912 $fparts = split("\.",$fname);
913 $path = dirname($fname);
914 if (count($fparts) > 1) {
915 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
916 //increment the counter in filename
917 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
918 $fname = join(".",$fparts);
920 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
921 //increment counter at end of filename (so compatible with previous openemr version files
922 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
923 $fname = join(".",$fparts);
925 elseif (is_numeric($fparts[count($fparts) -1])) {
926 //leave date at end and place counter in filename
927 array_splice($fparts, -1, 0, "1");
928 $fname = join(".",$fparts);
930 else {
931 //add the counter to filename
932 array_splice($fparts, -1, 0, "1");
933 $fname = join(".",$fparts);
936 else { // (count($fparts) == 1)
937 //place counter at end of filename
938 array_push($fparts,"1");
939 $fname = join(".",$fparts);
942 if (file_exists($fname)) {
943 return $this->_rename_file($fname);
945 else {
946 return($fname);
950 function &_array_recurse($array,$categories = array()) {
951 if (!is_array($array)) {
952 $array = array();
954 $node = &$this->_last_node;
955 $current_node = &$node;
956 $expandedIcon = 'folder-expanded.gif';
957 foreach($array as $id => $ar) {
958 $icon = 'folder.gif';
959 if (is_array($ar) || !empty($id)) {
960 if ($node == null) {
961 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
962 $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));
963 $this->_last_node = &$rnode;
964 $node = &$rnode;
965 $current_node = &$rnode;
967 else {
968 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
969 $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)));
970 $current_node = &$this->_last_node;
973 $this->_array_recurse($ar,$categories);
975 else {
976 if ($id === 0 && !empty($ar)) {
977 $info = $this->tree->get_node_info($id);
978 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
979 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
981 else {
982 //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
983 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
984 if ($id !== 0 && is_object($node)) {
985 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
986 $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)));
992 // If there are documents in this document category, then add their
993 // attributes to the current node.
994 $icon = "file3.png";
995 if (is_array($categories[$id])) {
996 foreach ($categories[$id] as $doc) {
997 if($this->tree->get_node_name($id) == "CCR"){
998 $current_node->addItem(new HTML_TreeNode(array(
999 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1000 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1001 'icon' => $icon,
1002 'expandedIcon' => $expandedIcon,
1003 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1004 )));
1005 }elseif($this->tree->get_node_name($id) == "CCD"){
1006 $current_node->addItem(new HTML_TreeNode(array(
1007 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1008 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1009 'icon' => $icon,
1010 'expandedIcon' => $expandedIcon,
1011 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1012 )));
1013 }else{
1014 $current_node->addItem(new HTML_TreeNode(array(
1015 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1016 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1017 'icon' => $icon,
1018 'expandedIcon' => $expandedIcon
1019 )));
1025 return $node;
1028 //function for logging the errors in writing file to CouchDB/Hard Disk
1029 function document_upload_download_log($patientid,$content){
1030 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1031 $log_file = 'log.txt';
1032 if(!is_dir($log_path))
1033 mkdir($log_path,0777,true);
1034 $LOG = fopen($log_path.$log_file,'a');
1035 fwrite($LOG,$content);
1036 fclose($LOG);
1040 //place to hold optional code
1041 //$first_node = array_keys($t->tree);
1042 //$first_node = $first_node[0];
1043 //$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')"));
1045 //$this->_last_node = &$node1;