Code

Removed CLI
[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   /* attribute list for save action */
21   var $attributes= array("cn", "description", "gosaApplicationExecute", "gosaApplicationName","gosaApplicationIcon",
22       "gosaApplicationFlags","gotoLogonScript");
23   var $objectclasses= array("top", "gosaApplication");
25   var $isReleaseApplikation = false;
27   function application (&$config, $dn= NULL, $parent= NULL)
28   {
29     plugin::plugin ($config, $dn, $parent);
31     $appfilter = session::get('appfilter')    ;
33     $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
34     if(!empty($tmp)) {
35       if(!preg_match("/^".get_ou('applicationou')."/",$appfilter['release'])){
36         $this->isReleaseApplikation = true;  
37       }
38     }
40     /* Load icon */
41     $ldap= $config->get_ldap_link();
42     if ($dn != 'new'){
43       $this->iconData= $ldap->get_attribute($dn, "gosaApplicationIcon");
44       $this->saved_attributes['gosaApplicationIcon'] = $this->iconData;
45     }
46     if ($this->iconData == ""){
47       $this->set_picture("");
48     }
49     session::set('binary',$this->iconData);
50     session::set('binarytype',"image/jpeg");
51     $this->gosaApplicationIcon= $this->iconData;
53     /* This is always an account */
54     $this->is_account= TRUE;
56     if ($this->dn == "new"){
57       if(session::is_set('CurrentMainBase')){
58         $this->base = session::get('CurrentMainBase');
59       }else{
60         $ui= get_userinfo();
61         $this->base= dn2base($ui->dn);
62       }
63     } else {
65       if($this->isReleaseApplikation){
66         $this->base = preg_replace("/^.*,".get_ou('applicationou')."/","",$this->dn);
67       }else{
68         $this->base= preg_replace ("/^[^,]+,[^,]+,/", "", $this->dn);
69       }
70     }
71   }
74   function generateTemplate()
75   {
76     $str= "# This code is part of GOsa (https://gosa.gonicus.de)\n#\n";
78     $values = array();
79     $names      = array();
80     if($this->parent->by_object['applicationParameters']->is_account){
81       $names = $this->parent->by_object['applicationParameters']->option_name;
82       $values = $this->parent->by_object['applicationParameters']->option_value;
83     }
85     if (count($names)){
86       $str .="# This plugin handles these environment variables:\n";
87     } else {
88       $str .="# This plugin handles no environment variables.\n";
89     }
91     foreach($names as $index => $name){
93       // Fix length
94       for($i = strlen($name) ; $i < 30 ; $i++){
95         $name= $name." ";
96       }
97       if((isset($values[$index]))&&(!empty($values[$index]))){
98         $str.= "# ".$name."\t(e.g. '".$values[$index]."')\n";
99       }else{
100         $str.= "# ".$name."\t("._("no example").")\n";
101       }
102     }
103     $str .= "#\n".
104       "# Don't remove the following tag, it is used for header update.\n".
105       "### END HEADER ###";
107     return($str);
108   }
110   function execute()
111   {
112     /* Call parent execute */
113     plugin::execute();
115     /* Log view */
116     if($this->is_account && !$this->view_logged){
117       $this->view_logged = TRUE;
118       new log("view","application/".get_class($this),$this->dn);
119     }
121     $smarty= get_smarty();
123     $tmp = $this->plInfo();
124     foreach($tmp['plProvidedAcls'] as $name => $translation){
125       $smarty->assign($name."ACL",$this->getacl($name));
126     }
127  
128     /* Do we represent a valid group? */
129     if (!$this->is_account && $this->parent === NULL){
130       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
131         _("This 'dn' is no application.")."</b>";
132       return ($display);
133     }
135     /* Download requested */
136     foreach($_POST as $name => $value){
137       if(preg_match("/^downloadScript/",$name)){
138         session::set('binary',$this->gotoLogonScript);
139         session::set('binarytype',"octet-stream");
140         session::set('binaryfile',$this->cn.".gosaApplication");
141         header("location: getbin.php ");
142         exit();
143       }
144     }
146     /* Reassign picture data, sometimes its corrupt cause we started a download of application scripts */
147     session::set('binary',$this->iconData);
148     session::set('binarytype',"image/jpeg");
149     
150     $smarty->assign("rand", rand(0, 10000));
151     $head = $this->generateTemplate();
152     $this->gotoLogonScript= $this->generateTemplate().preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
154     if((isset($_POST['upLoad']))&&(isset($_FILES['ScriptFile']))){
155       $str = file_get_contents($_FILES['ScriptFile']['tmp_name']);
156       $this->gotoLogonScript = $str;
157     }
159     /* Fill templating stuff */
160     $smarty->assign("cn", $this->cn);
161     $smarty->assign("bases", $this->get_allowed_bases());
162     if ($this->dn == "new"){
163       $smarty->assign("selectmode", "");
164       $smarty->assign("namemode", "");
165     } else {
166       $smarty->assign("namemode", "readonly");
167       $smarty->assign("selectmode", "disabled");
168     }
169     
170     /* Base select dialog */
171     $once = true;
172     foreach($_POST as $name => $value){
173       if(preg_match("/^chooseBase/",$name) && $once){
174         $once = false;
175         $this->dialog = new baseSelectDialog($this->config,$this,$this->get_allowed_bases());
176         $this->dialog->setCurrentBase($this->base);
177       }
178     }
180     /* Dialog handling */
181     if(is_object($this->dialog)){
182       /* Must be called before save_object */
183       $this->dialog->save_object();
185       if($this->dialog->isClosed()){
186         $this->dialog = false;
187       }elseif($this->dialog->isSelected()){
188  
189         /* Just allow selection valid bases */ 
190         $tmp = $this->get_allowed_bases();
191         if(isset($tmp[$this->dialog->isSelected()])){
192           $this->base = $this->dialog->isSelected();
193         }
194         $this->dialog= false;
195       }else{
196         return($this->dialog->execute());
197       }
198     }
200     /* Get random number for pictures */
201     srand((double)microtime()*1000000);
202     $smarty->assign("rand", rand(0, 10000));
204     /* Variables */
205     foreach(array("description", "gosaApplicationExecute", "gosaApplicationName","cn") as $val){
206       $smarty->assign($val, $this->$val);
207     }
209     /* Checkboxes */
210     foreach (array("G" => "exec_for_groupmembers", "O" => "overwrite_config",
211           "L" => "place_on_kicker",
212           "D" => "place_on_desktop", "M" => "place_in_startmenu") as $key => $val){
213       if (preg_match("/$key/", $this->gosaApplicationFlags)){
214         $smarty->assign("$val", "checked");
215       } else {
216         $smarty->assign("$val", "");
217       }
218     }
220     $smarty->assign("isReleaseApplikation" , $this->isReleaseApplikation);
221     $smarty->assign("gotoLogonScript",htmlentities($this->gotoLogonScript, ENT_COMPAT, 'UTF-8'));
222     $smarty->assign("base_select", $this->base);
223     /* Show main page */
224     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
225   }
228   function remove_from_parent()
229   {
230     restore_error_handler();
232     /* Parse release out of object dn */
233     $release = preg_replace("/".get_ou("applicationou").normalizePreg($this->base)."$/","",$this->dn);
234     $release = preg_replace("/^cn=[^,]+,/","",$release);
236     /* Get a list of all groups 
237      */
238     $groups = array();
239     $ldap= $this->config->get_ldap_link();
240     $ldap->cd($this->config->current['BASE']);
241     $ldap->search("(objectClass=posixGroup)",array("dn"));
242     while($attrs = $ldap->fetch()){
243       $groups[$attrs['dn']] = array();
244     }
245     
246     /* Check if there are groups, useing this application 
247      */
248     $found = array();
249     foreach($groups as $group => $data){
250       $ldap->cd($release.$group);
251       $ldap->search("(objectClass=gotoMenuEntry)",array("dn"));
252       while($attrs = $ldap->fetch()){
253         $info = preg_replace("/".normalizePreg($release.$group)."$/","",$attrs['dn']); 
254         if(preg_match("/^cn=".$this->cn."/",$info) && !preg_match("/ou=[^,]+,/",$info)){
255           $found[] = $attrs['dn'];
256         }
257       }
258     }
260     /* Create an error message an skip remove, if 
261         this application is still in use. 
262      */
263     if(count($found)){
264       $objs = "";
265       $cnt = 3;
266       for($i = 0 ; $i < $cnt ; $i++ ){
267         if(isset($found[$i])){
268           $objs .= "&nbsp;".$found[$i].",";
269         }
270       }
271       if(count($found) > $cnt){
272         $objs .= "... ";
273       }
274       $objs = trim($objs,", ");
275       print_red(sprintf(_("Can not remove application, it is still in use by these objects: %s."),$objs));
276       return(FALSE);
277     }
279     $ldap->rmDir($this->dn);
280     new log("remove","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
281     show_ldap_error($ldap->get_error(), sprintf(_("Removing of application with dn '%s' failed."),$this->dn));
283     /* Optionally execute a command after we're done */
284     $this->handle_post_events("remove");
286     /* Delete references to object groups */
287     $ldap->cd ($this->config->current['BASE']);
288     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
289     while ($ldap->fetch()){
290       $og= new ogroup($this->config, $ldap->getDN());
291       unset($og->member[$this->dn]);
292       $og->save ();
293       show_ldap_error($ldap->get_error(), sprintf(_("Removing application from objectgroup '%s' failed"), $og->dn));
294     }
295   }
298   /* Save data to object */
299   function save_object()
300   {
301     if (isset($_POST['cn'])){
303       /* Create a base backup and reset the
304          base directly after calling plugin::save_object();
305          Base will be set seperatly a few lines below */
306       $base_tmp = $this->base;
307       plugin::save_object();
308       $this->base = $base_tmp;
310       /* Save attributes */
311       parent::save_object();
313       /* Save application flags */
314       $flag= "";
315       if (isset($_POST['exec_for_groupmembers']) && $_POST['exec_for_groupmembers'] == 1){
316         $flag.= "G";
317       }
318       if (isset($_POST['place_on_desktop']) && $_POST['place_on_desktop'] == 1){
319         $flag.= "D";
320       }
321       if (isset($_POST['place_on_kicker']) && $_POST['place_on_kicker'] == 1){
322         $flag.= "L";
323       }
324       if (isset($_POST['place_in_startmenu']) && $_POST['place_in_startmenu'] == 1){
325         $flag.= "M";
326       }
327       if (isset($_POST['overwrite_config']) && $_POST['overwrite_config'] == 1){
328         $flag.= "O";
329       }
330       if ($this->acl_is_writeable("gosaApplicationFlags")){
331         $this->gosaApplicationFlags= "[$flag]";
332       }
334       /* Remove current picture */
335       if(isset($_POST['remove_picture'])){
336         $this->set_picture("");
337       }
339       /* Check for picture upload */
340       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
342         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
343           print_red (_("The specified picture has not been uploaded correctly."));
344         }
346         if (!function_exists("imagick_blob2image")){
347           /* Get temporary file name for conversation */
348           $fname = tempnam ("/tmp", "GOsa");
350           /* Open file and write out photoData */
351           $fp = fopen ($fname, "w");
352           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
353           fclose ($fp);
355           /* Build conversation query. Filename is generated automatically, so
356              we do not need any special security checks. Exec command and save
357              output. For PHP safe mode, you'll need a configuration which respects
358              image magick as executable... */
359           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
360           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
362           /* Read data written by convert */
363           $output= "";
364           $sh= popen($query, 'r');
365           while (!feof($sh)){
366             $output.= fread($sh, 4096);
367           }
368           pclose($sh);
370           unlink($fname);       
371         } else {
373           /* Load the new uploaded Photo */
374           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
375             print_red(_("Can't access uploaded image."));
376           }
378           /* Resizing image to 147x200 and blur */
379           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
380             print_red(_("Uploaded image could not be resized, possilby the image magick extension is missing."));
381           }
383           /* Converting image to JPEG */
384           if(!imagick_convert($handle,"PNG")) {
385             print_red(_("Could not convert image to png, possilby the image magick extension is missing."));
386           }
388           if(!imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
389             print_red(sprintf(_("Could not save uploaded image to %s."),$_FILES['picture_file']['tmp_name']));
390           }
392           imagick_free($handle);
393         }
395         /* Activate new picture */
396         $this->set_picture($_FILES['picture_file']['tmp_name']);
397       } 
399       if(!$this->isReleaseApplikation){
400         $tmp = $this->get_allowed_bases();
401         if(isset($_POST['base'])){
402           if(isset($tmp[$_POST['base']])){
403             $this->base= $_POST['base'];
404           }
405         }
406       }
407     }
408   }
411   /* Check values */
412   function check()
413   {
414     /* Call common method to give check the hook */
415     $message= plugin::check();
417     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
418       $message[]=(_("Specified execute path must start with '/'."));
419     }
421     /* Permissions for that base? */
422     if ($this->base != ""){
423       $new_dn= "cn=".$this->cn.",".get_ou('applicationou').$this->base;
424     } else {
425       $new_dn= $this->dn;
426     }
429     if($this->dn == "new"){
430       $this->set_acl_base($this->base);
431     }
433     /* All required fields are set? */
434     if ($this->cn == ""){
435       $message[]= _("Required field 'Name' is not filled.");
436     }
438     if(preg_match("/[^a-z0-9]/",$this->cn))     {
439       $message[]=_("Invalid character in application name. Only a-z 0-9 are allowed.");
440     }
442     if ($this->gosaApplicationExecute == ""){
443       $message[]= _("Required field 'Execute' is not filled.");
444     }
446     /* Check for existing application */
447     $ldap= $this->config->get_ldap_link();
448     $ldap->cd($this->config->current["BASE"]);
450     $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
451     $appfilter = session::get('appfilter');
452     if((!empty($tmp)) && (isset($appfilter['release']))){
453       $baseDn = str_replace($this->config->current['BASE'],$this->base,$appfilter['release']);
454       $baseDn = preg_replace("/".get_ou('applicationou').".*/",get_ou('applicationou').$this->base,$appfilter['release']);
455       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$baseDn,array("cn"));
456       if($ldap->count()){
457         $attrs = $ldap->fetch();
458         if($this->dn != $attrs['dn']) {
459           $message[]= _("There's already an application with this 'Name'.");
460         }
461       }
462     }else{
463       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",get_ou('applicationou').$this->base,array("cn"));
464       if ($ldap->count()){
465         $attrs = $ldap->fetch();
466         if($this->dn != $attrs['dn']) {
467           $message[]= _("There's already an application with this 'Name'.");
468         }
469       }
470     }
471     return $message;
472   }
475   /* Save to LDAP */
476   function save()
477   {
478     /* Get application script without header part, to check if we must save the script itself */
479     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
481     plugin::save();
482     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
484     /* Write back to ldap */
485     $ldap= $this->config->get_ldap_link();
486     $ldap->cat($this->dn, array('dn'));
488     $a= $ldap->fetch();
489     if (count($a)){
491       /* Remove gotoLogonScript if it is empty */
492       if(empty($script))    {
493         $this->attrs['gotoLogonScript'] = array();
494       }
496       $ldap->cd($this->dn);
497       $this->cleanup();
498       $ldap->modify ($this->attrs); 
499       $this->handle_post_events("modify");
500       new log("modify","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
501     } else {
502       
503       /* Remove gotoLogonScript if it is empty */
504       if(empty($script))    {
505         unset($this->attrs['gotoLogonScript']);
506       }
508       $ldap->cd($this->config->current['BASE']);
509       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
510       $ldap->cd($this->dn);
511       $ldap->add($this->attrs);
512       new log("create","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
513       $this->handle_post_events("add");
514     }
515     show_ldap_error($ldap->get_error(), sprintf(_("Saving of application with dn '%s' failed."),$this->dn));
516   }
518   function set_picture($filename)
519   {
520     if (!is_file($filename)){
521       $filename= "./images/default_icon.png";
522       $this->gosaApplicationIcon= "*removed*";
523     }
525     if (file_exists($filename)){
526       $fd = fopen ($filename, "rb");
527       $this->iconData= fread ($fd, filesize ($filename));
528       session::set('binary',$this->iconData);
529       session::set('binarytype',"image/jpeg");
530       $this->gosaApplicationIcon= $this->iconData;
532       fclose ($fd);
533     }
534   }
536   function getCopyDialog()
537   {
538     $vars = array("cn");
540     $str ="<h2>"._("Application settings")."</h2>
541       <table>
542       <tr>
543       <td>".
544       _("Application name"). 
545       "</td>  
546       <td>
547       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
548       value='".$this->cn."' 
549       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
550       </td>
551       </tr>
552       </table>";
553     $ret = array();
554     $ret['status'] = "";
555     $ret['string'] = $str;
556     return($ret);
557   }
559   function saveCopyDialog()
560   {
561     if(isset($_POST['cn'])){
562       $this->cn = $_POST['cn'];
563     }
564   }
567   function PrepareForCopyPaste($source)
568   {
569     plugin::PrepareForCopyPaste($source);
570     $source_o = new application($this->config,$source['dn']);
571     $this->gosaApplicationIcon = $source_o->gosaApplicationIcon;     
572   }
575   /* Return plugin informations for acl handling
576       #FIXME FAIscript seams to ununsed within this class... */
577   static function plInfo()
578   {
579     return (array(
580           "plShortName"   => _("Generic"),
581           "plDescription" => _("Application generic"),
582           "plSelfModify"  => FALSE,
583           "plDepends"     => array(),
584           "plPriority"    => 0,
585           "plSection"     => array("administration"),
586           "plCategory"    => array("application" => array("description"  => _("Application"),
587                                                           "objectClass"  => "gosaApplication")),
588           "plProvidedAcls"=> array(
589             "cn"                => _("Name"),
590             "base"              => _("Base"),
591             "description"       => _("Description"),
592             "gosaApplicationExecute"  => _("Execute"),
593             "gosaApplicationName"     => _("Name"),
594             "gosaApplicationIcon"     => _("Icon"),
595             "gosaApplicationFlags"    => _("Flag"),
596             "gotoLogonScript"         => _("Script content"),
598             "exec_for_groupmembers" => _("Only executable for members"),              // G
599             "place_on_desktop"      => _("Place icon on members desktop"),            // D
600             "place_on_kicker"       => _("Place entry in members launch bar"),        // L
601             "place_in_startmenu"    => _("Place entry in members startmenu"),         // M
602             "overwrite_config"      => _("Replace user configuration on startup"))  // O
603             ));
604   }
606 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
607 ?>