Code

Added sorting
[gosa.git] / plugins / admin / applications / class_applicationGeneric.inc
1 <?php
2 class application extends plugin
3 {
4   /* CLI vars */
5   var $cli_summary= "Handling of GOsa's application object";
6   var $cli_description= "Some longer text\nfor help";
7   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
9   /* application attributes */
10   var $cn= "";
11   var $description= "";
12   var $base= "";
13   var $gosaApplicationExecute= "";
14   var $gosaApplicationName= "";
15   var $gosaApplicationFlags= "";
16   var $gosaApplicationIcon= "";
17   var $gotoLogonScript  ="";
18   var $iconData;
20   /* Headpage attributes */
21   var $last_sorting= "invalid";
22   var $applications= array();
24   /* attribute list for save action */
25   var $attributes= array("cn", "description", "gosaApplicationExecute", "gosaApplicationName","gosaApplicationIcon",
26       "gosaApplicationFlags","gotoLogonScript");
27   var $objectclasses= array("top", "gosaApplication");
29   var $isReleaseApplikation = false;
31   function application ($config, $dn= NULL, $parent= NULL)
32   {
33     plugin::plugin ($config, $dn, $parent);
35     $tmp = search_config($this->config->data,"faiManagement","CLASS");
36     if(!empty($tmp)) {
37       if(!preg_match("/^ou=apps,/",$_SESSION['appfilter']['release'])){
38         $this->isReleaseApplikation = true;  
39       }
40     }
42     /* Load icon */
43     $ldap= $config->get_ldap_link();
44     if ($dn != 'new'){
45       $this->iconData= $ldap->get_attribute($dn, "gosaApplicationIcon");
46       $this->saved_attributes['gosaApplicationIcon'] = $this->iconData;
47     }
48     if ($this->iconData == ""){
49       $this->set_picture("");
50     }
51     $_SESSION['binary']= $this->iconData;
52     $_SESSION['binarytype']= "image/jpeg";
53     $this->gosaApplicationIcon= $this->iconData;
55     /* This is always an account */
56     $this->is_account= TRUE;
58     if ($this->dn == "new"){
59       if(isset($_SESSION['CurrentMainBase'])){
60         $this->base= $_SESSION['CurrentMainBase'];
61       }else{
62         $ui= get_userinfo();
63         $this->base= dn2base($ui->dn);
64       }
65     } else {
67       if($this->isReleaseApplikation){
68         $this->base = preg_replace("/^.*,ou=apps,/","",$this->dn);
69       }else{
70         $this->base= preg_replace ("/^[^,]+,[^,]+,/", "", $this->dn);
71       }
72     }
73       
74     if($this->is_account && $dn != "new"){
75       @log::log("view","application/".get_class($this),$this->dn);
76     }
77   }
80   function generateTemplate()
81   {
82     $str= "# This code is part of GOsa (https://gosa.gonicus.de)\n#\n";
84     $values = array();
85     $names      = array();
86     if($this->parent->by_object['applicationParameters']->is_account){
87       $names = $this->parent->by_object['applicationParameters']->option_name;
88       $values = $this->parent->by_object['applicationParameters']->option_value;
89     }
91     if (count($names)){
92       $str .="# This plugin handles these environment variables:\n";
93     } else {
94       $str .="# This plugin handles no environment variables.\n";
95     }
97     foreach($names as $index => $name){
99       // Fix length
100       for($i = strlen($name) ; $i < 30 ; $i++){
101         $name= $name." ";
102       }
103       if((isset($values[$index]))&&(!empty($values[$index]))){
104         $str.= "# ".$name."\t(e.g. '".$values[$index]."')\n";
105       }else{
106         $str.= "# ".$name."\t("._("no example").")\n";
107       }
108     }
109     $str .= "#\n".
110       "# Don't remove the following tag, it is used for header update.\n".
111       "### END HEADER ###";
113     return($str);
114   }
116   function execute()
117   {
118     /* Call parent execute */
119     plugin::execute();
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['binary']       = $this->gotoLogonScript;
139         $_SESSION['binarytype']   = "octet-stream";
140         $_SESSION['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['binary']     = $this->iconData;
148     $_SESSION['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     $ldap= $this->config->get_ldap_link();
231     $ldap->rmDir($this->dn);
232     @log::log("remove","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
233     show_ldap_error($ldap->get_error(), sprintf(_("Removing of application with dn '%s' failed."),$this->dn));
235     /* Optionally execute a command after we're done */
236     $this->handle_post_events("remove");
238     /* Delete references to object groups */
239     $ldap->cd ($this->config->current['BASE']);
240     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
241     while ($ldap->fetch()){
242       $og= new ogroup($this->config, $ldap->getDN());
243       unset($og->member[$this->dn]);
244       $og->save ();
245       show_ldap_error($ldap->get_error(), sprintf(_("Removing application from objectgroup '%s' failed"), $og->dn));
246     }
247     $ldap->search ("(&(objectClass=posixGroup)(gosaMemberApplication=".$this->cn."))", array("cn"));
248     while ($attrs= $ldap->fetch()){
249       $ag= new appgroup($this->config, $ldap->getDN());
250       $ag->removeApp($this->cn);
251       $ag->save ();
252       show_ldap_error($ldap->get_error(), sprintf(_("Removing application from group '%s' failed"), $ag->dn));
253     }
255   }
258   /* Save data to object */
259   function save_object()
260   {
261     if (isset($_POST['cn'])){
263       /* Create a base backup and reset the
264          base directly after calling plugin::save_object();
265          Base will be set seperatly a few lines below */
266       $base_tmp = $this->base;
267       plugin::save_object();
268       $this->base = $base_tmp;
270       /* Save attributes */
271       parent::save_object();
273       /* Save application flags */
274       $flag= "";
275       if (isset($_POST['exec_for_groupmembers']) && $_POST['exec_for_groupmembers'] == 1){
276         $flag.= "G";
277       }
278       if (isset($_POST['place_on_desktop']) && $_POST['place_on_desktop'] == 1){
279         $flag.= "D";
280       }
281       if (isset($_POST['place_on_kicker']) && $_POST['place_on_kicker'] == 1){
282         $flag.= "L";
283       }
284       if (isset($_POST['place_in_startmenu']) && $_POST['place_in_startmenu'] == 1){
285         $flag.= "M";
286       }
287       if (isset($_POST['overwrite_config']) && $_POST['overwrite_config'] == 1){
288         $flag.= "O";
289       }
290       if ($this->acl_is_writeable("gosaApplicationFlags")){
291         $this->gosaApplicationFlags= "[$flag]";
292       }
294       /* Remove current picture */
295       if(isset($_POST['remove_picture'])){
296         $this->set_picture("");
297       }
299       /* Check for picture upload */
300       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
302         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
303           print_red (_("The specified picture has not been uploaded correctly."));
304         }
306         if (!function_exists("imagick_blob2image")){
307           /* Get temporary file name for conversation */
308           $fname = tempnam ("/tmp", "GOsa");
310           /* Open file and write out photoData */
311           $fp = fopen ($fname, "w");
312           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
313           fclose ($fp);
315           /* Build conversation query. Filename is generated automatically, so
316              we do not need any special security checks. Exec command and save
317              output. For PHP safe mode, you'll need a configuration which respects
318              image magick as executable... */
319           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
320           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
322           /* Read data written by convert */
323           $output= "";
324           $sh= popen($query, 'r');
325           while (!feof($sh)){
326             $output.= fread($sh, 4096);
327           }
328           pclose($sh);
330           unlink($fname);       
331         } else {
333           /* Load the new uploaded Photo */
334           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
335             gosa_log("Can't Load image");
336           }
338           /* Resizing image to 147x200 and blur */
339           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
340             gosa_log("imagick_resize failed");
341           }
343           /* Converting image to JPEG */
344           if(!imagick_convert($handle,"PNG")) {
345             gosa_log("Can't Convert to PNG");
346           }
348           if(imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
349             gosa_log("can't write to specified folder");
350           }
352           imagick_free($handle);
353         }
355         /* Activate new picture */
356         $this->set_picture($_FILES['picture_file']['tmp_name']);
357       } 
359       if(!$this->isReleaseApplikation){
360         $tmp = $this->get_allowed_bases();
361         if(isset($_POST['base'])){
362           if(isset($tmp[$_POST['base']])){
363             $this->base= $_POST['base'];
364           }
365         }
366       }
367     }
368   }
371   /* Check values */
372   function check()
373   {
374     /* Call common method to give check the hook */
375     $message= plugin::check();
377     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
378       $message[]=(_("Specified execute path must start with '/'."));
379     }
381     /* Permissions for that base? */
382     if ($this->base != ""){
383       $new_dn= "cn=".$this->cn.",ou=apps,".$this->base;
384     } else {
385       $new_dn= $this->dn;
386     }
389     if($this->dn == "new"){
390       $this->set_acl_base($this->base);
391     }
393     /* All required fields are set? */
394     if ($this->cn == ""){
395       $message[]= _("Required field 'Name' is not filled.");
396     }
398     if(preg_match("/[^a-z0-9]/",$this->cn))     {
399       $message[]=_("Invalid character in application name. Only a-z 0-9 are allowed.");
400     }
402     if ($this->gosaApplicationExecute == ""){
403       $message[]= _("Required field 'Execute' is not filled.");
404     }
406     /* Check for existing application */
407     $ldap= $this->config->get_ldap_link();
408     $ldap->cd($this->config->current["BASE"]);
410     $tmp = search_config($this->config->data,"faiManagement","CLASS");
411     if((!empty($tmp)) && (isset($_SESSION['appfilter']['release']))){
412       $baseDn = str_replace($this->config->current['BASE'],$this->base,$_SESSION['appfilter']['release']);
413       $baseDn = preg_replace("/ou=apps,.*/","ou=apps,".$this->base,$_SESSION['appfilter']['release']);
414       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$baseDn,array("cn"));
415       if($ldap->count()){
416         $attrs = $ldap->fetch();
417         if($this->dn != $attrs['dn']) {
418           $message[]= _("There's already an application with this 'Name'.");
419         }
420       }
421     }else{
422       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))","ou=apps,".$this->base,array("cn"));
423       if ($ldap->count()){
424         $attrs = $ldap->fetch();
425         if($this->dn != $attrs['dn']) {
426           $message[]= _("There's already an application with this 'Name'.");
427         }
428       }
429     }
430     return $message;
431   }
434   /* Save to LDAP */
435   function save()
436   {
437     /* Get application script without header part, to check if we must save the script itself */
438     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
440     plugin::save();
441     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
443     /* Write back to ldap */
444     $ldap= $this->config->get_ldap_link();
445     $ldap->cat($this->dn, array('dn'));
447     $a= $ldap->fetch();
448     if (count($a)){
450       /* Remove gotoLogonScript if it is empty */
451       if(empty($script))    {
452         $this->attrs['gotoLogonScript'] = array();
453       }
455       $ldap->cd($this->dn);
456       $this->cleanup();
457       $ldap->modify ($this->attrs); 
458       $this->handle_post_events("modify");
459       @log::log("modify","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
460     } else {
461       
462       /* Remove gotoLogonScript if it is empty */
463       if(empty($script))    {
464         unset($this->attrs['gotoLogonScript']);
465       }
467       $ldap->cd($this->config->current['BASE']);
468       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
469       $ldap->cd($this->dn);
470       $ldap->add($this->attrs);
471       @log::log("create","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
472       $this->handle_post_events("add");
473     }
474     show_ldap_error($ldap->get_error(), sprintf(_("Saving of application with dn '%s' failed."),$this->dn));
475   }
477   function set_picture($filename)
478   {
479     if (!is_file($filename)){
480       $filename= "./images/default_icon.png";
481       $this->gosaApplicationIcon= "*removed*";
482     }
484     if (file_exists($filename)){
485       $fd = fopen ($filename, "rb");
486       $this->iconData= fread ($fd, filesize ($filename));
487       $_SESSION['binary']= $this->iconData;
488       $_SESSION['binarytype']= "image/jpeg";
489       $this->gosaApplicationIcon= $this->iconData;
491       fclose ($fd);
492     }
493   }
495   function getCopyDialog()
496   {
497     $vars = array("cn");
499     $str ="<h2>"._("Application settings")."</h2>
500       <table>
501       <tr>
502       <td>".
503       _("Application name"). 
504       "</td>  
505       <td>
506       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
507       value='".$this->cn."' 
508       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
509       </td>
510       </tr>
511       </table>";
512     $ret = array();
513     $ret['status'] = "";
514     $ret['string'] = $str;
515     return($ret);
516   }
518   function saveCopyDialog()
519   {
520     if(isset($_POST['cn'])){
521       $this->cn = $_POST['cn'];
522     }
523   }
526   /* Return plugin informations for acl handling
527       #FIXME FAIscript seams to ununsed within this class... */
528   function plInfo()
529   {
530     return (array(
531           "plShortName"   => _("Generic"),
532           "plDescription" => _("Application generic"),
533           "plSelfModify"  => FALSE,
534           "plDepends"     => array(),
535           "plPriority"    => 0,
536           "plSection"     => array("administration"),
537           "plCategory"    => array("application" => array("description"  => _("Application"),
538                                                           "objectClass"  => "gosaApplication")),
539           "plProvidedAcls"=> array(
540             "cn"                => _("Name"),
541             "base"              => _("Base"),
542             "description"       => _("Description"),
543             "gosaApplicationExecute"  => _("Execute"),
544             "gosaApplicationName"     => _("Name"),
545             "gosaApplicationIcon"     => _("Icon"),
546             "gosaApplicationFlags"    => _("Flag"),
547             "gotoLogonScript"         => _("Script content"),
549             "exec_for_groupmembers" => _("Only executable for members"),              // G
550             "place_on_desktop"      => _("Place icon on members desktop"),            // D
551             "place_on_kicker"       => _("Place entry in members launch bar"),        // L
552             "place_in_startmenu"    => _("Place entry in members startmenu"),         // M
553             "overwrite_config"      => _("Replace user configuration on startup"))  // O
554             ));
555   }
557 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
558 ?>