Code

cbdd26c7abe9d52ad0a12cf5cd6801fe10cc0d94
[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   }
76   function generateTemplate(){
77     $str= "# This code is part of GOsa (https://gosa.gonicus.de)\n#\n";
79     $values = array();
80     $names      = array();
81     if($this->parent->by_object['applicationParameters']->is_account){
82       $names = $this->parent->by_object['applicationParameters']->option_name;
83       $values = $this->parent->by_object['applicationParameters']->option_value;
84     }
86     if (count($names)){
87       $str .="# This plugin handles these environment variables:\n";
88     } else {
89       $str .="# This plugin handles no environment variables.\n";
90     }
92     foreach($names as $index => $name){
94       // Fix length
95       for($i = strlen($name) ; $i < 30 ; $i++){
96         $name= $name." ";
97       }
98       if((isset($values[$index]))&&(!empty($values[$index]))){
99         $str.= "# ".$name."\t(e.g. '".$values[$index]."')\n";
100       }else{
101         $str.= "# ".$name."\t("._("no example").")\n";
102       }
103     }
104     $str .= "#\n".
105       "# Don't remove the following tag, it is used for header update.\n".
106       "### END HEADER ###";
108     return($str);
109   }
111   function execute()
112   {
113     /* Call parent execute */
114     plugin::execute();
116     $smarty= get_smarty();
118     $tmp = $this->plInfo();
119     foreach($tmp['plProvidedAcls'] as $name => $translation){
120       $smarty->assign($name."ACL",$this->getacl($name));
121     }
122  
123     $baseACL = $this->getacl("base");
124     if(!$this->acl_is_moveable()) {
125       $baseACL = preg_replace("/w/","",$baseACL);
126     }
127     $smarty->assign("baseACL",          $baseACL);
129     /* Do we represent a valid group? */
130     if (!$this->is_account && $this->parent == NULL){
131       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
132         _("This 'dn' is no application.")."</b>";
133       return ($display);
134     }
136     /* Download requested */
137     foreach($_POST as $name => $value){
138       if(preg_match("/^downloadScript/",$name)){
139         $_SESSION['binary']       = $this->gotoLogonScript;
140         $_SESSION['binarytype']   = "octet-stream";
141         $_SESSION['binaryfile']   = $this->cn.".gosaApplication";
142         header("location: getbin.php ");
143         exit();
144       }
145     }
147     /* Reassign picture data, sometimes its corrupt cause we started a download of application scripts */
148     $_SESSION['binary']     = $this->iconData;
149     $_SESSION['binarytype'] = "image/jpeg";
150     
151     $smarty->assign("rand", rand(0, 10000));
152     $head = $this->generateTemplate();
153     $this->gotoLogonScript= $this->generateTemplate().preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
155     if((isset($_POST['upLoad']))&&(isset($_FILES['ScriptFile']))){
156       $str = file_get_contents($_FILES['ScriptFile']['tmp_name']);
157       $this->gotoLogonScript = $str;
158     }
160     /* Fill templating stuff */
161     $smarty->assign("cn", $this->cn);
162     $smarty->assign("bases", $this->get_allowed_bases());
163     if ($this->dn == "new"){
164       $smarty->assign("selectmode", "");
165       $smarty->assign("namemode", "");
166     } else {
167       $smarty->assign("namemode", "readonly");
168       $smarty->assign("selectmode", "disabled");
169     }
170     
171     /* Base select dialog */
172     $once = true;
173     foreach($_POST as $name => $value){
174       if(preg_match("/^chooseBase/",$name) && $once){
175         $once = false;
176         $this->dialog = new baseSelectDialog($this->config,$this,$this->get_allowed_bases());
177         $this->dialog->setCurrentBase($this->base);
178       }
179     }
181     /* Dialog handling */
182     if(is_object($this->dialog)){
183       /* Must be called before save_object */
184       $this->dialog->save_object();
186       if($this->dialog->isClosed()){
187         $this->dialog = false;
188       }elseif($this->dialog->isSelected()){
189         $this->base = $this->dialog->isSelected();
190         $this->dialog= false;
191       }else{
192         return($this->dialog->execute());
193       }
194     }
196     /* Get random number for pictures */
197     srand((double)microtime()*1000000);
198     $smarty->assign("rand", rand(0, 10000));
200     /* Variables */
201     foreach(array("description", "gosaApplicationExecute", "gosaApplicationName","cn") as $val){
202       $smarty->assign($val, $this->$val);
203     }
205     /* Checkboxes */
206     foreach (array("G" => "exec_for_groupmembers", "O" => "overwrite_config",
207           "L" => "place_on_kicker",
208           "D" => "place_on_desktop", "M" => "place_in_startmenu") as $key => $val){
209       if (preg_match("/$key/", $this->gosaApplicationFlags)){
210         $smarty->assign("$val", "checked");
211       } else {
212         $smarty->assign("$val", "");
213       }
214     }
216     $smarty->assign("isReleaseApplikation" , $this->isReleaseApplikation);
217     $smarty->assign("gotoLogonScript",htmlentities($this->gotoLogonScript, ENT_COMPAT, 'UTF-8'));
218     $smarty->assign("base_select", $this->base);
219     /* Show main page */
220     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
221   }
224   function remove_from_parent()
225   {
226     $ldap= $this->config->get_ldap_link();
227     $ldap->rmDir($this->dn);
228     show_ldap_error($ldap->get_error(), sprintf(_("Removing of application with dn '%s' failed."),$this->dn));
230     /* Optionally execute a command after we're done */
231     $this->handle_post_events("remove");
233     /* Delete references to object groups */
234     $ldap->cd ($this->config->current['BASE']);
235     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
236     while ($ldap->fetch()){
237       $og= new ogroup($this->config, $ldap->getDN());
238       unset($og->member[$this->dn]);
239       $og->save ();
240       show_ldap_error($ldap->get_error(), sprintf(_("Removing application from objectgroup '%s' failed"), $og->dn));
241     }
242     $ldap->search ("(&(objectClass=posixGroup)(gosaMemberApplication=".$this->cn."))", array("cn"));
243     while ($attrs= $ldap->fetch()){
244       $ag= new appgroup($this->config, $ldap->getDN());
245       $ag->removeApp($this->cn);
246       $ag->save ();
247       show_ldap_error($ldap->get_error(), sprintf(_("Removing application from group '%s' failed"), $ag->dn));
248     }
250   }
253   /* Save data to object */
254   function save_object()
255   {
256     if($this->isReleaseApplikation){
257       $tmpBase = $this->base;
258     } 
259  
260     if (isset($_POST['cn'])){
262       /* Save attributes */
263       parent::save_object();
265       /* Save application flags */
266       $flag= "";
267       if (isset($_POST['exec_for_groupmembers']) && $_POST['exec_for_groupmembers'] == 1){
268         $flag.= "G";
269       }
270       if (isset($_POST['place_on_desktop']) && $_POST['place_on_desktop'] == 1){
271         $flag.= "D";
272       }
273       if (isset($_POST['place_on_kicker']) && $_POST['place_on_kicker'] == 1){
274         $flag.= "L";
275       }
276       if (isset($_POST['place_in_startmenu']) && $_POST['place_in_startmenu'] == 1){
277         $flag.= "M";
278       }
279       if (isset($_POST['overwrite_config']) && $_POST['overwrite_config'] == 1){
280         $flag.= "O";
281       }
282       if ($this->acl_is_writeable("gosaApplicationFlags")){
283         $this->gosaApplicationFlags= "[$flag]";
284       }
286       /* Remove current picture */
287       if(isset($_POST['remove_picture'])){
288         $this->set_picture("");
289       }
291       /* Check for picture upload */
292       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
294         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
295           print_red (_("The specified picture has not been uploaded correctly."));
296         }
298         if (!function_exists("imagick_blob2image")){
299           /* Get temporary file name for conversation */
300           $fname = tempnam ("/tmp", "GOsa");
302           /* Open file and write out photoData */
303           $fp = fopen ($fname, "w");
304           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
305           fclose ($fp);
307           /* Build conversation query. Filename is generated automatically, so
308              we do not need any special security checks. Exec command and save
309              output. For PHP safe mode, you'll need a configuration which respects
310              image magick as executable... */
311           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
312           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
314           /* Read data written by convert */
315           $output= "";
316           $sh= popen($query, 'r');
317           while (!feof($sh)){
318             $output.= fread($sh, 4096);
319           }
320           pclose($sh);
322           unlink($fname);       
323         } else {
325           /* Load the new uploaded Photo */
326           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
327             gosa_log("Can't Load image");
328           }
330           /* Resizing image to 147x200 and blur */
331           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
332             gosa_log("imagick_resize failed");
333           }
335           /* Converting image to JPEG */
336           if(!imagick_convert($handle,"PNG")) {
337             gosa_log("Can't Convert to PNG");
338           }
340           if(imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
341             gosa_log("can't write to specified folder");
342           }
344           imagick_free($handle);
345         }
347         /* Activate new picture */
348         $this->set_picture($_FILES['picture_file']['tmp_name']);
349       } 
351       if(isset($_POST['base'])){
352         $this->base= $_POST['base'];
353       }
354     }
356     if($this->isReleaseApplikation){
357       $this->base = $tmpBase;
358     }
359   }
362   /* Check values */
363   function check()
364   {
365     /* Call common method to give check the hook */
366     $message= plugin::check();
368     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
369       $message[]=(_("Specified execute path must start with '/'."));
370     }
372     /* Permissions for that base? */
373     if ($this->base != ""){
374       $new_dn= "cn=".$this->cn.",ou=apps,".$this->base;
375     } else {
376       $new_dn= $this->dn;
377     }
380     if($this->dn == "new"){
381       $this->set_acl_base($this->base);
382     }
384     /* Check acls to create a new application here  */
385     $ui= get_userinfo();
386     if (!$this->acl_is_createable() && $this->dn == "new"){
387       $message[]= _("You have no permissions to create a application on this 'Base'.");
388     }
390     /* All required fields are set? */
391     if ($this->cn == ""){
392       $message[]= _("Required field 'Name' is not filled.");
393     }
395     if(preg_match("/[^a-z0-9]/",$this->cn))     {
396       $message[]=_("Invalid character in application name. Only a-z 0-9 are allowed.");
397     }
399     if ($this->gosaApplicationExecute == ""){
400       $message[]= _("Required field 'Execute' is not filled.");
401     }
403     /* Check for existing application */
404     $ldap= $this->config->get_ldap_link();
405     $ldap->cd($this->config->current["BASE"]);
407     $tmp = search_config($this->config->data,"faiManagement","CLASS");
408     if((!empty($tmp)) && (isset($_SESSION['appfilter']['release']))){
409       $baseDn = str_replace($this->config->current['BASE'],$this->base,$_SESSION['appfilter']['release']);
410       $baseDn = preg_replace("/ou=apps,.*/","ou=apps,".$this->base,$_SESSION['appfilter']['release']);
411       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$baseDn,array("cn"));
412       if($ldap->count()){
413         $attrs = $ldap->fetch();
414         if($this->dn != $attrs['dn']) {
415           $message[]= _("There's already an application with this 'Name'.");
416         }
417       }
418     }else{
419       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))","ou=apps,".$this->base,array("cn"));
420       if ($ldap->count()){
421         $attrs = $ldap->fetch();
422         if($this->dn != $attrs['dn']) {
423           $message[]= _("There's already an application with this 'Name'.");
424         }
425       }
426     }
427     return $message;
428   }
431   /* Save to LDAP */
432   function save()
433   {
434     /* Get application script without header part, to check if we must save the script itself */
435     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
437     plugin::save();
438     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
440     /* Write back to ldap */
441     $ldap= $this->config->get_ldap_link();
442     $ldap->cat($this->dn, array('dn'));
444     $a= $ldap->fetch();
445     if (count($a)){
447       /* Remove gotoLogonScript if it is empty */
448       if(empty($script))    {
449         $this->attrs['gotoLogonScript'] = array();
450       }
452       $ldap->cd($this->dn);
453       $this->cleanup();
454       $ldap->modify ($this->attrs); 
455       $this->handle_post_events("modify");
456     } else {
457       
458       /* Remove gotoLogonScript if it is empty */
459       if(empty($script))    {
460         unset($this->attrs['gotoLogonScript']);
461       }
463       $ldap->cd($this->config->current['BASE']);
464       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
465       $ldap->cd($this->dn);
466       $ldap->add($this->attrs);
467       $this->handle_post_events("add");
468     }
469     show_ldap_error($ldap->get_error(), sprintf(_("Saving of application with dn '%s' failed."),$this->dn));
470   }
472   function set_picture($filename)
473   {
474     if (!is_file($filename)){
475       $filename= "./images/default_icon.png";
476       $this->gosaApplicationIcon= "*removed*";
477     }
479     if (file_exists($filename)){
480       $fd = fopen ($filename, "rb");
481       $this->iconData= fread ($fd, filesize ($filename));
482       $_SESSION['binary']= $this->iconData;
483       $_SESSION['binarytype']= "image/jpeg";
484       $this->gosaApplicationIcon= $this->iconData;
486       fclose ($fd);
487     }
488   }
490   function getCopyDialog()
491   {
492     $vars = array("cn");
494     $str ="<h2>"._("Application settings")."</h2>
495       <table>
496       <tr>
497       <td>".
498       _("Application name"). 
499       "</td>  
500       <td>
501       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
502       value='".$this->cn."' 
503       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
504       </td>
505       </tr>
506       </table>";
507     $ret = array();
508     $ret['status'] = "";
509     $ret['string'] = $str;
510     return($ret);
511   }
513   function saveCopyDialog()
514   {
515     if(isset($_POST['cn'])){
516       $this->cn = $_POST['cn'];
517     }
518   }
521   /* Return plugin informations for acl handling
522       #FIXME FAIscript seams to ununsed within this class... */
523   function plInfo()
524   {
525     return (array(
526           "plShortName"   => _("Generic"),
527           "plDescription" => _("Application generic"),
528           "plSelfModify"  => FALSE,
529           "plDepends"     => array(),
530           "plPriority"    => 0,
531           "plSection"     => array("administration"),
532           "plCategory"    => array("application" => array("description"  => _("Application"),
533                                                           "objectClass"  => "gosaApplication")),
534           "plProvidedAcls"=> array(
535             "cn"                => _("Name"),
536             "base"              => _("Base"),
537             "description"       => _("Description"),
538             "gosaApplicationExecute"  => _("Execute"),
539             "gosaApplicationName"     => _("Name"),
540             "gosaApplicationIcon"     => _("Icon"),
541             "gosaApplicationFlags"    => _("Flag"),
542             "gotoLogonScript"         => _("Script content"),
544             "exec_for_groupmembers" => _("Only executable for members"),              // G
545             "place_on_desktop"      => _("Place icon on members desktop"),            // D
546             "place_on_kicker"       => _("Place entry in members launch bar"),        // L
547             "place_in_startmenu"    => _("Place entry in members startmenu"),         // M
548             "overwrite_config"      => _("Replace user configuration on startup"))  // O
549             ));
550   }
552 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
553 ?>