modified: messages.php
[openemr.git] / controllers / C_Document.class.php
blob6d21dc09fd5561d11614da17aa9eb25246f762ab
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 if ($file['type'] == 'text/xml') {
122 $d->mimetype = 'application/xml';
124 else {
125 $d->mimetype = $file['type'];
127 $d->size = $file['size'];
128 $sha1Hash = sha1_file( $this->file_path.$fname );
129 $d->hash = $sha1Hash;
130 $d->type = $d->type_array['file_url'];
131 $d->set_foreign_id($patient_id);
132 $d->persist();
133 $d->populate();
134 $this->assign("file",$d);
136 if (is_numeric($d->get_id()) && is_numeric($category_id)) {
137 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
138 $d->_db->Execute($sql);
141 else {
142 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
146 $this->assign("error", nl2br($error));
147 //$this->_state = false;
148 $_POST['process'] = "";
149 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
152 function note_action_process($patient_id) {
154 if ($_POST['process'] != "true")
155 return;
157 $n = new Note();
158 parent::populate_object($n);
159 $n->persist();
161 $this->_state = false;
162 $_POST['process'] = "";
163 return $this->view_action($patient_id,$n->get_foreign_id());
166 function default_action() {
167 return $this->list_action();
170 function view_action($patient_id="",$doc_id) {
171 // Added by Rod to support document delete:
172 global $gacl_object, $phpgacl_location;
173 global $ISSUE_TYPES;
175 require_once(dirname(__FILE__) . "/../library/acl.inc");
176 require_once(dirname(__FILE__) . "/../library/lists.inc");
178 $d = new Document($doc_id);
179 $n = new Note();
181 $notes = $n->notes_factory($doc_id);
183 $this->assign("file", $d);
184 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
185 $this->assign("NOTE_ACTION",$this->_link("note"));
186 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
187 $this->assign("hide_encryption", $GLOBALS['hide_document_encryption'] );
189 // Added by Rod to support document delete:
190 $delete_string = '';
191 if (acl_check('admin', 'super')) {
192 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
193 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
195 $this->assign("delete_string", $delete_string);
196 $this->assign("REFRESH_ACTION",$this->_link("list"));
198 $this->assign("VALIDATE_ACTION",$this->_link("validate") .
199 "document_id=" . $d->get_id() . "&process=true");
201 // Added by Rod to support document date update:
202 $this->assign("DOCDATE", $d->get_docdate());
203 $this->assign("UPDATE_ACTION",$this->_link("update") .
204 "document_id=" . $d->get_id() . "&process=true");
206 // Added by Rod to support document issue update:
207 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
208 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
209 "pid = $patient_id " . // AND enddate IS NULL " .
210 "ORDER BY type, begdate");
211 while ($irow = sqlFetchArray($ires)) {
212 $desc = $irow['type'];
213 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
214 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
215 $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';
216 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
218 $this->assign("ISSUES_LIST", $issues_options);
220 $this->assign("notes",$notes);
222 $this->_last_node = null;
224 $menu = new HTML_TreeMenu();
226 //pass an empty array because we don't want the documents for each category showing up in this list box
227 $rnode = $this->_array_recurse($this->tree->tree,array());
228 $menu->addItem($rnode);
229 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
231 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
233 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
234 $this->assign("activity", $activity);
236 return $this->list_action($patient_id);
239 function encrypt( $plaintext, $key, $cypher = 'tripledes', $mode = 'cfb' )
241 $td = mcrypt_module_open( $cypher, '', $mode, '');
242 $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND );
243 mcrypt_generic_init( $td, $key, $iv );
244 $crypttext = mcrypt_generic( $td, $plaintext );
245 mcrypt_generic_deinit( $td );
246 return $iv.$crypttext;
249 function decrypt( $crypttext, $key, $cypher = 'tripledes', $mode = 'cfb' )
251 $plaintext = '';
252 $td = mcrypt_module_open( $cypher, '', $mode, '' );
253 $ivsize = mcrypt_enc_get_iv_size( $td) ;
254 $iv = substr( $crypttext, 0, $ivsize );
255 $crypttext = substr( $crypttext, $ivsize );
256 if( $iv )
258 mcrypt_generic_init( $td, $key, $iv );
259 $plaintext = mdecrypt_generic( $td, $crypttext );
261 return $plaintext;
265 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
267 $encrypted = $_POST['encrypted'];
268 $passphrase = $_POST['passphrase'];
269 $doEncryption = false;
270 if ( !$GLOBALS['hide_document_encryption'] &&
271 $encrypted == "true" &&
272 $passphrase ) {
273 $doEncryption = true;
276 //controller function ruins booleans, so need to manually re-convert to booleans
277 if ($as_file == "true") {
278 $as_file=true;
280 else if ($as_file == "false") {
281 $as_file=false;
283 if ($original_file == "true") {
284 $original_file=true;
286 else if ($original_file == "false") {
287 $original_file=false;
290 $d = new Document($document_id);
291 $url = $d->get_url();
293 //strip url of protocol handler
294 $url = preg_replace("|^(.*)://|","",$url);
296 //change full path to current webroot. this is for documents that may have
297 //been moved from a different filesystem and the full path in the database
298 //is not current. this is also for documents that may of been moved to
299 //different patients
300 // NOTE that $from_filename and basename($url) are the same thing
301 $from_all = explode("/",$url);
302 $from_filename = array_pop($from_all);
303 $from_patientid = array_pop($from_all);
304 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
305 if (file_exists($temp_url)) {
306 $url = $temp_url;
308 if (!file_exists($url)) {
309 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;
311 else {
312 if ($original_file) {
313 //normal case when serving the file referenced in database
314 header('Content-Description: File Transfer');
315 header('Content-Transfer-Encoding: binary');
316 header('Expires: 0');
317 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
318 header('Pragma: public');
319 $f = fopen($url,"r");
320 if ( $doEncryption ) {
321 $filetext = fread( $f, filesize($url) );
322 $ciphertext = $this->encrypt( $filetext, $passphrase );
323 $tmpfilepath = $GLOBALS['temporary_files_dir'];
324 $tmpfilename = "/encrypted_".$d->get_url_file();
325 $tmpfile = fopen( $tmpfilepath.$tmpfilename, "w+" );
326 fwrite( $tmpfile, $ciphertext );
327 fclose( $tmpfile );
328 header('Content-Disposition: attachment; filename='.$tmpfilename );
329 header("Content-Type: application/octet-stream" );
330 header("Content-Length: " . filesize( $tmpfilepath.$tmpfilename ) );
331 ob_clean();
332 flush();
333 readfile( $tmpfilepath.$tmpfilename );
334 unlink( $tmpfilepath.$tmpfilename );
335 } else {
336 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
337 header("Content-Type: " . $d->get_mimetype());
338 header("Content-Length: " . filesize($url));
339 fpassthru($f);
341 exit;
343 else {
344 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
345 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
346 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $convertedFile;
347 header("Pragma: public");
348 header("Expires: 0");
349 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
350 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
351 header("Content-Type: image/jpeg");
352 header("Content-Length: " . filesize($url));
353 $f = fopen($url,"r");
354 fpassthru($f);
355 exit;
360 function queue_action($patient_id="") {
361 $messages = $this->_tpl_vars['messages'];
362 $queue_files = array();
364 //see if the repository exists and it is a directory else error
365 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
366 $dir = opendir($this->_config['repository']);
367 //read each entry in the directory
368 while (($file = readdir($dir)) !== false) {
369 //concat the filename and path
370 $file = $this->_config['repository'] .$file;
371 $file_info = array();
372 //if the filename is a file get its info and put into a tmp array
373 if (is_file($file) && strpos(basename($file),".") !== 0) {
374 $file_info['filename'] = basename($file);
375 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
376 $d = Document::document_factory_url("file://" . $file);
377 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
378 $file_info['patient_id'] = $patient_match[1];
379 $file_info['document_id'] = $d->get_id();
380 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
382 //merge the tmp array into the larger array
383 $queue_files[] = $file_info;
386 closedir($dir);
388 else {
389 $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";
393 $this->assign("queue_files",$queue_files);
394 $this->_last_node = null;
396 $menu = new HTML_TreeMenu();
398 //pass an empty array because we don't want the documents for each category showing up in this list box
399 $rnode = $this->_array_recurse($this->tree->tree,array());
400 $menu->addItem($rnode);
401 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
403 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
405 $this->assign("messages",nl2br($messages));
406 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
409 function queue_action_process() {
410 if ($_POST['process'] != "true")
411 return;
413 $messages = $this->_tpl_vars['messages'];
415 //build a category tree so we can have a list of category ids that are valid
416 $ct = new CategoryTree(1);
417 $categories = $ct->_id_name;
419 //see if there were and posted files and assign them
420 $files = null;
421 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
423 //loop through posted files
424 foreach($files as $doc_id=> $file) {
425 //only operate on files checked as active
426 if (!$file['active']) continue;
428 //run basic validation checks
429 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
430 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
431 continue;
434 //validate that the pod exists
435 $d = new Document($doc_id);
436 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
437 $result = $d->_db->Execute($sql);
439 if (!$result || $result->EOF) {
440 //patient id does not exist
441 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
442 continue;
445 //validate that the category id exists
446 if (!isset($categories[$file['category_id']])) {
447 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
448 continue;
451 //now do the work of moving the file
452 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
454 //see if the patient dir exists in the repository and create if not
455 if (!file_exists($new_path)) {
456 if (!mkdir($new_path,0700)) {
457 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
458 continue;
462 //fname is the name of the file after it is moved
463 $fname = $file['name'];
465 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
466 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
467 if ($patient_match[1] == $file['patient_id']) {
468 $fname = preg_replace("/^([0-9]+)_/","",$fname);
471 //filenames should not have funny chars
472 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
474 //see if there is an existing file with the same name and rename as necessary
475 if (file_exists($new_path.$file['name'])) {
476 $messages .= "File with same name already exists at location: " . $new_path . "\n";
477 $fname = basename($this->_rename_file($new_path.$file['name']));
478 $messages .= "Current file name was changed to " . $fname ."\n";
481 //now move the file
482 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
483 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
484 $d->url = "file://" .$new_path.$fname;
485 $d->set_foreign_id($file['patient_id']);
486 $d->set_mimetype($mimetype);
487 $d->persist();
488 $d->populate();
490 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
491 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
492 $d->_db->Execute($sql);
495 else {
496 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
499 $this->assign("messages",$messages);
500 $_POST['process'] = "";
503 function move_action_process($patient_id="",$document_id) {
504 if ($_POST['process'] != "true")
505 return;
507 $new_category_id = $_POST['new_category_id'];
508 $new_patient_id = $_POST['new_patient_id'];
510 //move to new category
511 if (is_numeric($new_category_id) && is_numeric($document_id)) {
512 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
513 $messages .= xl('Document moved to new category','','',' \'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
514 //echo $sql;
515 $this->tree->_db->Execute($sql);
518 //move to new patient
519 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
520 $d = new Document($document_id);
521 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
522 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
523 $result = $d->_db->Execute($sql);
525 if (!$result || $result->EOF) {
526 //patient id does not exist
527 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
529 else {
530 //set the new patient
531 $d->set_foreign_id($new_patient_id);
532 $d->persist();
533 $this->_state = false;
534 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
535 $this->assign("messages",$messages);
536 return $this->list_action($patient_id);
539 //in this case return the document to the queue instead of moving it
540 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
541 $d = new Document($document_id);
542 $new_path = $this->_config['repository'];
543 $fname = $d->get_url_file();
545 //see if there is an existing file with the same name and rename as necessary
546 if (file_exists($new_path.$d->get_url_file())) {
547 $messages .= "File with same name already exists in the queue.\n";
548 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
549 $messages .= "Current file name was changed to " . $fname ."\n";
552 //now move the file
553 if (rename($d->get_url_filepath(),$new_path.$fname)) {
554 $d->url = "file://" .$new_path.$fname;
555 $d->set_foreign_id("");
556 $d->persist();
557 $d->persist();
558 $d->populate();
560 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
561 $d->_db->Execute($sql);
562 $messages .= "Document returned to queue successfully.\n";
565 else {
566 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
569 $this->_state = false;
570 $this->assign("messages",$messages);
571 return $this->list_action($patient_id);
574 $this->_state = false;
575 $this->assign("messages",$messages);
576 return $this->view_action($patient_id,$document_id);
579 function validate_action_process($patient_id="", $document_id) {
581 $d = new Document($document_id);
582 $url = $d->get_url();
584 //strip url of protocol handler
585 $url = preg_replace("|^(.*)://|","",$url);
587 //change full path to current webroot. this is for documents that may have
588 //been moved from a different filesystem and the full path in the database
589 //is not current. this is also for documents that may of been moved to
590 //different patients
591 // NOTE that $from_filename and basename($url) are the same thing
592 $from_all = explode("/",$url);
593 $from_filename = array_pop($from_all);
594 $from_patientid = array_pop($from_all);
595 $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_patientid . '/' . $from_filename;
596 if (file_exists($temp_url)) {
597 $url = $temp_url;
600 if ($_POST['process'] != "true") {
601 die("process is '" . $_POST['process'] . "', expected 'true'");
602 return;
605 $d = new Document( $document_id );
606 $current_hash = sha1_file( $url );
607 $messages = xl('Current Hash').": ".$current_hash."<br>";
608 $messages .= xl('Stored Hash').": ".$d->get_hash()."<br>";
609 if ( $d->get_hash() == '' ) {
610 $d->hash = $current_hash;
611 $d->persist();
612 $d->populate();
613 $messages .= xl('Hash did not exist for this file. A new hash was generated.');
614 } else if ( $current_hash != $d->get_hash() ) {
615 $messages .= xl('Hash does not match. Data integrity has been compromised.');
616 } else {
617 $messages .= xl('Document passed integrity check.');
620 $this->_state = false;
621 $this->assign("messages", $messages);
622 return $this->view_action($patient_id, $document_id);
625 // Added by Rod for metadata update.
627 function update_action_process($patient_id="", $document_id) {
628 if ($_POST['process'] != "true") {
629 die("process is '" . $_POST['process'] . "', expected 'true'");
630 return;
633 $docdate = $_POST['docdate'];
634 $docname = $_POST['docname'];
635 $issue_id = $_POST['issue_id'];
637 if (is_numeric($document_id)) {
638 $messages = '';
639 $d = new Document( $document_id );
640 $file_name = $d->get_url_file();
641 if ( $docname != '' &&
642 $docname != $file_name ) {
643 $path = $d->get_url_filepath();
644 $path = str_replace( $file_name, "", $path );
645 $new_url = $this->_rename_file( $path.$docname );
646 if ( rename( $d->get_url(), $new_url ) ) {
647 // check the "converted" file, and delete it if it exists. It will be regenerated when report is run
648 $url = preg_replace("|^(.*)://|","",$d->get_url());
649 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
650 $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $patient_id . '/' . $convertedFile;
651 if ( file_exists( $url ) ) {
652 unlink( $url );
654 $d->url = $new_url;
655 $d->persist();
656 $d->populate();
657 $messages .= xl('Document successfully renamed.')."<br>";
658 } else {
659 $messages .= xl('The file could not be succesfully renamed, this error is usually related to permissions problems on the storage system.')."<br>";
663 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
664 $docdate = "'$docdate'";
665 } else {
666 $docdate = "NULL";
668 if (!is_numeric($issue_id)) {
669 $issue_id = 0;
671 $sql = "UPDATE documents SET docdate = $docdate, " .
672 "list_id = '$issue_id' " .
673 "WHERE id = '$document_id'";
674 $this->tree->_db->Execute($sql);
675 $messages .= xl('Document date and issue updated successfully') . "<br>";
678 $this->_state = false;
679 $this->assign("messages", $messages);
680 return $this->view_action($patient_id, $document_id);
683 function list_action($patient_id = "") {
684 $this->_last_node = null;
685 $categories_list = $this->tree->_get_categories_array($patient_id);
686 //print_r($categories_list);
688 $menu = new HTML_TreeMenu();
689 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
690 $menu->addItem($rnode);
691 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
692 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
694 $this->assign("tree_html",$treeMenu->toHTML());
696 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
700 * This is a recursive function to rename a file to something that doesn't already exist.
701 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
702 * to ensure documents opened correctly by external browser viewers. If the counter is at the
703 * end of the file, then will use it (to continue to work with older files), however all new
704 * counters will be placed within filenames.
706 function _rename_file($fname) {
707 $file = basename($fname);
708 $fparts = split("\.",$fname);
709 $path = dirname($fname);
710 if (count($fparts) > 1) {
711 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
712 //increment the counter in filename
713 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] + 1;
714 $fname = join(".",$fparts);
716 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
717 //increment counter at end of filename (so compatible with previous openemr version files
718 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] + 1;
719 $fname = join(".",$fparts);
721 elseif (is_numeric($fparts[count($fparts) -1])) {
722 //leave date at end and place counter in filename
723 array_splice($fparts, -1, 0, "1");
724 $fname = join(".",$fparts);
726 else {
727 //add the counter to filename
728 array_splice($fparts, -1, 0, "1");
729 $fname = join(".",$fparts);
732 else { // (count($fparts) == 1)
733 //place counter at end of filename
734 array_push($fparts,"1");
735 $fname = join(".",$fparts);
738 if (file_exists($fname)) {
739 return $this->_rename_file($fname);
741 else {
742 return($fname);
746 function &_array_recurse($array,$categories = array()) {
747 if (!is_array($array)) {
748 $array = array();
750 $node = &$this->_last_node;
751 $current_node = &$node;
752 $expandedIcon = 'folder-expanded.gif';
753 foreach($array as $id => $ar) {
754 $icon = 'folder.gif';
755 if (is_array($ar) || !empty($id)) {
756 if ($node == null) {
757 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
758 $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));
759 $this->_last_node = &$rnode;
760 $node = &$rnode;
761 $current_node =&$rnode;
763 else {
764 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
765 $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)));
766 $current_node =&$this->_last_node;
769 $this->_array_recurse($ar,$categories);
771 else {
772 if ($id === 0 && !empty($ar)) {
773 $info = $this->tree->get_node_info($id);
774 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
775 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
777 else {
778 //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
779 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
780 if ($id !== 0 && is_object($node)) {
781 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
782 $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)));
788 // If there are documents in this document category, then add their
789 // attributes to the current node.
790 $icon = "file3.png";
791 if (is_array($categories[$id])) {
792 foreach ($categories[$id] as $doc) {
793 if($this->tree->get_node_name($id) == "CCR"){
794 $current_node->addItem(new HTML_TreeNode(array(
795 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
796 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
797 'icon' => $icon,
798 'expandedIcon' => $expandedIcon,
799 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCR&doc_id=" . $doc['document_id'] . "','CCR');")
800 )));
801 }elseif($this->tree->get_node_name($id) == "CCD"){
802 $current_node->addItem(new HTML_TreeNode(array(
803 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
804 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
805 'icon' => $icon,
806 'expandedIcon' => $expandedIcon,
807 'events' => array('Onclick' => "javascript:newwindow=window.open('ccr/display.php?type=CCD&doc_id=" . $doc['document_id'] . "','CCD');")
808 )));
809 }else{
810 $current_node->addItem(new HTML_TreeNode(array(
811 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
812 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
813 'icon' => $icon,
814 'expandedIcon' => $expandedIcon
815 )));
821 return $node;
825 //place to hold optional code
826 //$first_node = array_keys($t->tree);
827 //$first_node = $first_node[0];
828 //$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')"));
830 //$this->_last_node = &$node1;