Yet another document bug fix; tested and works well (sha-1 validaiton and encrtpy...
[openemr.git] / controllers / C_Document.class.php
blobc29d5840e2a4d7bb1e58a07402ebc779fb58bd58
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");
13 class C_Document extends Controller {
15 var $template_mod;
16 var $documents;
17 var $document_categories;
18 var $tree;
19 var $_config;
20 var $file_path;
23 function C_Document($template_mod = "general") {
24 parent::Controller();
25 $this->documents = array();
26 $this->template_mod = $template_mod;
27 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
28 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
30 //get global config options for this namespace
31 $this->_config = $GLOBALS['oer_config']['documents'];
33 $this->file_path = $this->_config['repository'] . preg_replace("/[^A-Za-z0-9]/","_",$_GET['patient_id']) . "/";
35 $this->_args = array("patient_id" => $_GET['patient_id']);
37 $this->assign("STYLE", $GLOBALS['style']);
38 $t = new CategoryTree(1);
39 //print_r($t->tree);
40 $this->tree = $t;
43 function upload_action($patient_id,$category_id) {
44 $category_name = $this->tree->get_node_name($category_id);
45 $this->assign("category_id", $category_id);
46 $this->assign("category_name", $category_name);
47 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
48 $this->assign("patient_id", $patient_id);
49 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
50 $this->assign("activity", $activity);
51 return $this->list_action($patient_id);
54 function upload_action_process() {
56 if ($_POST['process'] != "true")
57 return;
59 $doDecryption = false;
60 $encrypted = $_POST['encrypted'];
61 $passphrase = $_POST['passphrase'];
62 if ( !$GLOBALS['hide_document_encryption'] &&
63 $encrypted && $passphrase ) {
64 $doDecryption = true;
67 if (is_numeric($_POST['category_id'])) {
68 $category_id = $_POST['category_id'];
70 if (is_numeric($_POST['patient_id'])) {
71 $patient_id = $_POST['patient_id'];
74 foreach ($_FILES as $file) {
75 $fname = $file['name'];
76 $err = "";
77 if ($file['error'] > 0 || empty($file['name']) || $file['size'] == 0) {
78 $fname = $file['name'];
79 if (empty($fname)) {
80 $fname = htmlentities("<empty>");
82 $error = "Error number: " . $file['error'] . " occured while uploading file named: " . $fname . "\n";
83 if ($file['size'] == 0) {
84 $error .= "The system does not permit uploading files of with size 0.\n";
88 else {
90 if (!file_exists($this->file_path)) {
91 if (!mkdir($this->file_path,0700)) {
92 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
95 if ( $_POST['destination'] != '' ) {
96 $fname = $_POST['destination'];
98 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
99 if (file_exists($this->file_path.$fname)) {
100 $error .= xl('File with same name already exists at location:','','',' ') . $this->file_path . "\n";
101 $fname = basename($this->_rename_file($this->file_path.$fname));
102 $file['name'] = $fname;
103 $error .= xl('Current file name was changed to','','',' ') . $fname ."\n";
106 if ( $doDecryption ) {
107 $tmpfile = fopen( $file['tmp_name'], "r" );
108 $filetext = fread( $tmpfile, $file['size'] );
109 $plaintext = $this->decrypt( $filetext, $passphrase );
110 unlink( $file['tmp_name'] );
111 $tmpfile = fopen( $file['tmp_name'], "w+" );
112 fwrite( $tmpfile, $plaintext );
113 fclose( $tmpfile );
114 $file['size'] = filesize( $tmpfilepath.$tmpfilename );
117 if (move_uploaded_file($file['tmp_name'],$this->file_path.$fname)) {
118 $this->assign("upload_success", "true");
119 $d = new Document();
120 $d->url = "file://" .$this->file_path.$fname;
121 $d->mimetype = $file['type'];
122 $d->size = $file['size'];
123 $sha1Hash = sha1_file( $this->file_path.$fname );
124 $d->hash = $sha1Hash;
125 $d->type = $d->type_array['file_url'];
126 $d->set_foreign_id($patient_id);
127 $d->persist();
128 $d->populate();
129 $this->assign("file",$d);
131 if (is_numeric($d->get_id()) && is_numeric($category_id)) {
132 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
133 $d->_db->Execute($sql);
136 else {
137 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
141 $this->assign("error", nl2br($error));
142 //$this->_state = false;
143 $_POST['process'] = "";
144 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
147 function note_action_process($patient_id) {
149 if ($_POST['process'] != "true")
150 return;
152 $n = new Note();
153 parent::populate_object($n);
154 $n->persist();
156 $this->_state = false;
157 $_POST['process'] = "";
158 return $this->view_action($patient_id,$n->get_foreign_id());
161 function default_action() {
162 return $this->list_action();
165 function view_action($patient_id="",$doc_id) {
166 // Added by Rod to support document delete:
167 global $gacl_object, $phpgacl_location;
168 global $ISSUE_TYPES;
170 require_once(dirname(__FILE__) . "/../library/acl.inc");
171 require_once(dirname(__FILE__) . "/../library/lists.inc");
173 $d = new Document($doc_id);
174 $n = new Note();
176 $notes = $n->notes_factory($doc_id);
178 $this->assign("file", $d);
179 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
180 $this->assign("NOTE_ACTION",$this->_link("note"));
181 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
182 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
184 // Added by Rod to support document delete:
185 $delete_string = '';
186 if (acl_check('admin', 'super')) {
187 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
188 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
190 $this->assign("delete_string", $delete_string);
191 $this->assign("REFRESH_ACTION",$this->_link("list"));
193 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
194 "document_id=" . $d->get_id() . "&process=true");
196 // Added by Rod to support document date update:
197 $this->assign("DOCDATE", $d->get_docdate());
198 $this->assign("UPDATE_ACTION",$this->_link("update") .
199 "document_id=" . $d->get_id() . "&process=true");
201 // Added by Rod to support document issue update:
202 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
203 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
204 "pid = $patient_id " . // AND enddate IS NULL " .
205 "ORDER BY type, begdate");
206 while ($irow = sqlFetchArray($ires)) {
207 $desc = $irow['type'];
208 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
209 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
210 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
211 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
213 $this->assign("ISSUES_LIST", $issues_options);
215 $this->assign("notes",$notes);
217 $this->_last_node = null;
219 $menu = new HTML_TreeMenu();
221 //pass an empty array because we don't want the documents for each category showing up in this list box
222 $rnode = $this->_array_recurse($this->tree->tree,array());
223 $menu->addItem($rnode);
224 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
226 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
228 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
229 $this->assign("activity", $activity);
231 return $this->list_action($patient_id);
234 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
236 $td = mcrypt_module_open( $cypher, '', $mode, '');
237 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
238 mcrypt_generic_init( $td, $key, $iv );
239 $crypttext = mcrypt_generic( $td, $plaintext );
240 mcrypt_generic_deinit( $td );
241 return $iv.$crypttext;
244 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
246 $plaintext = '';
247 $td = mcrypt_module_open( $cypher, '', $mode, '' );
248 $ivsize = mcrypt_enc_get_iv_size( $td) ;
249 $iv = substr( $crypttext, 0, $ivsize );
250 $crypttext = substr( $crypttext, $ivsize );
251 if( $iv )
253 mcrypt_generic_init( $td, $key, $iv );
254 $plaintext = mdecrypt_generic( $td, $crypttext );
256 return $plaintext;
260 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
262 $encrypted = $_POST['encrypted'];
263 $passphrase = $_POST['passphrase'];
264 $doEncryption = false;
265 if ( !$GLOBALS['hide_document_encryption'] &&
266 $encrypted == "true" &&
267 $passphrase ) {
268 $doEncryption = true;
271 //controller function ruins booleans, so need to manually re-convert to booleans
272 if ($as_file == "true") {
273 $as_file=true;
275 else if ($as_file == "false") {
276 $as_file=false;
278 if ($original_file == "true") {
279 $original_file=true;
281 else if ($original_file == "false") {
282 $original_file=false;
285 $d = new Document($document_id);
286 $url = $d->get_url();
288 //strip url of protocol handler
289 $url = preg_replace("|^(.*)://|","",$url);
291 //change full path to current webroot. this is for documents that may have
292 //been moved from a different filesystem and the full path in the database
293 //is not current. this is also for documents that may of been moved to
294 //different patients
295 // NOTE that $from_filename and basename($url) are the same thing
296 $from_all = explode("/",$url);
297 $from_filename = array_pop($from_all);
298 $from_patientid = array_pop($from_all);
299 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
300 if (file_exists($temp_url)) {
301 $url = $temp_url;
303 if (!file_exists($url)) {
304 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;
306 else {
307 if ($original_file) {
308 //normal case when serving the file referenced in database
309 header('Content-Description: File Transfer');
310 header('Content-Transfer-Encoding: binary');
311 header('Expires: 0');
312 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
313 header('Pragma: public');
314 $f = fopen($url,"r");
315 if ( $doEncryption ) {
316 $filetext = fread( $f, filesize($url) );
317 $ciphertext = $this->encrypt( $filetext, $passphrase );
318 $tmpfilepath = $GLOBALS['temporary_files_dir'];
319 $tmpfilename = "/encrypted_".$d->get_url_file();
320 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
321 fwrite( $tmpfile, $ciphertext );
322 fclose( $tmpfile );
323 header('Content-Disposition: attachment; filename='.$tmpfilename );
324 header("Content-Type: application/octet-stream" );
325 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
326 ob_clean();
327 flush();
328 readfile( $tmpfilepath.$tmpfilename );
329 unlink( $tmpfilepath.$tmpfilename );
330 } else {
331 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
332 header("Content-Type: " . $d->get_mimetype());
333 header("Content-Length: " . filesize($url));
334 fpassthru($f);
336 exit;
338 else {
339 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
340 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
341 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
342 header("Pragma: public");
343 header("Expires: 0");
344 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
345 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
346 header("Content-Type: image/jpeg");
347 header("Content-Length: " . filesize($url));
348 $f = fopen($url,"r");
349 fpassthru($f);
350 exit;
355 function queue_action($patient_id="") {
356 $messages = $this->_tpl_vars['messages'];
357 $queue_files = array();
359 //see if the repository exists and it is a directory else error
360 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
361 $dir = opendir($this->_config['repository']);
362 //read each entry in the directory
363 while (($file = readdir($dir)) !== false) {
364 //concat the filename and path
365 $file = $this->_config['repository'] .$file;
366 $file_info = array();
367 //if the filename is a file get its info and put into a tmp array
368 if (is_file($file) && strpos(basename($file),".") !== 0) {
369 $file_info['filename'] = basename($file);
370 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
371 $d = Document::document_factory_url("file://" . $file);
372 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
373 $file_info['patient_id'] = $patient_match[1];
374 $file_info['document_id'] = $d->get_id();
375 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
377 //merge the tmp array into the larger array
378 $queue_files[] = $file_info;
381 closedir($dir);
383 else {
384 $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";
388 $this->assign("queue_files",$queue_files);
389 $this->_last_node = null;
391 $menu = new HTML_TreeMenu();
393 //pass an empty array because we don't want the documents for each category showing up in this list box
394 $rnode = $this->_array_recurse($this->tree->tree,array());
395 $menu->addItem($rnode);
396 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
398 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
400 $this->assign("messages",nl2br($messages));
401 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
404 function queue_action_process() {
405 if ($_POST['process'] != "true")
406 return;
408 $messages = $this->_tpl_vars['messages'];
410 //build a category tree so we can have a list of category ids that are valid
411 $ct = new CategoryTree(1);
412 $categories = $ct->_id_name;
414 //see if there were and posted files and assign them
415 $files = null;
416 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
418 //loop through posted files
419 foreach($files as $doc_id=> $file) {
420 //only operate on files checked as active
421 if (!$file['active']) continue;
423 //run basic validation checks
424 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
425 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
426 continue;
429 //validate that the pod exists
430 $d = new Document($doc_id);
431 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
432 $result = $d->_db->Execute($sql);
434 if (!$result || $result->EOF) {
435 //patient id does not exist
436 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
437 continue;
440 //validate that the category id exists
441 if (!isset($categories[$file['category_id']])) {
442 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
443 continue;
446 //now do the work of moving the file
447 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
449 //see if the patient dir exists in the repository and create if not
450 if (!file_exists($new_path)) {
451 if (!mkdir($new_path,0700)) {
452 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
453 continue;
457 //fname is the name of the file after it is moved
458 $fname = $file['name'];
460 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
461 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
462 if ($patient_match[1] == $file['patient_id']) {
463 $fname = preg_replace("/^([0-9]+)_/","",$fname);
466 //filenames should not have funny chars
467 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
469 //see if there is an existing file with the same name and rename as necessary
470 if (file_exists($new_path.$file['name'])) {
471 $messages .= "File with same name already exists at location: " . $new_path . "\n";
472 $fname = basename($this->_rename_file($new_path.$file['name']));
473 $messages .= "Current file name was changed to " . $fname ."\n";
476 //now move the file
477 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
478 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
479 $d->url = "file://" .$new_path.$fname;
480 $d->set_foreign_id($file['patient_id']);
481 $d->set_mimetype($mimetype);
482 $d->persist();
483 $d->populate();
485 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
486 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
487 $d->_db->Execute($sql);
490 else {
491 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
494 $this->assign("messages",$messages);
495 $_POST['process'] = "";
498 function move_action_process($patient_id="",$document_id) {
499 if ($_POST['process'] != "true")
500 return;
502 $new_category_id = $_POST['new_category_id'];
503 $new_patient_id = $_POST['new_patient_id'];
505 //move to new category
506 if (is_numeric($new_category_id) && is_numeric($document_id)) {
507 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
508 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
509 //echo $sql;
510 $this->tree->_db->Execute($sql);
513 //move to new patient
514 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
515 $d = new Document($document_id);
516 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
517 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
518 $result = $d->_db->Execute($sql);
520 if (!$result || $result->EOF) {
521 //patient id does not exist
522 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
524 else {
525 //set the new patient
526 $d->set_foreign_id($new_patient_id);
527 $d->persist();
528 $this->_state = false;
529 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
530 $this->assign("messages",$messages);
531 return $this->list_action($patient_id);
534 //in this case return the document to the queue instead of moving it
535 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
536 $d = new Document($document_id);
537 $new_path = $this->_config['repository'];
538 $fname = $d->get_url_file();
540 //see if there is an existing file with the same name and rename as necessary
541 if (file_exists($new_path.$d->get_url_file())) {
542 $messages .= "File with same name already exists in the queue.\n";
543 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
544 $messages .= "Current file name was changed to " . $fname ."\n";
547 //now move the file
548 if (rename($d->get_url_filepath(),$new_path.$fname)) {
549 $d->url = "file://" .$new_path.$fname;
550 $d->set_foreign_id("");
551 $d->persist();
552 $d->persist();
553 $d->populate();
555 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
556 $d->_db->Execute($sql);
557 $messages .= "Document returned to queue successfully.\n";
560 else {
561 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
564 $this->_state = false;
565 $this->assign("messages",$messages);
566 return $this->list_action($patient_id);
569 $this->_state = false;
570 $this->assign("messages",$messages);
571 return $this->view_action($patient_id,$document_id);
574 function validate_action_process($patient_id="", $document_id) {
576 $d = new Document($document_id);
577 $url = $d->get_url();
579 //strip url of protocol handler
580 $url = preg_replace("|^(.*)://|","",$url);
582 //change full path to current webroot. this is for documents that may have
583 //been moved from a different filesystem and the full path in the database
584 //is not current. this is also for documents that may of been moved to
585 //different patients
586 // NOTE that $from_filename and basename($url) are the same thing
587 $from_all = explode("/",$url);
588 $from_filename = array_pop($from_all);
589 $from_patientid = array_pop($from_all);
590 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
591 if (file_exists($temp_url)) {
592 $url = $temp_url;
595 if ($_POST['process'] != "true") {
596 die("process is '" . $_POST['process'] . "', expected 'true'");
597 return;
600 $d = new Document( $document_id );
601 $current_hash = sha1_file( $url );
602 $messages = xl('Current Hash').": ".$current_hash."<br>";
603 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
604 if ( $d->get_hash() == '' ) {
605 $d->hash = $current_hash;
606 $d->persist();
607 $d->populate();
608 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
609 } else if ( $current_hash != $d->get_hash() ) {
610 $messages .= xl('Hash does not match. Data integrity has been compromised.');
611 } else {
612 $messages .= xl('Document passed integrity check.');
615 $this->_state = false;
616 $this->assign("messages", $messages);
617 return $this->view_action($patient_id, $document_id);
620 // Added by Rod for metadata update.
622 function update_action_process($patient_id="", $document_id) {
623 if ($_POST['process'] != "true") {
624 die("process is '" . $_POST['process'] . "', expected 'true'");
625 return;
628 $docdate = $_POST['docdate'];
629 $docname = $_POST['docname'];
630 $issue_id = $_POST['issue_id'];
632 if (is_numeric($document_id)) {
633 $messages = '';
634 $d = new Document( $document_id );
635 $file_name = $d->get_url_file();
636 if ( $docname != '' &&
637 $docname != $file_name ) {
638 $path = $d->get_url_filepath();
639 $path = str_replace( $file_name, "", $path );
640 $new_url = $this->_rename_file( $path.$docname );
641 if ( rename( $d->get_url(), $new_url ) ) {
642 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
643 $url = preg_replace("|^(.*)://|","",$d->get_url());
644 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
645 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
646 if ( file_exists( $url ) ) {
647 unlink( $url );
649 $d->url = $new_url;
650 $d->persist();
651 $d->populate();
652 $messages .= xl('Document successfully renamed.')."<br>";
653 } else {
654 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
658 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
659 $docdate = "'$docdate'";
660 } else {
661 $docdate = "NULL";
663 if (!is_numeric($issue_id)) {
664 $issue_id = 0;
666 $sql = "UPDATE documents SET docdate = $docdate, " .
667 "list_id = '$issue_id' " .
668 "WHERE id = '$document_id'";
669 $this->tree->_db->Execute($sql);
670 $messages .= xl('Document date and issue updated successfully') . "<br>";
673 $this->_state = false;
674 $this->assign("messages", $messages);
675 return $this->view_action($patient_id, $document_id);
678 function list_action($patient_id = "") {
679 $this->_last_node = null;
680 $categories_list = $this->tree->_get_categories_array($patient_id);
681 //print_r($categories_list);
683 $menu = new HTML_TreeMenu();
684 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
685 $menu->addItem($rnode);
686 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
687 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
689 $this->assign("tree_html",$treeMenu->toHTML());
691 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
695 * This is a recursive function to rename a file to something that doesn't already exist.
696 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
697 * to ensure documents opened correctly by external browser viewers. If the counter is at the
698 * end of the file, then will use it (to continue to work with older files), however all new
699 * counters will be placed within filenames.
701 function _rename_file($fname) {
702 $file = basename($fname);
703 $fparts = split("\.",$fname);
704 $path = dirname($fname);
705 if (count($fparts) > 1) {
706 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
707 //increment the counter in filename
708 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
709 $fname = join(".",$fparts);
711 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
712 //increment counter at end of filename (so compatible with previous openemr version files
713 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
714 $fname = join(".",$fparts);
716 elseif (is_numeric($fparts[count($fparts) -1])) {
717 //leave date at end and place counter in filename
718 array_splice($fparts, -1, 0, "1");
719 $fname = join(".",$fparts);
721 else {
722 //add the counter to filename
723 array_splice($fparts, -1, 0, "1");
724 $fname = join(".",$fparts);
727 else { // (count($fparts) == 1)
728 //place counter at end of filename
729 array_push($fparts,"1");
730 $fname = join(".",$fparts);
733 if (file_exists($fname)) {
734 return $this->_rename_file($fname);
736 else {
737 return($fname);
741 function &_array_recurse($array,$categories = array()) {
742 if (!is_array($array)) {
743 $array = array();
745 $node = &$this->_last_node;
746 $current_node = &$node;
747 $expandedIcon = 'folder-expanded.gif';
748 foreach($array as $id => $ar) {
749 $icon = 'folder.gif';
750 if (is_array($ar) || !empty($id)) {
751 if ($node == null) {
752 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
753 $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));
754 $this->_last_node = &$rnode;
755 $node = &$rnode;
756 $current_node =&$rnode;
758 else {
759 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
760 $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)));
761 $current_node =&$this->_last_node;
764 $this->_array_recurse($ar,$categories);
766 else {
767 if ($id === 0 && !empty($ar)) {
768 $info = $this->tree->get_node_info($id);
769 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
770 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
772 else {
773 //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
774 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
775 if ($id !== 0 && is_object($node)) {
776 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
777 $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)));
783 // If there are documents in this document category, then add their
784 // attributes to the current node.
785 $icon = "file3.png";
786 if (is_array($categories[$id])) {
787 foreach ($categories[$id] as $doc) {
788 $current_node->addItem(new HTML_TreeNode(array(
789 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
790 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
791 'icon' => $icon,
792 'expandedIcon' => $expandedIcon
793 )));
798 return $node;
802 //place to hold optional code
803 //$first_node = array_keys($t->tree);
804 //$first_node = $first_node[0];
805 //$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')"));
807 //$this->_last_node = &$node1;