3 require_once(dirname(__FILE__
) . "/../library/classes/Controller.class.php");
4 require_once(dirname(__FILE__
) . "/../library/classes/Document.class.php");
5 require_once(dirname(__FILE__
) . "/../library/classes/CategoryTree.class.php");
6 require_once(dirname(__FILE__
) . "/../library/classes/TreeMenu.php");
7 require_once(dirname(__FILE__
) . "/../library/classes/Note.class.php");
9 class C_Document
extends Controller
{
13 var $document_categories;
19 function C_Document($template_mod = "general") {
21 $this->documents
= array();
22 $this->template_mod
= $template_mod;
23 $this->assign("FORM_ACTION", $GLOBALS['webroot']."/controller.php?" . $_SERVER['QUERY_STRING']);
24 $this->assign("CURRENT_ACTION", $GLOBALS['webroot']."/controller.php?" . "document&");
26 //get global config options for this namespace
27 $this->_config
= $GLOBALS['oer_config']['documents'];
29 $this->file_path
= $this->_config
['repository'] . preg_replace("/[^A-Za-z0-9]/","_",$_GET['patient_id']) . "/";
31 $this->_args
= array("patient_id" => $_GET['patient_id']);
33 $this->assign("STYLE", $GLOBALS['style']);
34 $t = new CategoryTree(1);
39 function upload_action($patient_id,$category_id) {
40 $category_name = $this->tree
->get_node_name($category_id);
41 $this->assign("category_id", $category_id);
42 $this->assign("category_name", $category_name);
43 $this->assign("patient_id", $patient_id);
44 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_upload.html");
45 $this->assign("activity", $activity);
46 return $this->list_action($patient_id);
49 function upload_action_process() {
51 if ($_POST['process'] != "true")
54 if (is_numeric($_POST['category_id'])) {
55 $category_id = $_POST['category_id'];
57 if (is_numeric($_POST['patient_id'])) {
58 $patient_id = $_POST['patient_id'];
61 foreach ($_FILES as $file) {
62 $fname = $file['name'];
64 if ($file['error'] > 0 ||
empty($file['name']) ||
$file['size'] == 0) {
65 $fname = $file['name'];
67 $fname = htmlentities("<empty>");
69 $error = "Error number: " . $file['error'] . " occured while uploading file named: " . $fname . "\n";
70 if ($file['size'] == 0) {
71 $error .= "The system does not permit uploading files of with size 0.\n";
77 if (!file_exists($this->file_path
)) {
78 if (!mkdir($this->file_path
,0700)) {
79 $error .= "The system was unable to create the directory for this upload, '" . $this->file_path
. "'.\n";
83 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
84 if (file_exists($this->file_path
.$file['name'])) {
85 $error .= xl('File with same name already exists at location:','','',' ') . $this->file_path
. "\n";
86 $fname = basename($this->_rename_file($this->file_path
.$file['name']));
87 $file['name'] = $fname;
88 $error .= xl('Current file name was changed to','','',' ') . $fname ."\n";
90 if (move_uploaded_file($file['tmp_name'],$this->file_path
.$file['name'])) {
91 $this->assign("upload_success", "true");
93 $d->url
= "file://" .$this->file_path
.$file['name'];
94 $d->mimetype
= $file['type'];
95 $d->size
= $file['size'];
96 $d->type
= $d->type_array
['file_url'];
97 $d->set_foreign_id($patient_id);
100 $this->assign("file",$d);
102 if (is_numeric($d->get_id()) && is_numeric($category_id)) {
103 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $category_id . "', document_id = '" . $d->get_id() . "'";
104 $d->_db
->Execute($sql);
108 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
112 $this->assign("error", nl2br($error));
113 //$this->_state = false;
114 $_POST['process'] = "";
115 //return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_upload.html");
118 function note_action_process($patient_id) {
120 if ($_POST['process'] != "true")
124 parent
::populate_object($n);
127 $this->_state
= false;
128 $_POST['process'] = "";
129 return $this->view_action($patient_id,$n->get_foreign_id());
132 function default_action() {
133 return $this->list_action();
136 function view_action($patient_id="",$doc_id) {
137 // Added by Rod to support document delete:
138 global $gacl_object, $phpgacl_location;
141 require_once(dirname(__FILE__
) . "/../library/acl.inc");
142 require_once(dirname(__FILE__
) . "/../library/lists.inc");
144 $d = new Document($doc_id);
147 $notes = $n->notes_factory($doc_id);
149 $this->assign("file", $d);
150 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
151 $this->assign("NOTE_ACTION",$this->_link("note"));
152 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
154 // Added by Rod to support document delete:
156 if (acl_check('admin', 'super')) {
157 $delete_string = "<a href='' class='css_button' onclick='return deleteme(" . $d->get_id() .
158 ")'><span><font color='red'>" . xl('Delete') . "</font></span></a>";
160 $this->assign("delete_string", $delete_string);
161 $this->assign("REFRESH_ACTION",$this->_link("list"));
163 // Added by Rod to support document date update:
164 $this->assign("DOCDATE", $d->get_docdate());
165 $this->assign("UPDATE_ACTION",$this->_link("update") .
166 "document_id=" . $d->get_id() . "&process=true");
168 // Added by Rod to support document issue update:
169 $issues_options = "<option value='0'>-- " . xl('Select Issue') . " --</option>";
170 $ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
171 "pid = $patient_id " . // AND enddate IS NULL " .
172 "ORDER BY type, begdate");
173 while ($irow = sqlFetchArray($ires)) {
174 $desc = $irow['type'];
175 if ($ISSUE_TYPES[$desc]) $desc = $ISSUE_TYPES[$desc][2];
176 $desc .= ": " . $irow['begdate'] . " " . htmlspecialchars(substr($irow['title'], 0, 40));
177 $sel = ($irow['id'] == $d->get_list_id()) ?
' selected' : '';
178 $issues_options .= "<option value='" . $irow['id'] . "'$sel>$desc</option>";
180 $this->assign("ISSUES_LIST", $issues_options);
182 $this->assign("notes",$notes);
184 $this->_last_node
= null;
186 $menu = new HTML_TreeMenu();
188 //pass an empty array because we don't want the documents for each category showing up in this list box
189 $rnode = $this->_array_recurse($this->tree
->tree
,array());
190 $menu->addItem($rnode);
191 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => xl('Move Document to Category:')));
193 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
195 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_view.html");
196 $this->assign("activity", $activity);
198 return $this->list_action($patient_id);
201 function retrieve_action($patient_id="",$document_id,$as_file=true,$original_file=true) {
203 //controller function ruins booleans, so need to manually re-convert to booleans
204 if ($as_file == "true") {
207 else if ($as_file == "false") {
210 if ($original_file == "true") {
213 else if ($original_file == "false") {
214 $original_file=false;
217 $d = new Document($document_id);
218 $url = $d->get_url();
220 //strip url of protocol handler
221 $url = preg_replace("|^(.*)://|","",$url);
223 //change full path to current webroot. this is for documents that may have
224 //been moved from a different filesystem and the full path in the database
225 //is not current. this is also for documents that may of been moved to
227 // NOTE that $from_filename and basename($url) are the same thing
228 $from_all = explode("/",$url);
229 $from_filename = array_pop($from_all);
230 $from_patientid = array_pop($from_all);
231 $temp_url = $GLOBALS["fileroot"].'/documents/'.$from_patientid.'/'.$from_filename;
232 if (file_exists($temp_url)) {
235 if (!file_exists($url)) {
236 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;
239 if ($original_file) {
240 //normal case when serving the file referenced in database
241 header("Pragma: public");
242 header("Expires: 0");
243 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
244 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
245 header("Content-Type: " . $d->get_mimetype());
246 header("Content-Length: " . $d->get_size());
247 $f = fopen($url,"r");
252 //special case when retrieving a document that has been converted to a jpg and not directly referenced in database
253 $convertedFile = substr(basename($url), 0, strrpos(basename($url), '.')) . '_converted.jpg';
254 $url = $GLOBALS["fileroot"].'/documents/'.$from_patientid.'/'.$convertedFile;
255 header("Pragma: public");
256 header("Expires: 0");
257 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
258 header("Content-Disposition: " . ($as_file ?
"attachment" : "inline") . "; filename=\"" . basename($url) . "\"");
259 header("Content-Type: image/jpeg");
260 header("Content-Length: " . filesize($url));
261 $f = fopen($url,"r");
268 function queue_action($patient_id="") {
269 $messages = $this->_tpl_vars
['messages'];
270 $queue_files = array();
272 //see if the repository exists and it is a directory else error
273 if (file_exists($this->_config
['repository']) && is_dir($this->_config
['repository'])) {
274 $dir = opendir($this->_config
['repository']);
275 //read each entry in the directory
276 while (($file = readdir($dir)) !== false) {
277 //concat the filename and path
278 $file = $this->_config
['repository'] .$file;
279 $file_info = array();
280 //if the filename is a file get its info and put into a tmp array
281 if (is_file($file) && strpos(basename($file),".") !== 0) {
282 $file_info['filename'] = basename($file);
283 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
284 $d = Document
::document_factory_url("file://" . $file);
285 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
286 $file_info['patient_id'] = $patient_match[1];
287 $file_info['document_id'] = $d->get_id();
288 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
290 //merge the tmp array into the larger array
291 $queue_files[] = $file_info;
297 $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";
301 $this->assign("queue_files",$queue_files);
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());
311 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
313 $this->assign("messages",nl2br($messages));
314 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_queue.html");
317 function queue_action_process() {
318 if ($_POST['process'] != "true")
321 $messages = $this->_tpl_vars
['messages'];
323 //build a category tree so we can have a list of category ids that are valid
324 $ct = new CategoryTree(1);
325 $categories = $ct->_id_name
;
327 //see if there were and posted files and assign them
329 is_array($_POST['files']) ?
$files = $_POST['files']: $files = array();
331 //loop through posted files
332 foreach($files as $doc_id=> $file) {
333 //only operate on files checked as active
334 if (!$file['active']) continue;
336 //run basic validation checks
337 if (!is_numeric($file['patient_id']) ||
!is_numeric($file['category_id']) ||
!is_numeric($doc_id)) {
338 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
342 //validate that the pod exists
343 $d = new Document($doc_id);
344 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
345 $result = $d->_db
->Execute($sql);
347 if (!$result ||
$result->EOF
) {
348 //patient id does not exist
349 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
353 //validate that the category id exists
354 if (!isset($categories[$file['category_id']])) {
355 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
359 //now do the work of moving the file
360 $new_path = $this->_config
['repository'] . $file['patient_id'] ."/";
362 //see if the patient dir exists in the repository and create if not
363 if (!file_exists($new_path)) {
364 if (!mkdir($new_path,0700)) {
365 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path
. "'.\n";
370 //fname is the name of the file after it is moved
371 $fname = $file['name'];
373 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
374 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
375 if ($patient_match[1] == $file['patient_id']) {
376 $fname = preg_replace("/^([0-9]+)_/","",$fname);
379 //filenames should not have funny chars
380 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
382 //see if there is an existing file with the same name and rename as necessary
383 if (file_exists($new_path.$file['name'])) {
384 $messages .= "File with same name already exists at location: " . $new_path . "\n";
385 $fname = basename($this->_rename_file($new_path.$file['name']));
386 $messages .= "Current file name was changed to " . $fname ."\n";
390 if (rename($this->_config
['repository'].$file['name'],$new_path.$fname)) {
391 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
392 $d->url
= "file://" .$new_path.$fname;
393 $d->set_foreign_id($file['patient_id']);
394 $d->set_mimetype($mimetype);
398 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
399 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
400 $d->_db
->Execute($sql);
404 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
407 $this->assign("messages",$messages);
408 $_POST['process'] = "";
411 function move_action_process($patient_id="",$document_id) {
412 if ($_POST['process'] != "true")
415 $new_category_id = $_POST['new_category_id'];
416 $new_patient_id = $_POST['new_patient_id'];
418 //move to new category
419 if (is_numeric($new_category_id) && is_numeric($document_id)) {
420 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
421 $messages .= xl('Document moved to new category','','',' \'') . $this->tree
->_id_name
[$new_category_id]['name'] . xl('successfully.','','\' ') . "\n";
423 $this->tree
->_db
->Execute($sql);
426 //move to new patient
427 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
428 $d = new Document($document_id);
429 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
430 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
431 $result = $d->_db
->Execute($sql);
433 if (!$result ||
$result->EOF
) {
434 //patient id does not exist
435 $messages .= xl('Document could not be moved to patient id','','',' \'') . $new_patient_id . xl('because that id does not exist.','','\' ') . "\n";
438 //set the new patient
439 $d->set_foreign_id($new_patient_id);
441 $this->_state
= false;
442 $messages .= xl('Document moved to patient id','','',' \'') . $new_patient_id . xl('successfully.','','\' ') . "\n";
443 $this->assign("messages",$messages);
444 return $this->list_action($patient_id);
447 //in this case return the document to the queue instead of moving it
448 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
449 $d = new Document($document_id);
450 $new_path = $this->_config
['repository'];
451 $fname = $d->get_url_file();
453 //see if there is an existing file with the same name and rename as necessary
454 if (file_exists($new_path.$d->get_url_file())) {
455 $messages .= "File with same name already exists in the queue.\n";
456 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
457 $messages .= "Current file name was changed to " . $fname ."\n";
461 if (rename($d->get_url_filepath(),$new_path.$fname)) {
462 $d->url
= "file://" .$new_path.$fname;
463 $d->set_foreign_id("");
468 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db
->qstr($document_id);
469 $d->_db
->Execute($sql);
470 $messages .= "Document returned to queue successfully.\n";
474 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
477 $this->_state
= false;
478 $this->assign("messages",$messages);
479 return $this->list_action($patient_id);
482 $this->_state
= false;
483 $this->assign("messages",$messages);
484 return $this->view_action($patient_id,$document_id);
487 // Added by Rod for metadata update.
489 function update_action_process($patient_id="", $document_id) {
490 if ($_POST['process'] != "true") {
491 die("process is '" . $_POST['process'] . "', expected 'true'");
495 $docdate = $_POST['docdate'];
496 $issue_id = $_POST['issue_id'];
498 if (is_numeric($document_id)) {
499 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
500 $docdate = "'$docdate'";
504 if (!is_numeric($issue_id)) {
507 $sql = "UPDATE documents SET docdate = $docdate, " .
508 "list_id = '$issue_id' " .
509 "WHERE id = '$document_id'";
510 $this->tree
->_db
->Execute($sql);
511 $messages .= xl('Document date and issue updated successfully') . "\n";
514 $this->_state
= false;
515 $this->assign("messages", $messages);
516 return $this->view_action($patient_id, $document_id);
519 function list_action($patient_id = "") {
520 $this->_last_node
= null;
521 $categories_list = $this->tree
->_get_categories_array($patient_id);
522 //print_r($categories_list);
524 $menu = new HTML_TreeMenu();
525 $rnode = $this->_array_recurse($this->tree
->tree
,$categories_list);
526 $menu->addItem($rnode);
527 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
528 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
530 $this->assign("tree_html",$treeMenu->toHTML());
532 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod
. "_list.html");
536 * This is a recursive function to rename a file to something that doesn't already exist.
537 * Modified in version 3.2.0 to place a counter within the filename (previously was placed at end)
538 * to ensure documents opened correctly by external browser viewers. If the counter is at the
539 * end of the file, then will use it (to continue to work with older files), however all new
540 * counters will be placed within filenames.
542 function _rename_file($fname) {
543 $file = basename($fname);
544 $fparts = split("\.",$fname);
545 $path = dirname($fname);
546 if (count($fparts) > 1) {
547 if (is_numeric($fparts[count($fparts) -2]) && (count($fparts) > 2)) {
548 //increment the counter in filename
549 $fparts[count($fparts) -2] = $fparts[count($fparts) -2] +
1;
550 $fname = join(".",$fparts);
552 elseif (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
553 //increment counter at end of filename (so compatible with previous openemr version files
554 $fparts[count($fparts) -1] = $fparts[count($fparts) -1] +
1;
555 $fname = join(".",$fparts);
557 elseif (is_numeric($fparts[count($fparts) -1])) {
558 //leave date at end and place counter in filename
559 array_splice($fparts, -1, 0, "1");
560 $fname = join(".",$fparts);
563 //add the counter to filename
564 array_splice($fparts, -1, 0, "1");
565 $fname = join(".",$fparts);
568 else { // (count($fparts) == 1)
569 //place counter at end of filename
570 array_push($fparts,"1");
571 $fname = join(".",$fparts);
574 if (file_exists($fname)) {
575 return $this->_rename_file($fname);
582 function &_array_recurse($array,$categories = array()) {
583 if (!is_array($array)) {
586 $node = &$this->_last_node
;
587 $current_node = &$node;
588 $expandedIcon = 'folder-expanded.gif';
589 foreach($array as $id => $ar) {
590 $icon = 'folder.gif';
591 if (is_array($ar) ||
!empty($id)) {
593 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
594 $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));
595 $this->_last_node
= &$rnode;
597 $current_node =&$rnode;
600 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
601 $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)));
602 $current_node =&$this->_last_node
;
605 $this->_array_recurse($ar,$categories);
608 if ($id === 0 && !empty($ar)) {
609 $info = $this->tree
->get_node_info($id);
610 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
611 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
614 //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
615 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
616 if ($id !== 0 && is_object($node)) {
617 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
618 $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)));
624 // If there are documents in this document category, then add their
625 // attributes to the current node.
627 if (is_array($categories[$id])) {
628 foreach ($categories[$id] as $doc) {
629 $current_node->addItem(new HTML_TreeNode(array(
630 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
631 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
633 'expandedIcon' => $expandedIcon
643 //place to hold optional code
644 //$first_node = array_keys($t->tree);
645 //$first_node = $first_node[0];
646 //$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')"));
648 //$this->_last_node = &$node1;