Code

Added check to avoid multiple uploads of the same file
[gosa.git] / plugins / admin / systems / class_glpiAttachmentPool.inc
1 <?php
3 class glpiAttachmentPool extends plugin
4 {
5   /* CLI vars */
6   var $cli_summary= "Manage server basic objects";
7   var $cli_description= "Some longer text\nfor help";
8   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
10   /* attribute list for save action */
11   var $ignore_account = TRUE;
12   var $attributes     = array("name","comment","mime","filename","date_mod");
13   var $objectclasses  = array("whatever");
15   var $parent;
16   var $edit = false;
17   var $entry = false;
18   var $date_mod ="";
19   var $name     ="";
20   var $comment  ="";
21   var $mime     ="";
22   var $filename ="";  
24   var $Selected = array();
26   var $delAttach= "";
28   function glpiAttachmentPool ($config, $dn= NULL,$used=NULL)
29   {
30     plugin::plugin ($config, $dn);
31     if(!isset($_SESSION['GlpiAttachmentFilter'])){
32       $_SESSION['GlpiAttachmentFilter'] = array("filter"=>"*");
33     }
35     /* Assign used attributes */
36     if($used != NULL){
37       $this->Selected = $used;
38     }
39   }
41   function execute()
42   {
43     plugin::execute();
44     $attach     = $this->parent->handle->getAttachments();
45     /* Fill templating stuff */
46     $smarty     = get_smarty();
47     $display    = "";
48     $only_once  = true; 
50     /* walk through all posted objects */
51     foreach($_POST as $name => $value){
53       /* Open dialog to create a new entry */
54       if(preg_match("/new_attach/",$name)){
55         $this->edit = true;
56         $this->entry=array();
58         /* Set default values */
59         foreach($this->attributes as $attr) {
60           $this->$attr = "";
61           $this->entry[$attr]="";
62         }
63       }
64   
65       /* Remove attach*/ 
66       if((preg_match("/^delAttach_/",$name))&&($only_once)){
67         $only_once = false;
68         $str = preg_replace("/^delAttach_/","",$name);
69         $str = base64_decode(preg_replace("/_.*$/","",$str));
71         /* remove attach from db */
72         $this->delAttach = $str;
73         $smarty->assign("warning", sprintf(_("You're about to delete the glpi attachment component '%s'."), $attach[$str]['name']));
74         return($smarty->fetch(get_template_path('remove_glpi.tpl', TRUE)));
75       }
76  
77       /* Start editing entry */ 
78       if((preg_match("/^editAttach_/",$name))&&($only_once)){
79         $only_once = false;
80         $str = preg_replace("/^editAttach_/","",$name);
81         $str = base64_decode(preg_replace("/_.*$/","",$str));
82         
83         /* Check if we have an attachment with given ID */ 
84         foreach($attach as $att ){
85           if($att['ID'] == $str ){
87             /* Entry was found, show dialog */          
88             $this->edit = true;
89             $this->entry  = $att;       
91             foreach($att as $name => $value){
92               $this->$name = $value;
93             } 
94           } 
95         }
96       }
97     }
99     if((isset($_POST['delete_glpi_confirm']))&&(isset($attach[$this->delAttach]))){
100       if($this->parent->handle->is_attachmentUsed($this->delAttach)){
101         $tmp = $this->parent->handle->is_attachmentUsed($this->delAttach);
102         
103         $names = "";
104         foreach($tmp as $name){
105           $names .= ", ".$name;
106         }
107         $names = preg_replace("/^, /","",$names);
108         $names = trim($names);
109         if(count($tmp) == 3){
110           $names .= " ...";
111         }
112         print_red(sprintf(_("You can't delete this attachment, it is still in use by these system(s) '%s'"),$names));
114       }else{
115         $this->parent->handle->deleteAttachment($this->delAttach);
116         $attach     = $this->parent->handle->getAttachments();
117       }
118     }
120     /* Someone tries to upload a file */
121     if(($this->edit == true)&&(isset($_POST['upload']))){
122       if(!isset($_FILES['filename'])){
123         print_red(_("There is no valid file uploaded."));
124       }else{
125         $FILE = $_FILES['filename'];  
126         if(!isset($FILE['name'])){
127           print_red(_("There is no valid file uploaded."));
128         }else{
129           if($FILE['error']!=0) {
130             print_red(_("Upload wasn't successfull."));
131           }else{
132             if(!is_dir("/etc/gosa/glpi/")){
133               print_red(_("Missing directory '/etc/gosa/glpi/' to store glpi uploads."));
134             }else{
135               $filen = "/etc/gosa/glpi/".$FILE['name'];
136               if(file_exists($filen)){
137                 print_red(_("There is already a file with the same name uploaded."));
138               }else{
139                 $fh = fopen($filen,"w");
140                 if(!$fh){
141                   print_red(sprintf(_("Can't create file '%s'."),$filen));
142                 }else{
143                   $str = file_get_contents($FILE['tmp_name']);
144                   fwrite($fh,$str,strlen($str));
145                   fclose($fh);
146                   $this->mime     = $FILE['type'];   
147                   $this->filename = $FILE['name'];   
148                 }
149               } // File already exists
150             }
151           } // Check if any error occured
152         } // check if valid filename was uploaded
153       } // ende check if file was uploaded 
154     }// upload post
156     /* save attachment*/
157     if(($this->edit == true)&&(isset($_POST['SaveAttachment']))){
158       if(count($this->check())==0){
159         $this->date_mod = date("Y-m-d H:i:s");
160         $this->save_entry();
161         $this->edit= false;
162         $this->entry = array();
163         $attach = $this->parent->handle->getAttachments();
164       }else{
165         foreach($this->check() as $msg){
166           print_red($msg);
167         }
168       }
169     }
171     /* Abort editing/adding  attachment*/
172     if(($this->edit == true)&&(isset($_POST['CancelAttachment']))){
173       $this->edit  = false;
174       $this->entry = array();
175     }
177     /* If edit == true, we have to show a dialog to edit or add an attach 
178      */
179     if($this->edit == true){
180       foreach($this->attributes as $attr){
181         $smarty->assign($attr,htmlentities(utf8_decode($this->$attr)));
182       }
183       if(!empty($this->filename)){
184         if(is_readable("/etc/gosa/glpi/".$this->filename)){
185           $status =_("File is available.");
186         }else{
187           $status =_("File is not readable, possibly the file is missing.");
188         }
189       }else{
190         $status = _("Currently no file uploaded.");
191       }
192       $smarty->assign("status",$status); 
193       return($smarty->fetch(get_template_path('glpiAttachmentEdit.tpl', TRUE)));
194     }
196     /* Create list with checkboxes to select / deselect some attachents */
197     $divlist = new divlist("Attachment");  
198     $divlist->SetHeader(array(
199           array("string" => "&nbsp;", "attach" => "style='text-align:center;width:20px;'"),
200           array("string" => _("Name")),
201           array("string" => _("Mime"),"attach"=>"style='width:200px;'"),
202           array("string" => _("Actions"), "attach" => "style='width:60px;border-right:0px;text-align:right;'" )));
204     $divlist->SetSummary(_("This table displays all available attachments."));
205     $divlist->SetEntriesPerPage(0);
207     $editdel = "<input type='image' name='editAttach_%s' src='images/edit.png'>";
208     $editdel.= "<input type='image' name='delAttach_%s'  src='images/edittrash.png'>";
210     /* Add all given attachments to divlist 
211      */ 
212     foreach($attach as $entry){
214       /* Create display name*/
215       if((empty($entry['name']))||(empty($entry['comment']))){
217         /* In glpi it is possible to add entries without name 
218            so i've added this block 
219          */ 
220         if(empty($entry['name'])){
221           $str1 = "<i>"._("empty")."</i>";
222         }else{ 
223           $str1 = $entry['name'];
224         }
226         if(!empty($entry['comment'])){
227           $str1.= " [".$entry['comment']."]";
228         }
229       }else{
230         /* Both attributes given */
231         $str1 = $entry['name']." [".$entry['comment']."]";
232       }
234       $edit = str_replace("%s",base64_encode($entry['ID']),$editdel);
235       $str2 = $entry['mime']."&nbsp;";      
237       $chkbox = "<input type='hidden' name='wasOnPage_%s'>".
238         "<input type='checkbox' name='useMe_%s' value='%s' %CHECKED%>";
240       if(in_array($entry['ID'],$this->Selected)){
241         $chkbox = preg_replace("/%CHECKED%/"," checked ",$chkbox);
242       }else {
243         $chkbox = preg_replace("/%CHECKED%/"," ",$chkbox);
244       }
245       $chkbox = preg_replace("/%s/",$entry['ID'],$chkbox);
246       $divlist->AddEntry(array(
247             array("string" => $chkbox, 
248               "attach" => "style='text-align:center;width:20px;'"),
249             array("string"=> $str1),
250             array("string"=> $str2,"attach"=>"style='width:200px;'"),
251             array("string"=> $edit ,"attach" => "style='width:60px;border-right:0px;text-align:right;'")
252             ));
254     }
256     $listhead = "<div style='background:#F0F0F9;padding:5px;'>".
257       "   <input class='center' type='image' 
258       src='images/new.png' align='middle' title='"._("Create new attachment")."' 
259       name='new_attach' alt='"._("New Attachment"). "'>&nbsp;".
260       "</div>";
262     $smarty->assign("attachments",      $divlist->DrawList());
263     $smarty->assign("attachmenthead",   $listhead);
264     $smarty->assign("search_image",     get_template_path('images/search.png'));
265     $smarty->assign("searchu_image",    get_template_path('images/search_user.png'));
266     $smarty->assign("tree_image",       get_template_path('images/tree.png'));
267     $smarty->assign("infoimage",        get_template_path('images/info_small.png'));
268     $smarty->assign("launchimage",      get_template_path('images/small_filter.png'));
269     $smarty->assign("apply",            apply_filter());
270     $smarty->assign("alphabet",         generate_alphabet());
271     $smarty->assign("attachment_regex", $_SESSION['GlpiAttachmentFilter']['filter']);
273     $display.= $smarty->fetch(get_template_path('glpiAttachmentPool.tpl', TRUE));
274     return($display);
275   }
277   function save()
278   {
279     return($this->Selected);
280   }
282   /* Adds new or saves edited entries */
283   function save_entry()
284   {
285     if($this->edit){
286       $tmp = array();
287       foreach($this->attributes as $attr){
288         $tmp[$attr] = $this->$attr;
289       } 
290       $id = -1;
291       if(isset($this->entry['ID'])){
292         $id = $this->entry['ID'];
293       }
294       $this->parent->handle->saveAttachments($tmp,$id);
295     }
296   }
298   function save_object()
299   {
300     foreach($this->attributes as $attr){
301       if(isset($_POST[$attr])){
302         $this->$attr = $_POST[$attr];
303       }
304     }
306     /* Checkboxes are only posted, if they are checked
307      * To check if it was deselected, we check if wasOnPage 
308      * was posted with given name, so we can deselect this entry
309      */  
311     foreach($_POST as $name => $value){
312       if(preg_match("/wasOnPage_/",$name)){
313         $id=preg_replace("/wasOnPage_/","",$name);
314         if(isset($_POST["useMe_".$id])){
315           $this->Selected[$id]=$id;
316         }else{
317           if(isset($this->Selected[$id])){
318             unset($this->Selected[$id]);
319           }
320         }
321       }
322     }
323   }
325   /* Simple check */
326   function check()
327   {
328     $message = array();
329     if($this->edit){
330     
331       /* check if given name is already in use */
332       $att = $this->parent->handle->getAttachments();
333       $ok = true;
334       $this->name=trim($this->name);
336       foreach($att as $val){
337         if(!isset($this->entry['ID'])){
338           if($val['name'] == $this->name){
339             $ok = false;
340           }
341         }else{
342           if(($val['name'] == $this->name)&&($this->entry['ID'] != $val['ID'])){
343             $ok = false;
344           }
345         }
346       }
347       if(!$ok){
348         $message[] = _("This name is already in use.");
349       }
350       if(empty($this->name)){
351         $message[] = _("Please specify a valid name for this attachment.");
352       }
353     }
354     return($message);
355   }
357 }// vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
358 ?>