Code

Updated applicationGeneric
[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         msgPool::noValidExtension(_("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       msg_dialog::display(_("Error"), sprintf(_("Cannot remove application - it is still in use by these objects: %s"), "<br>".msgPool::buildList($found)), ERROR_DIALOG);
265       return(FALSE);
266     }
268     $ldap->rmDir($this->dn);
269     new log("remove","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
270     if (!$ldap->success()){
271       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()), ERROR_DIALOG);
272     }
274     /* Optionally execute a command after we're done */
275     $this->handle_post_events("remove");
277     /* Delete references to object groups */
278     $ldap->cd ($this->config->current['BASE']);
279     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
280     while ($ldap->fetch()){
281       $og= new ogroup($this->config, $ldap->getDN());
282       unset($og->member[$this->dn]);
283       $og->save ();
284       if (!$ldap->success()){
285         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
286       }
287     }
288   }
291   /* Save data to object */
292   function save_object()
293   {
294     if (isset($_POST['cn'])){
296       /* Create a base backup and reset the
297          base directly after calling plugin::save_object();
298          Base will be set seperatly a few lines below */
299       $base_tmp = $this->base;
300       plugin::save_object();
301       $this->base = $base_tmp;
303       /* Save attributes */
304       parent::save_object();
306       /* Save application flags */
307       $flag= "";
308       if (isset($_POST['exec_for_groupmembers']) && $_POST['exec_for_groupmembers'] == 1){
309         $flag.= "G";
310       }
311       if (isset($_POST['place_on_desktop']) && $_POST['place_on_desktop'] == 1){
312         $flag.= "D";
313       }
314       if (isset($_POST['place_on_kicker']) && $_POST['place_on_kicker'] == 1){
315         $flag.= "L";
316       }
317       if (isset($_POST['place_in_startmenu']) && $_POST['place_in_startmenu'] == 1){
318         $flag.= "M";
319       }
320       if (isset($_POST['overwrite_config']) && $_POST['overwrite_config'] == 1){
321         $flag.= "O";
322       }
323       if ($this->acl_is_writeable("gosaApplicationFlags")){
324         $this->gosaApplicationFlags= "[$flag]";
325       }
327       /* Remove current picture */
328       if(isset($_POST['remove_picture'])){
329         $this->set_picture("");
330       }
332       /* Check for picture upload */
333       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
335         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
336           msg_dialog::display(_("Error"), msgPool::incorrectUpload(), ERROR_DIALOG);
337         }
339         if (!function_exists("imagick_blob2image")){
340           /* Get temporary file name for conversation */
341           $fname = tempnam ("/tmp", "GOsa");
343           /* Open file and write out photoData */
344           $fp = fopen ($fname, "w");
345           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
346           fclose ($fp);
348           /* Build conversation query. Filename is generated automatically, so
349              we do not need any special security checks. Exec command and save
350              output. For PHP safe mode, you'll need a configuration which respects
351              image magick as executable... */
352           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
353           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
355           /* Read data written by convert */
356           $output= "";
357           $sh= popen($query, 'r');
358           while (!feof($sh)){
359             $output.= fread($sh, 4096);
360           }
361           pclose($sh);
363           unlink($fname);       
364         } else {
366           /* Load the new uploaded Photo */
367           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
368             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("no read permission")), ERROR_DIALOG);
369           }
371           /* Resizing image to 147x200 and blur */
372           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
373             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot resize image")), ERROR_DIALOG);
374           }
376           /* Converting image to JPEG */
377           if(!imagick_convert($handle,"PNG")) {
378             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot convert image")), ERROR_DIALOG);
379           }
381           if(!imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
382             msg_dialog::display(_("Error"), msgPool::incorrectUpload(sprintf(_("cannot save image to '%s'"), $_FILES['picture_file']['tmp_name'])), ERROR_DIALOG);
383           }
385           imagick_free($handle);
386         }
388         /* Activate new picture */
389         $this->set_picture($_FILES['picture_file']['tmp_name']);
390       } 
392       if(!$this->isReleaseApplikation){
393         $tmp = $this->get_allowed_bases();
394         if(isset($_POST['base'])){
395           if(isset($tmp[$_POST['base']])){
396             $this->base= $_POST['base'];
397           }
398         }
399       }
400     }
401   }
404   /* Check values */
405   function check()
406   {
407     /* Call common method to give check the hook */
408     $message= plugin::check();
410     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
411       $message[]=msgPool::invalid(_("Execute path"),"","","/some/path");
412     }
414     /* Permissions for that base? */
415     if ($this->base != ""){
416       $new_dn= "cn=".$this->cn.",".get_ou('applicationou').$this->base;
417     } else {
418       $new_dn= $this->dn;
419     }
422     if($this->dn == "new"){
423       $this->set_acl_base($this->base);
424     }
426     /* All required fields are set? */
427     if ($this->cn == ""){
428       $message[]= msgPool::required(_("Name"));
429     }
431     if(preg_match("/[^a-z0-9]/",$this->cn))     {
432       $message[]=msgPool::invalid(_("Name"),$this->cn,"/^[a-z0-9]*$/");
433     }
435     if ($this->gosaApplicationExecute == ""){
436       $message[]= msgPool::required(_("Execute"));
437     }
439     /* Check for existing application */
440     $ldap= $this->config->get_ldap_link();
441     $ldap->cd($this->config->current["BASE"]);
443     $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
444     $appfilter = session::get('appfilter');
445     if((!empty($tmp)) && (isset($appfilter['release']))){
446       $baseDn = str_replace($this->config->current['BASE'],$this->base,$appfilter['release']);
447       $baseDn = preg_replace("/".get_ou('applicationou').".*/",get_ou('applicationou').$this->base,$appfilter['release']);
448       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$baseDn,array("cn"));
449       if($ldap->count()){
450         $attrs = $ldap->fetch();
451         if($this->dn != $attrs['dn']) {
452           $message[]= msgPool::duplicated("cn");
453         }
454       }
455     }else{
456       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",get_ou('applicationou').$this->base,array("cn"));
457       if ($ldap->count()){
458         $attrs = $ldap->fetch();
459         if($this->dn != $attrs['dn']) {
460           $message[]= msgPool::duplicated("cn");
461         }
462       }
463     }
464     return $message;
465   }
468   /* Save to LDAP */
469   function save()
470   {
471     /* Get application script without header part, to check if we must save the script itself */
472     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
474     plugin::save();
475     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
477     /* Write back to ldap */
478     $ldap= $this->config->get_ldap_link();
479     $ldap->cat($this->dn, array('dn'));
481     $a= $ldap->fetch();
482     if (count($a)){
484       /* Remove gotoLogonScript if it is empty */
485       if(empty($script))    {
486         $this->attrs['gotoLogonScript'] = array();
487       }
489       $ldap->cd($this->dn);
490       $this->cleanup();
491       $ldap->modify ($this->attrs); 
492       $this->handle_post_events("modify");
493       new log("modify","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
494     } else {
495       
496       /* Remove gotoLogonScript if it is empty */
497       if(empty($script))    {
498         unset($this->attrs['gotoLogonScript']);
499       }
501       $ldap->cd($this->config->current['BASE']);
502       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
503       $ldap->cd($this->dn);
504       $ldap->add($this->attrs);
505       new log("create","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
506       $this->handle_post_events("add");
507     }
508     if (!$ldap->success()){
509       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
510     }
511   }
513   function set_picture($filename)
514   {
515     if (!is_file($filename)){
516       $filename= "./images/default_icon.png";
517       $this->gosaApplicationIcon= "*removed*";
518     }
520     if (file_exists($filename)){
521       $fd = fopen ($filename, "rb");
522       $this->iconData= fread ($fd, filesize ($filename));
523       session::set('binary',$this->iconData);
524       session::set('binarytype',"image/jpeg");
525       $this->gosaApplicationIcon= $this->iconData;
527       fclose ($fd);
528     }
529   }
531   function getCopyDialog()
532   {
533     $vars = array("cn");
535     $str ="<h2>"._("Application settings")."</h2>
536       <table>
537       <tr>
538       <td>".
539       _("Application name"). 
540       "</td>  
541       <td>
542       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
543       value='".$this->cn."' 
544       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
545       </td>
546       </tr>
547       </table>";
548     $ret = array();
549     $ret['status'] = "";
550     $ret['string'] = $str;
551     return($ret);
552   }
554   function saveCopyDialog()
555   {
556     if(isset($_POST['cn'])){
557       $this->cn = $_POST['cn'];
558     }
559   }
562   function PrepareForCopyPaste($source)
563   {
564     plugin::PrepareForCopyPaste($source);
565     $source_o = new application($this->config,$source['dn']);
566     $this->gosaApplicationIcon = $source_o->gosaApplicationIcon;     
567   }
570   /* Return plugin informations for acl handling
571       #FIXME FAIscript seams to ununsed within this class... */
572   static function plInfo()
573   {
574     return (array(
575           "plShortName"   => _("Generic"),
576           "plDescription" => _("Application generic"),
577           "plSelfModify"  => FALSE,
578           "plDepends"     => array(),
579           "plPriority"    => 0,
580           "plSection"     => array("administration"),
581           "plCategory"    => array("application" => array("description"  => _("Application"),
582                                                           "objectClass"  => "gosaApplication")),
583           "plProvidedAcls"=> array(
584             "cn"                => _("Name"),
585             "base"              => _("Base"),
586             "description"       => _("Description"),
587             "gosaApplicationExecute"  => _("Execute"),
588             "gosaApplicationName"     => _("Name"),
589             "gosaApplicationIcon"     => _("Icon"),
590             "gosaApplicationFlags"    => _("Flag"),
591             "gotoLogonScript"         => _("Script content"),
593             "exec_for_groupmembers" => _("Only executable for members"),              // G
594             "place_on_desktop"      => _("Place icon on members desktop"),            // D
595             "place_on_kicker"       => _("Place entry in members launch bar"),        // L
596             "place_in_startmenu"    => _("Place entry in members startmenu"),         // M
597             "overwrite_config"      => _("Replace user configuration on startup"))  // O
598             ));
599   }
601 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
602 ?>