Code

Added move / create check
[gosa.git] / gosa-plugins / goto / admin / applications / class_applicationGeneric.inc
1 <?php
2 class application extends plugin
3 {
4   /* application attributes */
5   var $cn= "";
6   var $description= "";
7   var $base= "";
8   var $gosaApplicationExecute= "";
9   var $gosaApplicationName= "";
10   var $gosaApplicationFlags= "";
11   var $gosaApplicationIcon= "";
12   var $gotoLogonScript  ="";
13   var $iconData;
14   var $view_logged = FALSE;
16   /* Headpage attributes */
17   var $last_sorting= "invalid";
18   var $applications= array();
20   var $orig_base = "";
21   var $orig_cn = "";
23   /* attribute list for save action */
24   var $attributes= array("cn", "description", "gosaApplicationExecute", "gosaApplicationName","gosaApplicationIcon",
25       "gosaApplicationFlags","gotoLogonScript");
27   var $objectclasses= array("top", "gosaApplication");
29   function application (&$config, $dn= NULL, $parent= NULL)
30   {
31     plugin::plugin ($config, $dn, $parent);
33     /* Load icon */
34     $ldap= $config->get_ldap_link();
35     if ($dn != 'new'){
36       $this->iconData= $ldap->get_attribute($dn, "gosaApplicationIcon");
37       $this->saved_attributes['gosaApplicationIcon'] = $this->iconData;
38     }
39     if ($this->iconData == ""){
40       $this->set_picture("");
41     }
42     session::set('binary',$this->iconData);
43     session::set('binarytype',"image/jpeg");
44     $this->gosaApplicationIcon= $this->iconData;
46     /* This is always an account */
47     $this->is_account= TRUE;
49     if ($this->dn == "new"){
50       if(session::is_set('CurrentMainBase')){
51         $this->base = session::get('CurrentMainBase');
52       }else{
53         $ui= get_userinfo();
54         $this->base= dn2base($ui->dn);
55       }
56     } else {
57       $this->base= preg_replace ("/^[^,]+,".get_ou('applicationou')."/", "", $this->dn);
58     }
60     $this->orig_cn = $this->cn;
61     $this->orig_base = $this->base;
62   }
65   function generateTemplate()
66   {
67     $str= "# This code is part of GOsa (https://gosa.gonicus.de)\n#\n";
69     $values = array();
70     $names      = array();
71     if($this->parent->by_object['applicationParameters']->is_account){
72       $names = $this->parent->by_object['applicationParameters']->option_name;
73       $values = $this->parent->by_object['applicationParameters']->option_value;
74     }
76     if (count($names)){
77       $str .="# This plugin handles these environment variables:\n";
78     } else {
79       $str .="# This plugin handles no environment variables.\n";
80     }
82     foreach($names as $index => $name){
84       // Fix length
85       for($i = strlen($name) ; $i < 30 ; $i++){
86         $name= $name." ";
87       }
88       if((isset($values[$index]))&&(!empty($values[$index]))){
89         $str.= "# ".$name."\t(e.g. '".$values[$index]."')\n";
90       }else{
91         $str.= "# ".$name."\t("._("no example").")\n";
92       }
93     }
94     $str .= "#\n".
95       "# Don't remove the following tag, it is used for header update.\n".
96       "### END HEADER ###";
98     return($str);
99   }
101   function execute()
102   {
103     /* Call parent execute */
104     plugin::execute();
106     /* Log view */
107     if($this->is_account && !$this->view_logged){
108       $this->view_logged = TRUE;
109       new log("view","application/".get_class($this),$this->dn);
110     }
112     $smarty= get_smarty();
114     $tmp = $this->plInfo();
115     foreach($tmp['plProvidedAcls'] as $name => $translation){
116       $smarty->assign($name."ACL",$this->getacl($name));
117     }
118  
119     /* Do we represent a valid group? */
120     if (!$this->is_account && $this->parent === NULL){
121       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
122         msgPool::noValidExtension(_("application"))."</b>";
123       return ($display);
124     }
126     /* Download requested */
127     foreach($_POST as $name => $value){
128       if(preg_match("/^downloadScript/",$name)){
129         session::set('binary',$this->gotoLogonScript);
130         session::set('binarytype',"octet-stream");
131         session::set('binaryfile',$this->cn.".gosaApplication");
132         header("location: getbin.php ");
133         exit();
134       }
135     }
137     /* Reassign picture data, sometimes its corrupt cause we started a download of application scripts */
138     session::set('binary',$this->iconData);
139     session::set('binarytype',"image/jpeg");
140     
141     $smarty->assign("rand", rand(0, 10000));
142     $head = $this->generateTemplate();
143     $this->gotoLogonScript= $this->generateTemplate().preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
145     if((isset($_POST['upLoad']))&&(isset($_FILES['ScriptFile']))){
146       $str = file_get_contents($_FILES['ScriptFile']['tmp_name']);
147       $this->gotoLogonScript = $str;
148     }
150     /* Fill templating stuff */
151     $smarty->assign("cn", $this->cn);
152     if(!$this->is_release()){
153       $smarty->assign("bases", $this->get_allowed_bases());
154     }else{
155       $smarty->assign("bases", array());
156     }
157     if ($this->dn == "new"){
158       $smarty->assign("selectmode", "");
159       $smarty->assign("namemode", "");
160     } else {
161       $smarty->assign("namemode", "readonly");
162       $smarty->assign("selectmode", "disabled");
163     }
164     
165     /* Base select dialog */
166     $once = true;
167     foreach($_POST as $name => $value){
168       if(preg_match("/^chooseBase/",$name) && $once){
169         $once = false;
170         $this->dialog = new baseSelectDialog($this->config,$this,$this->get_allowed_bases());
171         $this->dialog->setCurrentBase($this->base);
172       }
173     }
175     /* Dialog handling */
176     if(is_object($this->dialog)){
177       /* Must be called before save_object */
178       $this->dialog->save_object();
180       if($this->dialog->isClosed()){
181         $this->dialog = false;
182       }elseif($this->dialog->isSelected()){
183  
184         /* Just allow selection valid bases */ 
185         $tmp = $this->get_allowed_bases();
186         if(isset($tmp[$this->dialog->isSelected()])){
187           $this->base = $this->dialog->isSelected();
188         }
189         $this->dialog= false;
190       }else{
191         return($this->dialog->execute());
192       }
193     }
195     /* Get random number for pictures */
196     srand((double)microtime()*1000000);
197     $smarty->assign("rand", rand(0, 10000));
199     /* Variables */
200     foreach(array("description", "gosaApplicationExecute", "gosaApplicationName","cn") as $val){
201       $smarty->assign($val, $this->$val);
202     }
204     /* Checkboxes */
205     foreach (array("G" => "exec_for_groupmembers", "O" => "overwrite_config",
206           "L" => "place_on_kicker",
207           "D" => "place_on_desktop", "M" => "place_in_startmenu") as $key => $val){
208       if (preg_match("/$key/", $this->gosaApplicationFlags)){
209         $smarty->assign("$val", "checked");
210       } else {
211         $smarty->assign("$val", "");
212       }
213     }
215     $smarty->assign("isReleaseApplikation" ,$this->is_release());
216     $smarty->assign("gotoLogonScript",htmlentities($this->gotoLogonScript, ENT_COMPAT, 'UTF-8'));
217     $smarty->assign("base_select", $this->base);
218     /* Show main page */
219     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
220   }
223   function remove_from_parent()
224   {
225     restore_error_handler();
227     /* Parse release out of object dn */
228     $release = preg_replace("/".get_ou("applicationou").normalizePreg($this->base)."$/","",$this->dn);
229     $release = preg_replace("/^cn=[^,]+,/","",$release);
231     /* Get a list of all groups 
232      */
233     $groups = array();
234     $ldap= $this->config->get_ldap_link();
235     $ldap->cd($this->config->current['BASE']);
236     $ldap->search("(objectClass=posixGroup)",array("dn"));
237     while($attrs = $ldap->fetch()){
238       $groups[$attrs['dn']] = array();
239     }
240     
241     /* Check if there are groups, useing this application 
242      */
243     $found = array();
244     foreach($groups as $group => $data){
245       $ldap->cd($release.$group);
246       $ldap->search("(objectClass=gotoMenuEntry)",array("dn"));
247       while($attrs = $ldap->fetch()){
248         $info = preg_replace("/".normalizePreg($release.$group)."$/","",$attrs['dn']); 
249         if(preg_match("/^cn=".$this->cn."/",$info) && !preg_match("/ou=[^,]+,/",$info)){
250           $found[] = $attrs['dn'];
251         }
252       }
253     }
255     /* Create an error message an skip remove, if 
256         this application is still in use. 
257      */
258     if(count($found)){
259       msg_dialog::display(_("Error"), sprintf(_("Cannot remove application - it is still in use by these objects: %s"), "<br>".msgPool::buildList($found)), ERROR_DIALOG);
260       return(FALSE);
261     }
263     $ldap->rmDir($this->dn);
264     new log("remove","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
265     if (!$ldap->success()){
266       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()), ERROR_DIALOG);
267     }
269     /* Optionally execute a command after we're done */
270     $this->handle_post_events("remove");
272     /* Delete references to object groups */
273     $ldap->cd ($this->config->current['BASE']);
274     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
275     while ($ldap->fetch()){
276       $og= new ogroup($this->config, $ldap->getDN());
277       unset($og->member[$this->dn]);
278       $og->save ();
279       if (!$ldap->success()){
280         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
281       }
282     }
283   }
286   /* Save data to object */
287   function save_object()
288   {
289     if (isset($_POST['cn'])){
291       /* Create a base backup and reset the
292          base directly after calling plugin::save_object();
293          Base will be set seperatly a few lines below */
294       $base_tmp = $this->base;
295       plugin::save_object();
296       $this->base = $base_tmp;
298       /* Save attributes */
299       parent::save_object();
301       /* Save application flags */
302       $flag= "";
303       if (isset($_POST['exec_for_groupmembers']) && $_POST['exec_for_groupmembers'] == 1){
304         $flag.= "G";
305       }
306       if (isset($_POST['place_on_desktop']) && $_POST['place_on_desktop'] == 1){
307         $flag.= "D";
308       }
309       if (isset($_POST['place_on_kicker']) && $_POST['place_on_kicker'] == 1){
310         $flag.= "L";
311       }
312       if (isset($_POST['place_in_startmenu']) && $_POST['place_in_startmenu'] == 1){
313         $flag.= "M";
314       }
315       if (isset($_POST['overwrite_config']) && $_POST['overwrite_config'] == 1){
316         $flag.= "O";
317       }
318       if ($this->acl_is_writeable("gosaApplicationFlags")){
319         $this->gosaApplicationFlags= "[$flag]";
320       }
322       /* Remove current picture */
323       if(isset($_POST['remove_picture'])){
324         $this->set_picture("");
325       }
327       /* Check for picture upload */
328       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
330         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
331           msg_dialog::display(_("Error"), msgPool::incorrectUpload(), ERROR_DIALOG);
332         }
334         if (!function_exists("imagick_blob2image")){
335           /* Get temporary file name for conversation */
336           $fname = tempnam (TEMP_DIR, "GOsa");
338           /* Open file and write out photoData */
339           $fp = fopen ($fname, "w");
340           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
341           fclose ($fp);
343           /* Build conversation query. Filename is generated automatically, so
344              we do not need any special security checks. Exec command and save
345              output. For PHP safe mode, you'll need a configuration which respects
346              image magick as executable... */
347           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
348           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
350           /* Read data written by convert */
351           $output= "";
352           $sh= popen($query, 'r');
353           while (!feof($sh)){
354             $output.= fread($sh, 4096);
355           }
356           pclose($sh);
358           unlink($fname);       
359         } else {
361           /* Load the new uploaded Photo */
362           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
363             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("no read permission")), ERROR_DIALOG);
364           }
366           /* Resizing image to 147x200 and blur */
367           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
368             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot resize image")), ERROR_DIALOG);
369           }
371           /* Converting image to JPEG */
372           if(!imagick_convert($handle,"PNG")) {
373             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot convert image")), ERROR_DIALOG);
374           }
376           if(!imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
377             msg_dialog::display(_("Error"), msgPool::incorrectUpload(sprintf(_("cannot save image to '%s'"), $_FILES['picture_file']['tmp_name'])), ERROR_DIALOG);
378           }
380           imagick_free($handle);
381         }
383         /* Activate new picture */
384         $this->set_picture($_FILES['picture_file']['tmp_name']);
385       } 
387       if(!$this->is_release()){
388         $tmp = $this->get_allowed_bases();
389         if(isset($_POST['base'])){
390           if(isset($tmp[$_POST['base']])){
391             $this->base= $_POST['base'];
392           }
393         }
394       }
395     }
396   }
399   /* Check values */
400   function check()
401   {
402     /* Call common method to give check the hook */
403     $message= plugin::check();
405     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
406       $message[]=msgPool::invalid(_("Execute path"),"","","/some/path");
407     }
409     /* Permissions for that base? */
410     if ($this->base != ""){
411       $new_dn= "cn=".$this->cn.",".get_ou('applicationou').$this->base;
412     } else {
413       $new_dn= $this->dn;
414     }
417     if($this->dn == "new"){
418       $this->set_acl_base($this->base);
419     }
421     /* All required fields are set? */
422     if ($this->cn == ""){
423       $message[]= msgPool::required(_("Name"));
424     }
426     if(preg_match("/[^a-z0-9]/",$this->cn))     {
427       $message[]=msgPool::invalid(_("Name"),$this->cn,"/^[a-z0-9]*$/");
428     }
430     if ($this->gosaApplicationExecute == ""){
431       $message[]= msgPool::required(_("Execute"));
432     }
434     /* Check for existing application */
435     $ldap= $this->config->get_ldap_link();
436     $ldap->cd($this->config->current["BASE"]);
438     $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
440     if($this->is_release()){
441       $base = $this->parent->parent->app_release;
442     }else{
443       $base = get_ou('applicationou').$this->base;
444     }
446     $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$base,array("cn"));
447     if($ldap->count()){
448       $attrs = $ldap->fetch();
449       if($this->dn != $attrs['dn']) {
450         $message[]= msgPool::duplicated("cn");
451       }
452     }
454     /* Check if we are allowed to create or move this object 
455      */
456     if($this->dn == "new" && !$this->acl_is_createable($this->base)){
457       $message[] = msgPool::permCreate();
458     }elseif($this->cn != $this->orig_cn || $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
459       $message[] = msgPool::permMove();
460     }
462     return $message;
463   }
466   /* Save to LDAP */
467   function save()
468   {
469     /* Get application script without header part, to check if we must save the script itself */
470     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
472     plugin::save();
473     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
475     /* Write back to ldap */
476     $ldap= $this->config->get_ldap_link();
477     $ldap->cat($this->dn, array('dn'));
479     $a= $ldap->fetch();
480     if (count($a)){
482       /* Remove gotoLogonScript if it is empty */
483       if(empty($script))    {
484         $this->attrs['gotoLogonScript'] = array();
485       }
487       $ldap->cd($this->dn);
488       $this->cleanup();
489       $ldap->modify ($this->attrs); 
490       $this->handle_post_events("modify");
491       new log("modify","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
492     } else {
493       
494       /* Remove gotoLogonScript if it is empty */
495       if(empty($script))    {
496         unset($this->attrs['gotoLogonScript']);
497       }
499       $ldap->cd($this->config->current['BASE']);
500       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
501       $ldap->cd($this->dn);
502       $ldap->add($this->attrs);
503       new log("create","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
504       $this->handle_post_events("add");
505     }
506     if (!$ldap->success()){
507       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
508     }
509   }
511   
512   function is_release()
513   {
514     if(isset($this->parent->parent)){
515       return($this->parent->parent->IsReleaseManagementActivated());
516     }else{
517       /* Check if we should enable the release selection */
518       $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
519       if(!empty($tmp)){
520         return(true);
521       }
522     }
523     return(FALSE);
524   }
527   function set_picture($filename)
528   {
529     if (!is_file($filename)){
530       $filename= "./images/default_icon.png";
531       $this->gosaApplicationIcon= "*removed*";
532     }
534     if (file_exists($filename)){
535       $fd = fopen ($filename, "rb");
536       $this->iconData= fread ($fd, filesize ($filename));
537       session::set('binary',$this->iconData);
538       session::set('binarytype',"image/jpeg");
539       $this->gosaApplicationIcon= $this->iconData;
541       fclose ($fd);
542     }
543   }
545   function getCopyDialog()
546   {
547     $vars = array("cn");
549     $str ="<h2>"._("Application settings")."</h2>
550       <table>
551       <tr>
552       <td>".
553       _("Application name"). 
554       "</td>  
555       <td>
556       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
557       value='".$this->cn."' 
558       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
559       </td>
560       </tr>
561       </table>";
562     $ret = array();
563     $ret['status'] = "";
564     $ret['string'] = $str;
565     return($ret);
566   }
568   function saveCopyDialog()
569   {
570     if(isset($_POST['cn'])){
571       $this->cn = $_POST['cn'];
572     }
573   }
576   function PrepareForCopyPaste($source)
577   {
578     plugin::PrepareForCopyPaste($source);
579     $source_o = new application($this->config,$source['dn']);
580     $this->gosaApplicationIcon = $source_o->gosaApplicationIcon;     
581   }
584   /* Return plugin informations for acl handling
585       #FIXME FAIscript seams to ununsed within this class... */
586   static function plInfo()
587   {
588     return (array(
589           "plShortName"   => _("Generic"),
590           "plDescription" => _("Application generic"),
591           "plSelfModify"  => FALSE,
592           "plDepends"     => array(),
593           "plPriority"    => 0,
594           "plSection"     => array("administration"),
595           "plCategory"    => array("application" => array("description"  => _("Application"),
596                                                           "objectClass"  => "gosaApplication")),
597           "plProvidedAcls"=> array(
598             "cn"                => _("Name"),
599             "base"              => _("Base"),
600             "description"       => _("Description"),
601             "gosaApplicationExecute"  => _("Execute"),
602             "gosaApplicationName"     => _("Name"),
603             "gosaApplicationIcon"     => _("Icon"),
604             "gosaApplicationFlags"    => _("Flag"),
605             "gotoLogonScript"         => _("Script content"),
607             "exec_for_groupmembers" => _("Only executable for members"),              // G
608             "place_on_desktop"      => _("Place icon on members desktop"),            // D
609             "place_on_kicker"       => _("Place entry in members launch bar"),        // L
610             "place_in_startmenu"    => _("Place entry in members startmenu"),         // M
611             "overwrite_config"      => _("Replace user configuration on startup"))  // O
612             ));
613   }
615 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
616 ?>