Code

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