option for using DOS as billing date added
[openemr.git] / controllers / C_Document.class.php
blobaa966b1e12f43328b17909a46d176b3a5422d408
1 <?php
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 {
11 var $template_mod;
12 var $documents;
13 var $document_categories;
14 var $tree;
15 var $_config;
16 var $file_path;
19 function C_Document($template_mod = "general") {
20 parent::Controller();
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);
35 //print_r($t->tree);
36 $this->tree = $t;
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")
52 return;
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'];
63 $err = "";
64 if ($file['error'] > 0 || empty($file['name']) || $file['size'] == 0) {
65 $fname = $file['name'];
66 if (empty($fname)) {
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";
75 else {
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 .= "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 .= "Current file name was changed to " . $fname ."\n";
90 if (move_uploaded_file($file['tmp_name'],$this->file_path.$file['name'])) {
91 $error .= "File " . $file['name'] . " successfully stored.\n";
92 $d = new Document();
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);
98 $d->persist();
99 $d->populate();
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);
107 else {
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")
121 return;
123 $n = new Note();
124 parent::populate_object($n);
125 $n->persist();
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) {
138 $d = new Document($doc_id);
139 $n = new Note();
141 $notes = $n->notes_factory($doc_id);
143 $this->assign("file", $d);
144 $this->assign("web_path", $this->_link("retrieve") . "document_id=" . $d->get_id() . "&");
145 $this->assign("NOTE_ACTION",$this->_link("note"));
146 $this->assign("MOVE_ACTION",$this->_link("move") . "document_id=" . $d->get_id() . "&process=true");
148 $this->assign("notes",$notes);
150 $this->_last_node = null;
152 $menu = new HTML_TreeMenu();
154 //pass an empty array because we don't want the documents for each category showing up in this list box
155 $rnode = $this->_array_recurse($this->tree->tree,array());
156 $menu->addItem($rnode);
157 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array("promoText" => "Move Document to Category:"));
159 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
161 $activity = $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_view.html");
162 $this->assign("activity", $activity);
164 return $this->list_action($patient_id);
167 function retrieve_action($patient_id="",$document_id,$as_file=true) {
168 $d = new Document($document_id);
169 $url = $d->get_url();
171 //strip url of protocol handler
172 $url = preg_replace("|^(.*)://|","",$url);
174 if (!file_exists($url)) {
175 echo "The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it. $url";
177 else {
178 header("Pragma: public");
179 header("Expires: 0");
180 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
181 if ($as_file) {
182 header("Content-Disposition: attachment; filename=\"" . basename($d->get_url()) . "\"");
184 header("Content-Type: " . $d->get_mimetype());
185 header("Content-Length: " . $d->get_size());
186 $f = fopen($url,"r");
187 fpassthru($f);
188 exit;
192 function queue_action($patient_id="") {
193 $messages = $this->_tpl_vars['messages'];
194 $queue_files = array();
196 //see if the repository exists and it is a directory else error
197 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
198 $dir = opendir($this->_config['repository']);
199 //read each entry in the directory
200 while (($file = readdir($dir)) !== false) {
201 //concat the filename and path
202 $file = $this->_config['repository'] .$file;
203 $file_info = array();
204 //if the filename is a file get its info and put into a tmp array
205 if (is_file($file) && strpos(basename($file),".") !== 0) {
206 $file_info['filename'] = basename($file);
207 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
208 $d = Document::document_factory_url("file://" . $file);
209 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
210 $file_info['patient_id'] = $patient_match[1];
211 $file_info['document_id'] = $d->get_id();
212 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
214 //merge the tmp array into the larger array
215 $queue_files[] = $file_info;
218 closedir($dir);
220 else {
221 $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";
225 $this->assign("queue_files",$queue_files);
226 $this->_last_node = null;
228 $menu = new HTML_TreeMenu();
230 //pass an empty array because we don't want the documents for each category showing up in this list box
231 $rnode = $this->_array_recurse($this->tree->tree,array());
232 $menu->addItem($rnode);
233 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
235 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
237 $this->assign("messages",nl2br($messages));
238 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
241 function queue_action_process() {
242 if ($_POST['process'] != "true")
243 return;
245 $messages = $this->_tpl_vars['messages'];
247 //build a category tree so we can have a list of category ids that are valid
248 $ct = new CategoryTree(1);
249 $categories = $ct->_id_name;
251 //see if there were and posted files and assign them
252 $files = null;
253 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
255 //loop through posted files
256 foreach($files as $doc_id=> $file) {
257 //only operate on files checked as active
258 if (!$file['active']) continue;
260 //run basic validation checks
261 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
262 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
263 continue;
266 //validate that the pod exists
267 $d = new Document($doc_id);
268 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
269 $result = $d->_db->Execute($sql);
271 if (!$result || $result->EOF) {
272 //patient id does not exist
273 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
274 continue;
277 //validate that the category id exists
278 if (!isset($categories[$file['category_id']])) {
279 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
280 continue;
283 //now do the work of moving the file
284 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
286 //see if the patient dir exists in the repository and create if not
287 if (!file_exists($new_path)) {
288 if (!mkdir($new_path,0700)) {
289 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
290 continue;
294 //fname is the name of the file after it is moved
295 $fname = $file['name'];
297 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
298 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
299 if ($patient_match[1] == $file['patient_id']) {
300 $fname = preg_replace("/^([0-9]+)_/","",$fname);
303 //filenames should not have funny chars
304 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
306 //see if there is an existing file with the same name and rename as necessary
307 if (file_exists($new_path.$file['name'])) {
308 $messages .= "File with same name already exists at location: " . $new_path . "\n";
309 $fname = basename($this->_rename_file($new_path.$file['name']));
310 $messages .= "Current file name was changed to " . $fname ."\n";
313 //now move the file
314 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
315 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
316 $d->url = "file://" .$new_path.$fname;
317 $d->set_foreign_id($file['patient_id']);
318 $d->set_mimetype($mimetype);
319 $d->persist();
320 $d->populate();
322 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
323 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
324 $d->_db->Execute($sql);
327 else {
328 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
331 $this->assign("messages",$messages);
332 $_POST['process'] = "";
335 function move_action_process($patient_id="",$document_id) {
336 if ($_POST['process'] != "true")
337 return;
339 $new_category_id = $_POST['new_category_id'];
340 $new_patient_id = $_POST['new_patient_id'];
342 //move to new category
343 if (is_numeric($new_category_id) && is_numeric($document_id)) {
344 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
345 $messages .= "Document moved to new category '" . $this->tree->_id_name[$new_category_id]['name'] . "' successfully.\n";
346 //echo $sql;
347 $this->tree->_db->Execute($sql);
350 //move to new patient
351 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
352 $d = new Document($document_id);
353 $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
354 $result = $d->_db->Execute($sql);
356 if (!$result || $result->EOF) {
357 //patient id does not exist
358 $messages .= "Document could not be moved to patient id '" . $new_patient_id . "' because that id does not exist.\n";
360 else {
361 //set the new patient
362 $d->set_foreign_id($new_patient_id);
363 $d->persist();
364 $this->_state = false;
365 $messages .= "Document moved to patient id '" . $new_patient_id . "' successfully.\n";
366 $this->assign("messages",$messages);
367 return $this->list_action($patient_id);
370 //in this case return the document to the queue instead of moving it
371 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
372 $d = new Document($document_id);
373 $new_path = $this->_config['repository'];
374 $fname = $d->get_url_file();
376 //see if there is an existing file with the same name and rename as necessary
377 if (file_exists($new_path.$d->get_url_file())) {
378 $messages .= "File with same name already exists in the queue.\n";
379 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
380 $messages .= "Current file name was changed to " . $fname ."\n";
383 //now move the file
384 if (rename($d->get_url_filepath(),$new_path.$fname)) {
385 $d->url = "file://" .$new_path.$fname;
386 $d->set_foreign_id("");
387 $d->persist();
388 $d->persist();
389 $d->populate();
391 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
392 $d->_db->Execute($sql);
393 $messages .= "Document returned to queue successfully.\n";
396 else {
397 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
400 $this->_state = false;
401 $this->assign("messages",$messages);
402 return $this->list_action($patient_id);
405 $this->_state = false;
406 $this->assign("messages",$messages);
407 return $this->view_action($patient_id,$document_id);
410 function list_action($patient_id = "") {
411 $this->_last_node = null;
412 $categories_list = $this->tree->_get_categories_array($patient_id);
413 //print_r($categories_list);
415 $menu = new HTML_TreeMenu();
416 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
417 $menu->addItem($rnode);
418 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
419 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
421 $this->assign("tree_html",$treeMenu->toHTML());
423 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
427 * This is a recursive function to rename a file to something that doesn't already exist. It appends a numeric to the end of the file, if
428 * the file already has a numeric it increments that.
429 * It supports numeric endings upto 1000, after which it uses an md5sum on now() instead. This is because some files end in
430 * dates and we don't want to increment those.
432 function _rename_file($fname) {
433 $file = basename($fname);
434 $fparts = split("\.",$fname);
435 $path = dirname($fname);
436 if (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
437 $new_name = "";
438 for($i=0;$i<count($fparts);$i++) {
439 if ($i == (count($fparts) -1)) {
440 $new_name .= ($fparts[$i] +1);
442 else {
443 $new_name .= $fparts[$i] . ".";
446 $fname = $new_name;
448 elseif (is_numeric($fparts[count($fparts)])) {
449 $fname = $fname . "." . md5sum(now());
451 else {
452 $fname = $fname . ".1";
454 if (file_exists($fname)) {
455 return $this->_rename_file($fname);
457 else {
458 return($fname);
462 function &_array_recurse($array,$categories = array()) {
463 if (!is_array($array)) {
464 $array = array();
466 $node = &$this->_last_node;
467 $current_node = &$node;
468 $expandedIcon = 'folder-expanded.gif';
469 foreach($array as $id => $ar) {
470 $icon = 'folder.gif';
471 if (is_array($ar) || !empty($id)) {
472 if ($node == null) {
473 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
474 $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));
475 $this->_last_node = &$rnode;
476 $node = &$rnode;
477 $current_node =&$rnode;
479 else {
480 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
481 $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)));
482 $current_node =&$this->_last_node;
485 $this->_array_recurse($ar,$categories);
487 else {
488 if ($id === 0 && !empty($ar)) {
489 $info = $this->tree->get_node_info($id);
490 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
491 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
493 else {
494 //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
495 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
496 if ($id !== 0 && is_object($node)) {
497 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
498 $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)));
504 $icon = "file3.png";
505 if (is_array($categories[$id])) {
506 foreach ($categories[$id] as $doc) {
507 $current_node->addItem(new HTML_TreeNode(array('text' => basename($doc['url']), 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
511 return $node;
516 //place to hold optional code
517 //$first_node = array_keys($t->tree);
518 //$first_node = $first_node[0];
519 //$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')"));
521 //$this->_last_node = &$node1;