4466bfca6625f5f056e433612a44215819d3a4f9
[openemr.git] / controllers / C_Document.class.php
blob4466bfca6625f5f056e433612a44215819d3a4f9
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 function upload_action_process() {
59 $couchDB = false;
60 $harddisk = false;
61 if($GLOBALS['document_storage_method']==0){
62 $harddisk = true;
64 if($GLOBALS['document_storage_method']==1){
65 $couchDB = true;
68 if ($_POST['process'] != "true")
69 return;
71 $doDecryption = false;
72 $encrypted = $_POST['encrypted'];
73 $passphrase = $_POST['passphrase'];
74 if ( !$GLOBALS['hide_document_encryption'] &&
75 $encrypted && $passphrase ) {
76 $doDecryption = true;
79 if (is_numeric($_POST['category_id'])) {
80 $category_id = $_POST['category_id'];
82 if (is_numeric($_POST['patient_id'])) {
83 $patient_id = $_POST['patient_id'];
86 foreach ($_FILES as $file) {
87 $fname = $file['name'];
88 $err = "";
89 if ($file['error'] > 0 || empty($file['name']) || $file['size'] == 0) {
90 $fname = $file['name'];
91 if (empty($fname)) {
92 $fname = htmlentities("<empty>");
94 $error = "Error number: " . $file['error'] . " occured while uploading file named: " . $fname . "\n";
95 if ($file['size'] == 0) {
96 $error .= "The system does not permit uploading files of with size 0.\n";
100 else {
102 if (!file_exists($this->file_path)) {
103 if (!mkdir($this->file_path,0700)) {
104 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
107 if ( $_POST['destination'] != '' ) {
108 $fname = $_POST['destination'];
110 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
111 if (file_exists($this->file_path.$fname)) {
112 $error .= xl('File with same name already exists at location:','','',' ') . $this->file_path . "\n";
113 $fname = basename($this->_rename_file($this->file_path.$fname));
114 $file['name'] = $fname;
115 $error .= xl('Current file name was changed to','','',' ') . $fname ."\n";
118 if ( $doDecryption ) {
119 $tmpfile = fopen( $file['tmp_name'], "r" );
120 $filetext = fread( $tmpfile, $file['size'] );
121 $plaintext = $this->decrypt( $filetext, $passphrase );
122 fclose($tmpfile);
123 unlink( $file['tmp_name'] );
124 $tmpfile = fopen( $file['tmp_name'], "w+" );
125 fwrite( $tmpfile, $plaintext );
126 fclose( $tmpfile );
127 $file['size'] = filesize( $file['tmp_name'] );
129 $docid = '';
130 $resp = '';
131 if($couchDB == true){
132 $couch = new CouchDB();
133 $docname = $_SESSION['authId'].$patient_id.$encounter.$fname.date("%Y-%m-%d H:i:s");
134 $docid = $couch->stringToId($docname);
135 $tmpfile = fopen( $file['tmp_name'], "rb" );
136 $filetext = fread( $tmpfile, $file['size'] );
137 fclose( $tmpfile );
138 //--------Temporarily writing the file for calculating the hash--------//
139 //-----------Will be removed after calculating the hash value----------//
140 $temp_file = fopen($this->file_path.$fname,"w");
141 fwrite($temp_file,$filetext);
142 fclose($temp_file);
143 //---------------------------------------------------------------------//
145 $json = json_encode(base64_encode($filetext));
146 $db = $GLOBALS['couchdb_dbase'];
147 $data = array($db,$docid,$patient_id,$encounter,$file['type'],$json);
148 $resp = $couch->check_saveDOC($data);
149 if(!$resp->id || !$resp->_rev){
150 $data = array($db,$docid,$patient_id,$encounter);
151 $resp = $couch->retrieve_doc($data);
152 $docid = $resp->_id;
153 $revid = $resp->_rev;
155 else{
156 $docid = $resp->id;
157 $revid = $resp->rev;
159 if(!$docid && !$revid){ //if couchdb save failed
160 $error .= "<font color='red'><b>".xl("The file could not be saved to CouchDB.") . "</b></font>\n";
161 if($GLOBALS['couchdb_log']==1){
162 ob_start();
163 var_dump($resp);
164 $couchError=ob_get_clean();
165 $log_content = date('Y-m-d H:i:s')." ==> Uploading document: ".$fname."\r\n";
166 $log_content .= date('Y-m-d H:i:s')." ==> Failed to Store document content to CouchDB.\r\n";
167 $log_content .= date('Y-m-d H:i:s')." ==> Document ID: ".$docid."\r\n";
168 $log_content .= date('Y-m-d H:i:s')." ==> ".print_r($data,1)."\r\n";
169 $log_content .= $couchError;
170 $this->document_upload_download_log($patient_id,$log_content);//log error if any, for testing phase only
174 if($harddisk == true){
175 $uploadSuccess = false;
176 if(move_uploaded_file($file['tmp_name'],$this->file_path.$fname)){
177 $uploadSuccess = true;
179 else{
180 $error .= xl("The file could not be succesfully stored, this error is usually related to permissions problems on the storage system")."\n";
183 $this->assign("upload_success", "true");
184 $d = new Document();
185 $d->storagemethod = $GLOBALS['document_storage_method'];
186 if($harddisk == true)
187 $d->url = "file://" .$this->file_path.$fname;
188 else
189 $d->url = $fname;
190 if($couchDB == true){
191 $d->couch_docid = $docid;
192 $d->couch_revid = $revid;
194 if ($file['type'] == 'text/xml') {
195 $d->mimetype = 'application/xml';
197 else {
198 $d->mimetype = $file['type'];
200 $d->size = $file['size'];
201 $d->owner = $_SESSION['authUserID'];
202 $sha1Hash = sha1_file( $this->file_path.$fname );
203 if($couchDB == true){
204 //Removing the temporary file which is used to create the hash
205 unlink($this->file_path.$fname);
207 $d->hash = $sha1Hash;
208 $d->type = $d->type_array['file_url'];
209 $d->set_foreign_id($patient_id);
210 if($harddisk == true || ($couchDB == true && $docid && $revid)){
211 $d->persist();
212 $d->populate();
214 $this->assign("file",$d);
216 if (is_numeric($d->get_id()) && is_numeric($category_id)){
217 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
218 $d->_db->Execute($sql);
220 if($GLOBALS['couchdb_log']==1 && $log_content!=''){
221 $log_content .= "\r\n\r\n";
222 $this->document_upload_download_log($patient_id,$log_content);
226 $this->assign("error", nl2br($error));
227 //$this->_state = false;
228 $_POST['process'] = "";
229 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
232 function note_action_process($patient_id) {
234 if ($_POST['process'] != "true")
235 return;
237 $n = new Note();
238 parent::populate_object($n);
239 $n->persist();
241 $this->_state = false;
242 $_POST['process'] = "";
243 return $this->view_action($patient_id,$n->get_foreign_id());
246 function default_action() {
247 return $this->list_action();
250 function view_action($patient_id="",$doc_id) {
251 // Added by Rod to support document delete:
252 global $gacl_object, $phpgacl_location;
253 global $ISSUE_TYPES;
255 require_once(dirname(__FILE__) . "/../library/acl.inc");
256 require_once(dirname(__FILE__) . "/../library/lists.inc");
258 $d = new Document($doc_id);
259 $n = new Note();
261 $notes = $n->notes_factory($doc_id);
263 $this->assign("file", $d);
264 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
265 $this->assign("NOTE_ACTION",$this->_link("note"));
266 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
267 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
269 // Added by Rod to support document delete:
270 $delete_string = '';
271 if (acl_check('admin', 'super')) {
272 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
273 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
275 $this->assign("delete_string", $delete_string);
276 $this->assign("REFRESH_ACTION",$this->_link("list"));
278 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
279 "document_id=" . $d->get_id() . "&process=true");
281 // Added by Rod to support document date update:
282 $this->assign("DOCDATE", $d->get_docdate());
283 $this->assign("UPDATE_ACTION",$this->_link("update") .
284 "document_id=" . $d->get_id() . "&process=true");
286 // Added by Rod to support document issue update:
287 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
288 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
289 "pid = $patient_id " . // AND enddate IS NULL " .
290 "ORDER BY type, begdate");
291 while ($irow = sqlFetchArray($ires)) {
292 $desc = $irow['type'];
293 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
294 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
295 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
296 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
298 $this->assign("ISSUES_LIST", $issues_options);
300 $this->assign("notes",$notes);
302 $this->_last_node = null;
304 $menu = new HTML_TreeMenu();
306 //pass an empty array because we don't want the documents for each category showing up in this list box
307 $rnode = $this->_array_recurse($this->tree->tree,array());
308 $menu->addItem($rnode);
309 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
311 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
313 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
314 $this->assign("activity", $activity);
316 return $this->list_action($patient_id);
319 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
321 $td = mcrypt_module_open( $cypher, '', $mode, '');
322 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
323 mcrypt_generic_init( $td, $key, $iv );
324 $crypttext = mcrypt_generic( $td, $plaintext );
325 mcrypt_generic_deinit( $td );
326 return $iv.$crypttext;
329 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
331 $plaintext = '';
332 $td = mcrypt_module_open( $cypher, '', $mode, '' );
333 $ivsize = mcrypt_enc_get_iv_size( $td) ;
334 $iv = substr( $crypttext, 0, $ivsize );
335 $crypttext = substr( $crypttext, $ivsize );
336 if( $iv )
338 mcrypt_generic_init( $td, $key, $iv );
339 $plaintext = mdecrypt_generic( $td, $crypttext );
341 return $plaintext;
345 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
347 $encrypted = $_POST['encrypted'];
348 $passphrase = $_POST['passphrase'];
349 $doEncryption = false;
350 if ( !$GLOBALS['hide_document_encryption'] &&
351 $encrypted == "true" &&
352 $passphrase ) {
353 $doEncryption = true;
356 //controller function ruins booleans, so need to manually re-convert to booleans
357 if ($as_file == "true") {
358 $as_file=true;
360 else if ($as_file == "false") {
361 $as_file=false;
363 if ($original_file == "true") {
364 $original_file=true;
366 else if ($original_file == "false") {
367 $original_file=false;
370 $d = new Document($document_id);
371 $url = $d->get_url();
372 $storagemethod = $d->get_storagemethod();
373 $couch_docid = $d->get_couch_docid();
374 $couch_revid = $d->get_couch_revid();
376 if($couch_docid && $couch_revid && $original_file){
377 $couch = new CouchDB();
378 $data = array($GLOBALS['couchdb_dbase'],$couch_docid);
379 $resp = $couch->retrieve_doc($data);
380 $content = $resp->data;
381 if($content=='' && $GLOBALS['couchdb_log']==1){
382 $log_content = date('Y-m-d H:i:s')." ==> Retrieving document\r\n";
383 $log_content = date('Y-m-d H:i:s')." ==> URL: ".$url."\r\n";
384 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Document Id: ".$couch_docid."\r\n";
385 $log_content .= date('Y-m-d H:i:s')." ==> CouchDB Revision Id: ".$couch_revid."\r\n";
386 $log_content .= date('Y-m-d H:i:s')." ==> Failed to fetch document content from CouchDB.\r\n";
387 $log_content .= date('Y-m-d H:i:s')." ==> Will try to download file from HardDisk if exists.\r\n\r\n";
388 $this->document_upload_download_log($d->get_foreign_id(),$log_content);
389 die(xl("File retrieval from CouchDB failed"));
391 header('Content-Description: File Transfer');
392 header('Content-Transfer-Encoding: binary');
393 header('Expires: 0');
394 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
395 header('Pragma: public');
396 $tmpcouchpath = $GLOBALS['OE_SITE_DIR'].'/documents/temp/couch_'.date("YmdHis").$d->get_url_file();
397 $fh = fopen($tmpcouchpath,"w");
398 fwrite($fh,base64_decode($content));
399 fclose($fh);
400 $f = fopen($tmpcouchpath,"r");
401 if ( $doEncryption ) {
402 $filetext = fread( $f, filesize($tmpcouchpath) );
403 $ciphertext = $this->encrypt( $filetext, $passphrase );
404 $tmpfilepath = $GLOBALS['temporary_files_dir'];
405 $tmpfilename = "/encrypted_".$d->get_url_file();
406 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
407 fwrite( $tmpfile, $ciphertext );
408 fclose( $tmpfile );
409 header('Content-Disposition: attachment; filename='.$tmpfilename );
410 header("Content-Type: application/octet-stream" );
411 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
412 ob_clean();
413 flush();
414 readfile( $tmpfilepath.$tmpfilename );
415 unlink( $tmpfilepath.$tmpfilename );
416 } else {
417 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
418 header("Content-Type: " . $d->get_mimetype());
419 header("Content-Length: " . filesize($tmpcouchpath));
420 fpassthru($f);
422 fclose($f);
423 if($content!='')
424 unlink($tmpcouchpath);
425 exit;//exits only if file download from CouchDB is successfull.
427 //strip url of protocol handler
428 $url = preg_replace("|^(.*)://|","",$url);
430 //change full path to current webroot. this is for documents that may have
431 //been moved from a different filesystem and the full path in the database
432 //is not current. this is also for documents that may of been moved to
433 //different patients
434 // NOTE that $from_filename and basename($url) are the same thing
435 $from_all = explode("/",$url);
436 $from_filename = array_pop($from_all);
437 $from_patientid = array_pop($from_all);
438 if($couch_docid && $couch_revid){
439 //for couchDB no URL is available in the table, hence using the foreign_id which is patientID
440 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;
443 else{
444 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
447 if (file_exists($temp_url)) {
448 $url = $temp_url;
452 if (!file_exists($url)) {
453 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;
456 else {
457 if ($original_file) {
458 //normal case when serving the file referenced in database
459 header('Content-Description: File Transfer');
460 header('Content-Transfer-Encoding: binary');
461 header('Expires: 0');
462 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
463 header('Pragma: public');
464 $f = fopen($url,"r");
465 if ( $doEncryption ) {
466 $filetext = fread( $f, filesize($url) );
467 $ciphertext = $this->encrypt( $filetext, $passphrase );
468 $tmpfilepath = $GLOBALS['temporary_files_dir'];
469 $tmpfilename = "/encrypted_".$d->get_url_file();
470 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
471 fwrite( $tmpfile, $ciphertext );
472 fclose( $tmpfile );
473 header('Content-Disposition: attachment; filename='.$tmpfilename );
474 header("Content-Type: application/octet-stream" );
475 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
476 ob_clean();
477 flush();
478 readfile( $tmpfilepath.$tmpfilename );
479 unlink( $tmpfilepath.$tmpfilename );
480 } else {
481 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
482 header("Content-Type: " . $d->get_mimetype());
483 header("Content-Length: " . filesize($url));
484 fpassthru($f);
486 exit;
488 else {
489 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
490 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
491 if($couch_docid && $couch_revid){
492 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $convertedFile;
494 else{
495 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
497 header("Pragma: public");
498 header("Expires: 0");
499 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
500 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
501 header("Content-Type: image/jpeg");
502 header("Content-Length: " . filesize($url));
503 $f = fopen($url,"r");
504 fpassthru($f);
505 if($couch_docid && $couch_revid){
506 fclose($f);
507 unlink($url);
508 $url=str_replace("_converted.jpg",'.pdf',$url);
509 unlink($url);
511 exit;
516 function queue_action($patient_id="") {
517 $messages = $this->_tpl_vars['messages'];
518 $queue_files = array();
520 //see if the repository exists and it is a directory else error
521 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
522 $dir = opendir($this->_config['repository']);
523 //read each entry in the directory
524 while (($file = readdir($dir)) !== false) {
525 //concat the filename and path
526 $file = $this->_config['repository'] .$file;
527 $file_info = array();
528 //if the filename is a file get its info and put into a tmp array
529 if (is_file($file) && strpos(basename($file),".") !== 0) {
530 $file_info['filename'] = basename($file);
531 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
532 $d = Document::document_factory_url("file://" . $file);
533 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
534 $file_info['patient_id'] = $patient_match[1];
535 $file_info['document_id'] = $d->get_id();
536 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
538 //merge the tmp array into the larger array
539 $queue_files[] = $file_info;
542 closedir($dir);
544 else {
545 $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";
549 $this->assign("queue_files",$queue_files);
550 $this->_last_node = null;
552 $menu = new HTML_TreeMenu();
554 //pass an empty array because we don't want the documents for each category showing up in this list box
555 $rnode = $this->_array_recurse($this->tree->tree,array());
556 $menu->addItem($rnode);
557 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
559 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
561 $this->assign("messages",nl2br($messages));
562 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
565 function queue_action_process() {
566 if ($_POST['process'] != "true")
567 return;
569 $messages = $this->_tpl_vars['messages'];
571 //build a category tree so we can have a list of category ids that are valid
572 $ct = new CategoryTree(1);
573 $categories = $ct->_id_name;
575 //see if there were and posted files and assign them
576 $files = null;
577 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
579 //loop through posted files
580 foreach($files as $doc_id=> $file) {
581 //only operate on files checked as active
582 if (!$file['active']) continue;
584 //run basic validation checks
585 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
586 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
587 continue;
590 //validate that the pod exists
591 $d = new Document($doc_id);
592 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
593 $result = $d->_db->Execute($sql);
595 if (!$result || $result->EOF) {
596 //patient id does not exist
597 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
598 continue;
601 //validate that the category id exists
602 if (!isset($categories[$file['category_id']])) {
603 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
604 continue;
607 //now do the work of moving the file
608 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
610 //see if the patient dir exists in the repository and create if not
611 if (!file_exists($new_path)) {
612 if (!mkdir($new_path,0700)) {
613 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
614 continue;
618 //fname is the name of the file after it is moved
619 $fname = $file['name'];
621 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
622 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
623 if ($patient_match[1] == $file['patient_id']) {
624 $fname = preg_replace("/^([0-9]+)_/","",$fname);
627 //filenames should not have funny chars
628 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
630 //see if there is an existing file with the same name and rename as necessary
631 if (file_exists($new_path.$file['name'])) {
632 $messages .= "File with same name already exists at location: " . $new_path . "\n";
633 $fname = basename($this->_rename_file($new_path.$file['name']));
634 $messages .= "Current file name was changed to " . $fname ."\n";
637 //now move the file
638 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
639 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
640 $d->url = "file://" .$new_path.$fname;
641 $d->set_foreign_id($file['patient_id']);
642 $d->set_mimetype($mimetype);
643 $d->persist();
644 $d->populate();
646 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
647 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
648 $d->_db->Execute($sql);
651 else {
652 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
655 $this->assign("messages",$messages);
656 $_POST['process'] = "";
659 function move_action_process($patient_id="",$document_id) {
660 if ($_POST['process'] != "true")
661 return;
663 $new_category_id = $_POST['new_category_id'];
664 $new_patient_id = $_POST['new_patient_id'];
666 //move to new category
667 if (is_numeric($new_category_id) && is_numeric($document_id)) {
668 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
669 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
670 //echo $sql;
671 $this->tree->_db->Execute($sql);
674 //move to new patient
675 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
676 $d = new Document($document_id);
677 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
678 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
679 $result = $d->_db->Execute($sql);
681 if (!$result || $result->EOF) {
682 //patient id does not exist
683 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
685 else {
687 $couch_docid = $d->get_couch_docid();
688 $couch_revid = $d->get_couch_revid();
689 //set the new patient in CouchDB
690 $couchsavefailed=false;
691 if($couch_docid && $couch_revid){
692 $couch = new CouchDB();
693 $db = $GLOBALS['couchdb_dbase'];
694 $data=array($db,$couch_docid);
695 $couchresp=$couch->retrieve_doc($data);
696 //CouchDB doesnot support updating a single value in a document.
697 //Have to retrieve the entire document,update the necessary value and save again
698 list($db,$docid,$revid,$patient_id,$encounter,$type,$json) = $data;
699 $data=array($db,$couch_docid,$couch_revid,$new_patient_id,$couchresp->encounter,$couchresp->mimetype,json_encode($couchresp->data));
700 $resp = $couch->update_doc($data);
701 //Sometimes the response from CouchDB is not available
702 //still it would have saved in the DB. Hence check one more time
703 if(!$resp->_id || !$resp->_rev){
704 $data = array($db,$couch_docid,$new_patient_id,$couchresp->encounter);
705 $resp = $couch->retrieve_doc($data);
709 if($resp->_rev ==$couch_revid){
710 $couchsavefailed=true;
712 else{
713 $d->set_couch_revid($resp->_rev);
718 //set the new patient in mysql
719 $d->set_foreign_id($new_patient_id);
720 $d->persist();
721 $this->_state = false;
722 if(!$couchsavefailed){
724 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
726 else{
728 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('Failed.','','\' ') . "\n";
730 $this->assign("messages",$messages);
731 return $this->list_action($patient_id);
734 //in this case return the document to the queue instead of moving it
735 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
736 $d = new Document($document_id);
737 $new_path = $this->_config['repository'];
738 $fname = $d->get_url_file();
740 //see if there is an existing file with the same name and rename as necessary
741 if (file_exists($new_path.$d->get_url_file())) {
742 $messages .= "File with same name already exists in the queue.\n";
743 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
744 $messages .= "Current file name was changed to " . $fname ."\n";
747 //now move the file
748 if (rename($d->get_url_filepath(),$new_path.$fname)) {
749 $d->url = "file://" .$new_path.$fname;
750 $d->set_foreign_id("");
751 $d->persist();
752 $d->persist();
753 $d->populate();
755 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
756 $d->_db->Execute($sql);
757 $messages .= "Document returned to queue successfully.\n";
760 else {
761 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
764 $this->_state = false;
765 $this->assign("messages",$messages);
766 return $this->list_action($patient_id);
769 $this->_state = false;
770 $this->assign("messages",$messages);
771 return $this->view_action($patient_id,$document_id);
774 function validate_action_process($patient_id="", $document_id) {
776 $d = new Document($document_id);
777 if($d->couch_docid && $d->couch_revid){
778 $file_path = $GLOBALS['OE_SITE_DIR'].'/documents/temp/';
779 $url = $file_path.$d->get_url();
780 $couch = new CouchDB();
781 $data = array($GLOBALS['couchdb_dbase'],$d->couch_docid);
782 $resp = $couch->retrieve_doc($data);
783 $content = $resp->data;
784 //--------Temporarily writing the file for calculating the hash--------//
785 //-----------Will be removed after calculating the hash value----------//
786 $temp_file = fopen($url,"w");
787 fwrite($temp_file,base64_decode($content));
788 fclose($temp_file);
790 else{
791 $url = $d->get_url();
793 //strip url of protocol handler
794 $url = preg_replace("|^(.*)://|","",$url);
796 //change full path to current webroot. this is for documents that may have
797 //been moved from a different filesystem and the full path in the database
798 //is not current. this is also for documents that may of been moved to
799 //different patients
800 // NOTE that $from_filename and basename($url) are the same thing
801 $from_all = explode("/",$url);
802 $from_filename = array_pop($from_all);
803 $from_patientid = array_pop($from_all);
804 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
805 if (file_exists($temp_url)) {
806 $url = $temp_url;
809 if ($_POST['process'] != "true") {
810 die("process is '" . $_POST['process'] . "', expected 'true'");
811 return;
814 $d = new Document( $document_id );
815 $current_hash = sha1_file( $url );
816 $messages = xl('Current Hash').": ".$current_hash."<br>";
817 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
818 if ( $d->get_hash() == '' ) {
819 $d->hash = $current_hash;
820 $d->persist();
821 $d->populate();
822 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
823 } else if ( $current_hash != $d->get_hash() ) {
824 $messages .= xl('Hash does not match. Data integrity has been compromised.');
825 } else {
826 $messages .= xl('Document passed integrity check.');
828 $this->_state = false;
829 $this->assign("messages", $messages);
830 if($d->couch_docid && $d->couch_revid){
831 //Removing the temporary file which is used to create the hash
832 unlink($GLOBALS['OE_SITE_DIR'].'/documents/temp/'.$d->get_url());
834 return $this->view_action($patient_id, $document_id);
837 // Added by Rod for metadata update.
839 function update_action_process($patient_id="", $document_id) {
841 if ($_POST['process'] != "true") {
842 die("process is '" . $_POST['process'] . "', expected 'true'");
843 return;
846 $docdate = $_POST['docdate'];
847 $docname = $_POST['docname'];
848 $issue_id = $_POST['issue_id'];
850 if (is_numeric($document_id)) {
851 $messages = '';
852 $d = new Document( $document_id );
853 $file_name = $d->get_url_file();
854 if ( $docname != '' &&
855 $docname != $file_name ) {
856 $path = $d->get_url_filepath();
857 $path = str_replace( $file_name, "", $path );
858 $new_url = $this->_rename_file( $path.$docname );
859 if ( rename( $d->get_url(), $new_url ) ) {
860 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
861 $url = preg_replace("|^(.*)://|","",$d->get_url());
862 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
863 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
864 if ( file_exists( $url ) ) {
865 unlink( $url );
867 $d->url = $new_url;
868 $d->persist();
869 $d->populate();
870 $messages .= xl('Document successfully renamed.')."<br>";
871 } else {
872 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
876 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
877 $docdate = "'$docdate'";
878 } else {
879 $docdate = "NULL";
881 if (!is_numeric($issue_id)) {
882 $issue_id = 0;
884 $couch_docid = $d->get_couch_docid();
885 $couch_revid = $d->get_couch_revid();
886 if($couch_docid && $couch_revid ){
887 $sql = "UPDATE documents SET docdate = $docdate, url = '".$_POST['docname']."', " .
888 "list_id = '$issue_id' " .
889 "WHERE id = '$document_id'";
890 $this->tree->_db->Execute($sql);
893 else{
894 $sql = "UPDATE documents SET docdate = $docdate, " .
895 "list_id = '$issue_id' " .
896 "WHERE id = '$document_id'";
897 $this->tree->_db->Execute($sql);
899 $messages .= xl('Document date and issue updated successfully') . "<br>";
902 $this->_state = false;
903 $this->assign("messages", $messages);
904 return $this->view_action($patient_id, $document_id);
907 function list_action($patient_id = "") {
908 $this->_last_node = null;
909 $categories_list = $this->tree->_get_categories_array($patient_id);
910 //print_r($categories_list);
912 $menu = new HTML_TreeMenu();
913 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
914 $menu->addItem($rnode);
915 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
916 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
918 $this->assign("tree_html",$treeMenu->toHTML());
920 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
924 * This is a recursive function to rename a file to something that doesn't already exist.
925 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
926 * to ensure documents opened correctly by external browser viewers. If the counter is at the
927 * end of the file, then will use it (to continue to work with older files), however all new
928 * counters will be placed within filenames.
930 function _rename_file($fname) {
931 $file = basename($fname);
932 $fparts = split("\.",$fname);
933 $path = dirname($fname);
934 if (count($fparts) > 1) {
935 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
936 //increment the counter in filename
937 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
938 $fname = join(".",$fparts);
940 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
941 //increment counter at end of filename (so compatible with previous openemr version files
942 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
943 $fname = join(".",$fparts);
945 elseif (is_numeric($fparts[count($fparts) -1])) {
946 //leave date at end and place counter in filename
947 array_splice($fparts, -1, 0, "1");
948 $fname = join(".",$fparts);
950 else {
951 //add the counter to filename
952 array_splice($fparts, -1, 0, "1");
953 $fname = join(".",$fparts);
956 else { // (count($fparts) == 1)
957 //place counter at end of filename
958 array_push($fparts,"1");
959 $fname = join(".",$fparts);
962 if (file_exists($fname)) {
963 return $this->_rename_file($fname);
965 else {
966 return($fname);
970 function &_array_recurse($array,$categories = array()) {
971 if (!is_array($array)) {
972 $array = array();
974 $node = &$this->_last_node;
975 $current_node = &$node;
976 $expandedIcon = 'folder-expanded.gif';
977 foreach($array as $id => $ar) {
978 $icon = 'folder.gif';
979 if (is_array($ar) || !empty($id)) {
980 if ($node == null) {
981 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
982 $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));
983 $this->_last_node = &$rnode;
984 $node = &$rnode;
985 $current_node =&$rnode;
987 else {
988 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
989 $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)));
990 $current_node =&$this->_last_node;
993 $this->_array_recurse($ar,$categories);
995 else {
996 if ($id === 0 && !empty($ar)) {
997 $info = $this->tree->get_node_info($id);
998 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
999 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
1001 else {
1002 //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
1003 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
1004 if ($id !== 0 && is_object($node)) {
1005 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
1006 $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)));
1012 // If there are documents in this document category, then add their
1013 // attributes to the current node.
1014 $icon = "file3.png";
1015 if (is_array($categories[$id])) {
1016 foreach ($categories[$id] as $doc) {
1017 if($this->tree->get_node_name($id) == "CCR"){
1018 $current_node->addItem(new HTML_TreeNode(array(
1019 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1020 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1021 'icon' => $icon,
1022 'expandedIcon' => $expandedIcon,
1023 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
1024 )));
1025 }elseif($this->tree->get_node_name($id) == "CCD"){
1026 $current_node->addItem(new HTML_TreeNode(array(
1027 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1028 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1029 'icon' => $icon,
1030 'expandedIcon' => $expandedIcon,
1031 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
1032 )));
1033 }else{
1034 $current_node->addItem(new HTML_TreeNode(array(
1035 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
1036 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
1037 'icon' => $icon,
1038 'expandedIcon' => $expandedIcon
1039 )));
1045 return $node;
1048 //function for logging the errors in writing file to CouchDB/Hard Disk
1049 function document_upload_download_log($patientid,$content){
1050 $log_path = $GLOBALS['OE_SITE_DIR']."/documents/couchdb/";
1051 $log_file = 'log.txt';
1052 if(!is_dir($log_path))
1053 mkdir($log_path,0777,true);
1054 $LOG = fopen($log_path.$log_file,'a');
1055 fwrite($LOG,$content);
1056 fclose($LOG);
1060 //place to hold optional code
1061 //$first_node = array_keys($t->tree);
1062 //$first_node = $first_node[0];
1063 //$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')"));
1065 //$this->_last_node = &$node1;