fix for document embedding bug
[openemr.git] / controllers / C_Document.class.php
blobea65701dcc08fa366cc1827ad7da98ab4ff4436b
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) {
137 // Added by Rod to support document delete:
138 global $gacl_object, $phpgacl_location;
139 global $ISSUE_TYPES;
141 require_once(dirname(__FILE__) . "/../library/acl.inc");
142 require_once(dirname(__FILE__) . "/../library/lists.inc");
144 $d = new Document($doc_id);
145 $n = new Note();
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:
155 $delete_string = '';
156 if (acl_check('admin', 'super')) {
157 $delete_string = "<a href='' onclick='return deleteme(" . $d->get_id() .
158 ")'><font color='red'>(Delete this document)</font></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'>-- 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" => "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) {
202 $d = new Document($document_id);
203 $url = $d->get_url();
205 //strip url of protocol handler
206 $url = preg_replace("|^(.*)://|","",$url);
208 //change full path to current webroot. this is for documents that may have
209 //been moved from a different filesystem and the full path in the database
210 //is not current.
211 $temp_url = $GLOBALS["fileroot"].'/documents/'.$_SESSION["pid"].'/'.basename($url);
212 if (file_exists($temp_url)) {
213 $url = $temp_url;
215 if (!file_exists($url)) {
216 echo "The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it. $url";
218 else {
219 header("Pragma: public");
220 header("Expires: 0");
221 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
222 header("Content-Disposition: " . ($as_file ? "attachment" : "inline") . "; filename=\"" . basename($d->get_url()) . "\"");
223 header("Content-Type: " . $d->get_mimetype());
224 header("Content-Length: " . $d->get_size());
225 $f = fopen($url,"r");
226 fpassthru($f);
227 exit;
231 function queue_action($patient_id="") {
232 $messages = $this->_tpl_vars['messages'];
233 $queue_files = array();
235 //see if the repository exists and it is a directory else error
236 if (file_exists($this->_config['repository']) && is_dir($this->_config['repository'])) {
237 $dir = opendir($this->_config['repository']);
238 //read each entry in the directory
239 while (($file = readdir($dir)) !== false) {
240 //concat the filename and path
241 $file = $this->_config['repository'] .$file;
242 $file_info = array();
243 //if the filename is a file get its info and put into a tmp array
244 if (is_file($file) && strpos(basename($file),".") !== 0) {
245 $file_info['filename'] = basename($file);
246 $file_info['mtime'] = date("m/d/Y H:i:s",filemtime($file));
247 $d = Document::document_factory_url("file://" . $file);
248 preg_match("/^([0-9]+)_/",basename($file),$patient_match);
249 $file_info['patient_id'] = $patient_match[1];
250 $file_info['document_id'] = $d->get_id();
251 $file_info['web_path'] = $this->_link("retrieve",true) . "document_id=" . $d->get_id() . "&";
253 //merge the tmp array into the larger array
254 $queue_files[] = $file_info;
257 closedir($dir);
259 else {
260 $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";
264 $this->assign("queue_files",$queue_files);
265 $this->_last_node = null;
267 $menu = new HTML_TreeMenu();
269 //pass an empty array because we don't want the documents for each category showing up in this list box
270 $rnode = $this->_array_recurse($this->tree->tree,array());
271 $menu->addItem($rnode);
272 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array());
274 $this->assign("tree_html_listbox",$treeMenu_listbox->toHTML());
276 $this->assign("messages",nl2br($messages));
277 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_queue.html");
280 function queue_action_process() {
281 if ($_POST['process'] != "true")
282 return;
284 $messages = $this->_tpl_vars['messages'];
286 //build a category tree so we can have a list of category ids that are valid
287 $ct = new CategoryTree(1);
288 $categories = $ct->_id_name;
290 //see if there were and posted files and assign them
291 $files = null;
292 is_array($_POST['files']) ? $files = $_POST['files']: $files = array();
294 //loop through posted files
295 foreach($files as $doc_id=> $file) {
296 //only operate on files checked as active
297 if (!$file['active']) continue;
299 //run basic validation checks
300 if (!is_numeric($file['patient_id']) || !is_numeric($file['category_id']) || !is_numeric($doc_id)) {
301 $messages .= "Error processing file '" . $file['name'] ."' the patient id must be a number and the category must exist.\n";
302 continue;
305 //validate that the pod exists
306 $d = new Document($doc_id);
307 $sql = "SELECT pid from patient_data where pubpid = '" . $file['patient_id'] . "'";
308 $result = $d->_db->Execute($sql);
310 if (!$result || $result->EOF) {
311 //patient id does not exist
312 $messages .= "Error processing file '" . $file['name'] ." the specified patient id '" . $file['patient_id'] . "' could not be found.\n";
313 continue;
316 //validate that the category id exists
317 if (!isset($categories[$file['category_id']])) {
318 $messages .= "Error processing file '" . $file['name'] . " the specified category with id '" . $file['category_id'] . "' could not be found.\n";
319 continue;
322 //now do the work of moving the file
323 $new_path = $this->_config['repository'] . $file['patient_id'] ."/";
325 //see if the patient dir exists in the repository and create if not
326 if (!file_exists($new_path)) {
327 if (!mkdir($new_path,0700)) {
328 $messages .= "The system was unable to create the directory for this upload, '" . $this->file_path . "'.\n";
329 continue;
333 //fname is the name of the file after it is moved
334 $fname = $file['name'];
336 //see if patient autonumbering is used in this filename, if so strip out the autonumber part
337 preg_match("/^([0-9]+)_/",basename($fname),$patient_match);
338 if ($patient_match[1] == $file['patient_id']) {
339 $fname = preg_replace("/^([0-9]+)_/","",$fname);
342 //filenames should not have funny chars
343 $fname = preg_replace("/[^a-zA-Z0-9_.]/","_",$fname);
345 //see if there is an existing file with the same name and rename as necessary
346 if (file_exists($new_path.$file['name'])) {
347 $messages .= "File with same name already exists at location: " . $new_path . "\n";
348 $fname = basename($this->_rename_file($new_path.$file['name']));
349 $messages .= "Current file name was changed to " . $fname ."\n";
352 //now move the file
353 if (rename($this->_config['repository'].$file['name'],$new_path.$fname)) {
354 $messages .= "File " . $fname . " moved to patient id '" . $file['patient_id'] ."' and category '" . $categories[$file['category_id']]['name'] . "' successfully.\n";
355 $d->url = "file://" .$new_path.$fname;
356 $d->set_foreign_id($file['patient_id']);
357 $d->set_mimetype($mimetype);
358 $d->persist();
359 $d->populate();
361 if (is_numeric($d->get_id()) && is_numeric($file['category_id'])) {
362 $sql = "REPLACE INTO categories_to_documents set category_id = '" . $file['category_id'] . "', document_id = '" . $d->get_id() . "'";
363 $d->_db->Execute($sql);
366 else {
367 $error .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
370 $this->assign("messages",$messages);
371 $_POST['process'] = "";
374 function move_action_process($patient_id="",$document_id) {
375 if ($_POST['process'] != "true")
376 return;
378 $new_category_id = $_POST['new_category_id'];
379 $new_patient_id = $_POST['new_patient_id'];
381 //move to new category
382 if (is_numeric($new_category_id) && is_numeric($document_id)) {
383 $sql = "UPDATE categories_to_documents set category_id = '" . $new_category_id . "' where document_id = '" . $document_id ."'";
384 $messages .= "Document moved to new category '" . $this->tree->_id_name[$new_category_id]['name'] . "' successfully.\n";
385 //echo $sql;
386 $this->tree->_db->Execute($sql);
389 //move to new patient
390 if (is_numeric($new_patient_id) && is_numeric($document_id)) {
391 $d = new Document($document_id);
392 // $sql = "SELECT pid from patient_data where pubpid = '" . $new_patient_id . "'";
393 $sql = "SELECT pid from patient_data where pid = '" . $new_patient_id . "'";
394 $result = $d->_db->Execute($sql);
396 if (!$result || $result->EOF) {
397 //patient id does not exist
398 $messages .= "Document could not be moved to patient id '" . $new_patient_id . "' because that id does not exist.\n";
400 else {
401 //set the new patient
402 $d->set_foreign_id($new_patient_id);
403 $d->persist();
404 $this->_state = false;
405 $messages .= "Document moved to patient id '" . $new_patient_id . "' successfully.\n";
406 $this->assign("messages",$messages);
407 return $this->list_action($patient_id);
410 //in this case return the document to the queue instead of moving it
411 elseif (strtolower($new_patient_id) == "q" && is_numeric($document_id)) {
412 $d = new Document($document_id);
413 $new_path = $this->_config['repository'];
414 $fname = $d->get_url_file();
416 //see if there is an existing file with the same name and rename as necessary
417 if (file_exists($new_path.$d->get_url_file())) {
418 $messages .= "File with same name already exists in the queue.\n";
419 $fname = basename($this->_rename_file($new_path.$d->get_url_file()));
420 $messages .= "Current file name was changed to " . $fname ."\n";
423 //now move the file
424 if (rename($d->get_url_filepath(),$new_path.$fname)) {
425 $d->url = "file://" .$new_path.$fname;
426 $d->set_foreign_id("");
427 $d->persist();
428 $d->persist();
429 $d->populate();
431 $sql = "DELETE FROM categories_to_documents where document_id =" . $d->_db->qstr($document_id);
432 $d->_db->Execute($sql);
433 $messages .= "Document returned to queue successfully.\n";
436 else {
437 $messages .= "The file could not be succesfully stored, this error is usually related to permissions problems on the storage system.\n";
440 $this->_state = false;
441 $this->assign("messages",$messages);
442 return $this->list_action($patient_id);
445 $this->_state = false;
446 $this->assign("messages",$messages);
447 return $this->view_action($patient_id,$document_id);
450 // Added by Rod for metadata update.
452 function update_action_process($patient_id="", $document_id) {
453 if ($_POST['process'] != "true") {
454 die("process is '" . $_POST['process'] . "', expected 'true'");
455 return;
458 $docdate = $_POST['docdate'];
459 $issue_id = $_POST['issue_id'];
461 if (is_numeric($document_id)) {
462 if (preg_match('/^\d\d\d\d-\d+-\d+$/', $docdate)) {
463 $docdate = "'$docdate'";
464 } else {
465 $docdate = "NULL";
467 if (!is_numeric($issue_id)) {
468 $issue_id = 0;
470 $sql = "UPDATE documents SET docdate = $docdate, " .
471 "list_id = '$issue_id' " .
472 "WHERE id = '$document_id'";
473 $this->tree->_db->Execute($sql);
474 $messages .= "Document date and issue updated successfully\n";
477 $this->_state = false;
478 $this->assign("messages", $messages);
479 return $this->view_action($patient_id, $document_id);
482 function list_action($patient_id = "") {
483 $this->_last_node = null;
484 $categories_list = $this->tree->_get_categories_array($patient_id);
485 //print_r($categories_list);
487 $menu = new HTML_TreeMenu();
488 $rnode = $this->_array_recurse($this->tree->tree,$categories_list);
489 $menu->addItem($rnode);
490 $treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => 'images', 'defaultClass' => 'treeMenuDefault'));
491 $treeMenu_listbox = &new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));
493 $this->assign("tree_html",$treeMenu->toHTML());
495 return $this->fetch($GLOBALS['template_dir'] . "documents/" . $this->template_mod . "_list.html");
499 * 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
500 * the file already has a numeric it increments that.
501 * It supports numeric endings upto 1000, after which it uses an md5sum on now() instead. This is because some files end in
502 * dates and we don't want to increment those.
504 function _rename_file($fname) {
505 $file = basename($fname);
506 $fparts = split("\.",$fname);
507 $path = dirname($fname);
508 if (is_numeric($fparts[count($fparts) -1]) && $fparts[count($fparts) -1] < 1000) {
509 $new_name = "";
510 for($i=0;$i<count($fparts);$i++) {
511 if ($i == (count($fparts) -1)) {
512 $new_name .= ($fparts[$i] +1);
514 else {
515 $new_name .= $fparts[$i] . ".";
518 $fname = $new_name;
520 elseif (is_numeric($fparts[count($fparts)])) {
521 $fname = $fname . "." . md5sum(now());
523 else {
524 $fname = $fname . ".1";
526 if (file_exists($fname)) {
527 return $this->_rename_file($fname);
529 else {
530 return($fname);
534 function &_array_recurse($array,$categories = array()) {
535 if (!is_array($array)) {
536 $array = array();
538 $node = &$this->_last_node;
539 $current_node = &$node;
540 $expandedIcon = 'folder-expanded.gif';
541 foreach($array as $id => $ar) {
542 $icon = 'folder.gif';
543 if (is_array($ar) || !empty($id)) {
544 if ($node == null) {
545 //echo "r:" . $this->tree->get_node_name($id) . "<br>";
546 $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));
547 $this->_last_node = &$rnode;
548 $node = &$rnode;
549 $current_node =&$rnode;
551 else {
552 //echo "p:" . $this->tree->get_node_name($id) . "<br>";
553 $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)));
554 $current_node =&$this->_last_node;
557 $this->_array_recurse($ar,$categories);
559 else {
560 if ($id === 0 && !empty($ar)) {
561 $info = $this->tree->get_node_info($id);
562 //echo "b:" . $this->tree->get_node_name($id) . "<br>";
563 $current_node = &$node->addItem(new HTML_TreeNode(array("id" => $id, 'text' => $info['value'], 'link' => $this->_link("upload") . "parent_id=" . $id . "&", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));
565 else {
566 //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
567 //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO
568 if ($id !== 0 && is_object($node)) {
569 //echo "n:" . $this->tree->get_node_name($id) . "<br>";
570 $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)));
576 // If there are documents in this document category, then add their
577 // attributes to the current node.
578 $icon = "file3.png";
579 if (is_array($categories[$id])) {
580 foreach ($categories[$id] as $doc) {
581 $current_node->addItem(new HTML_TreeNode(array(
582 'text' => $doc['docdate'] . ' ' . basename($doc['url']),
583 'link' => $this->_link("view") . "doc_id=" . $doc['document_id'] . "&",
584 'icon' => $icon,
585 'expandedIcon' => $expandedIcon
586 )));
591 return $node;
595 //place to hold optional code
596 //$first_node = array_keys($t->tree);
597 //$first_node = $first_node[0];
598 //$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')"));
600 //$this->_last_node = &$node1;